bf9ddaa6841c64fadff2145b41bf75a5ed59cc27
[fms.git] / libs / sqlite3 / sqlite3.c
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.5.4.  By combining all the individual C code files into this 
4 ** single large file, the entire code can be compiled as a one translation
5 ** unit.  This allows many compilers to do optimizations that would not be
6 ** possible if the files were compiled separately.  Performance improvements
7 ** of 5% are more are commonly seen when SQLite is compiled as a single
8 ** translation unit.
9 **
10 ** This file is all you need to compile SQLite.  To use SQLite in other
11 ** programs, you need this file and the "sqlite3.h" header file that defines
12 ** the programming interface to the SQLite library.  (If you do not have 
13 ** the "sqlite3.h" header file at hand, you will find a copy in the first
14 ** 3840 lines past this header comment.)  Additional code files may be
15 ** needed if you want a wrapper to interface SQLite with your choice of
16 ** programming language.  The code for the "sqlite3" command-line shell
17 ** is also in a separate file.  This file contains only code for the core
18 ** SQLite library.
19 **
20 ** This amalgamation was generated on 2007-12-14 17:40:56 UTC.
21 */
22 #define SQLITE_AMALGAMATION 1
23 #ifndef SQLITE_PRIVATE
24 # define SQLITE_PRIVATE static
25 #endif
26 #ifndef SQLITE_API
27 # define SQLITE_API
28 #endif
29 /************** Begin file sqliteInt.h ***************************************/
30 /*
31 ** 2001 September 15
32 **
33 ** The author disclaims copyright to this source code.  In place of
34 ** a legal notice, here is a blessing:
35 **
36 **    May you do good and not evil.
37 **    May you find forgiveness for yourself and forgive others.
38 **    May you share freely, never taking more than you give.
39 **
40 *************************************************************************
41 ** Internal interface definitions for SQLite.
42 **
43 ** @(#) $Id: sqliteInt.h,v 1.626 2007/12/13 03:45:08 drh Exp $
44 */
45 #ifndef _SQLITEINT_H_
46 #define _SQLITEINT_H_
47
48 /*
49 ** The macro unlikely() is a hint that surrounds a boolean
50 ** expression that is usually false.  Macro likely() surrounds
51 ** a boolean expression that is usually true.  GCC is able to
52 ** use these hints to generate better code, sometimes.
53 */
54 #if defined(__GNUC__)
55 # define likely(X)    __builtin_expect((X),1)
56 # define unlikely(X)  __builtin_expect((X),0)
57 #else
58 # define likely(X)    !!(X)
59 # define unlikely(X)  !!(X)
60 #endif
61
62
63 /*
64 ** These #defines should enable >2GB file support on Posix if the
65 ** underlying operating system supports it.  If the OS lacks
66 ** large file support, or if the OS is windows, these should be no-ops.
67 **
68 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
69 ** system #includes.  Hence, this block of code must be the very first
70 ** code in all source files.
71 **
72 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
73 ** on the compiler command line.  This is necessary if you are compiling
74 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
75 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
76 ** without this option, LFS is enable.  But LFS does not exist in the kernel
77 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
78 ** portability you should omit LFS.
79 **
80 ** Similar is true for MacOS.  LFS is only supported on MacOS 9 and later.
81 */
82 #ifndef SQLITE_DISABLE_LFS
83 # define _LARGE_FILE       1
84 # ifndef _FILE_OFFSET_BITS
85 #   define _FILE_OFFSET_BITS 64
86 # endif
87 # define _LARGEFILE_SOURCE 1
88 #endif
89
90
91 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
92 /************** Begin file sqliteLimit.h *************************************/
93 /*
94 ** 2007 May 7
95 **
96 ** The author disclaims copyright to this source code.  In place of
97 ** a legal notice, here is a blessing:
98 **
99 **    May you do good and not evil.
100 **    May you find forgiveness for yourself and forgive others.
101 **    May you share freely, never taking more than you give.
102 **
103 *************************************************************************
104 ** 
105 ** This file defines various limits of what SQLite can process.
106 **
107 ** @(#) $Id: sqliteLimit.h,v 1.5 2007/12/13 21:54:11 drh Exp $
108 */
109
110 /*
111 ** The maximum length of a TEXT or BLOB in bytes.   This also
112 ** limits the size of a row in a table or index.
113 **
114 ** The hard limit is the ability of a 32-bit signed integer
115 ** to count the size: 2^31-1 or 2147483647.
116 */
117 #ifndef SQLITE_MAX_LENGTH
118 # define SQLITE_MAX_LENGTH 1000000000
119 #endif
120
121 /*
122 ** This is the maximum number of
123 **
124 **    * Columns in a table
125 **    * Columns in an index
126 **    * Columns in a view
127 **    * Terms in the SET clause of an UPDATE statement
128 **    * Terms in the result set of a SELECT statement
129 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
130 **    * Terms in the VALUES clause of an INSERT statement
131 **
132 ** The hard upper limit here is 32676.  Most database people will
133 ** tell you that in a well-normalized database, you usually should
134 ** not have more than a dozen or so columns in any table.  And if
135 ** that is the case, there is no point in having more than a few
136 ** dozen values in any of the other situations described above.
137 */
138 #ifndef SQLITE_MAX_COLUMN
139 # define SQLITE_MAX_COLUMN 2000
140 #endif
141
142 /*
143 ** The maximum length of a single SQL statement in bytes.
144 ** The hard limit is 1 million.
145 */
146 #ifndef SQLITE_MAX_SQL_LENGTH
147 # define SQLITE_MAX_SQL_LENGTH 1000000
148 #endif
149
150 /*
151 ** The maximum depth of an expression tree. This is limited to 
152 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
153 ** want to place more severe limits on the complexity of an 
154 ** expression. A value of 0 (the default) means do not enforce
155 ** any limitation on expression tree depth.
156 */
157 #ifndef SQLITE_MAX_EXPR_DEPTH
158 # define SQLITE_MAX_EXPR_DEPTH 1000
159 #endif
160
161 /*
162 ** The maximum number of terms in a compound SELECT statement.
163 ** The code generator for compound SELECT statements does one
164 ** level of recursion for each term.  A stack overflow can result
165 ** if the number of terms is too large.  In practice, most SQL
166 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
167 ** any limit on the number of terms in a compount SELECT.
168 */
169 #ifndef SQLITE_MAX_COMPOUND_SELECT
170 # define SQLITE_MAX_COMPOUND_SELECT 500
171 #endif
172
173 /*
174 ** The maximum number of opcodes in a VDBE program.
175 ** Not currently enforced.
176 */
177 #ifndef SQLITE_MAX_VDBE_OP
178 # define SQLITE_MAX_VDBE_OP 25000
179 #endif
180
181 /*
182 ** The maximum number of arguments to an SQL function.
183 */
184 #ifndef SQLITE_MAX_FUNCTION_ARG
185 # define SQLITE_MAX_FUNCTION_ARG 100
186 #endif
187
188 /*
189 ** The maximum number of in-memory pages to use for the main database
190 ** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
191 */
192 #ifndef SQLITE_DEFAULT_CACHE_SIZE
193 # define SQLITE_DEFAULT_CACHE_SIZE  2000
194 #endif
195 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
196 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
197 #endif
198
199 /*
200 ** The maximum number of attached databases.  This must be at least 2
201 ** in order to support the main database file (0) and the file used to
202 ** hold temporary tables (1).  And it must be less than 32 because
203 ** we use a bitmask of databases with a u32 in places (for example
204 ** the Parse.cookieMask field).
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 32768.  This a limit
219 ** imposed by the necessity of storing the value in a 2-byte unsigned integer
220 ** and the fact that the page size must be a power of 2.
221 */
222 #ifndef SQLITE_MAX_PAGE_SIZE
223 # define SQLITE_MAX_PAGE_SIZE 32768
224 #endif
225
226
227 /*
228 ** The default size of a database page.
229 */
230 #ifndef SQLITE_DEFAULT_PAGE_SIZE
231 # define SQLITE_DEFAULT_PAGE_SIZE 1024
232 #endif
233 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
234 # undef SQLITE_DEFAULT_PAGE_SIZE
235 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
236 #endif
237
238 /*
239 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
240 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
241 ** device characteristics (sector-size and atomic write() support),
242 ** SQLite may choose a larger value. This constant is the maximum value
243 ** SQLite will choose on its own.
244 */
245 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
246 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
247 #endif
248 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
249 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
250 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
251 #endif
252
253
254 /*
255 ** Maximum number of pages in one database file.
256 **
257 ** This is really just the default value for the max_page_count pragma.
258 ** This value can be lowered (or raised) at run-time using that the
259 ** max_page_count macro.
260 */
261 #ifndef SQLITE_MAX_PAGE_COUNT
262 # define SQLITE_MAX_PAGE_COUNT 1073741823
263 #endif
264
265 /*
266 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
267 ** operator.
268 */
269 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
270 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
271 #endif
272
273 /************** End of sqliteLimit.h *****************************************/
274 /************** Continuing where we left off in sqliteInt.h ******************/
275
276 /*
277 ** For testing purposes, the various size limit constants are really
278 ** variables that we can modify in the testfixture.
279 */
280 #ifdef SQLITE_TEST
281   #undef SQLITE_MAX_LENGTH
282   #undef SQLITE_MAX_COLUMN
283   #undef SQLITE_MAX_SQL_LENGTH
284   #undef SQLITE_MAX_EXPR_DEPTH
285   #undef SQLITE_MAX_COMPOUND_SELECT
286   #undef SQLITE_MAX_VDBE_OP
287   #undef SQLITE_MAX_FUNCTION_ARG
288   #undef SQLITE_MAX_VARIABLE_NUMBER
289   #undef SQLITE_MAX_PAGE_SIZE
290   #undef SQLITE_MAX_PAGE_COUNT
291   #undef SQLITE_MAX_LIKE_PATTERN_LENGTH
292
293   #define SQLITE_MAX_LENGTH              sqlite3MAX_LENGTH
294   #define SQLITE_MAX_COLUMN              sqlite3MAX_COLUMN
295   #define SQLITE_MAX_SQL_LENGTH          sqlite3MAX_SQL_LENGTH
296   #define SQLITE_MAX_EXPR_DEPTH          sqlite3MAX_EXPR_DEPTH
297   #define SQLITE_MAX_COMPOUND_SELECT     sqlite3MAX_COMPOUND_SELECT
298   #define SQLITE_MAX_VDBE_OP             sqlite3MAX_VDBE_OP
299   #define SQLITE_MAX_FUNCTION_ARG        sqlite3MAX_FUNCTION_ARG
300   #define SQLITE_MAX_VARIABLE_NUMBER     sqlite3MAX_VARIABLE_NUMBER
301   #define SQLITE_MAX_PAGE_SIZE           sqlite3MAX_PAGE_SIZE
302   #define SQLITE_MAX_PAGE_COUNT          sqlite3MAX_PAGE_COUNT
303   #define SQLITE_MAX_LIKE_PATTERN_LENGTH sqlite3MAX_LIKE_PATTERN_LENGTH
304
305   extern int sqlite3MAX_LENGTH;
306   extern int sqlite3MAX_COLUMN;
307   extern int sqlite3MAX_SQL_LENGTH;
308   extern int sqlite3MAX_EXPR_DEPTH;
309   extern int sqlite3MAX_COMPOUND_SELECT;
310   extern int sqlite3MAX_VDBE_OP;
311   extern int sqlite3MAX_FUNCTION_ARG;
312   extern int sqlite3MAX_VARIABLE_NUMBER;
313   extern int sqlite3MAX_PAGE_SIZE;
314   extern int sqlite3MAX_PAGE_COUNT;
315   extern int sqlite3MAX_LIKE_PATTERN_LENGTH;
316 #endif
317
318
319 /*
320 ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
321 ** Older versions of SQLite used an optional THREADSAFE macro.
322 ** We support that for legacy
323 */
324 #if !defined(SQLITE_THREADSAFE)
325 #if defined(THREADSAFE)
326 # define SQLITE_THREADSAFE THREADSAFE
327 #else
328 # define SQLITE_THREADSAFE 1
329 #endif
330 #endif
331
332 /*
333 ** We need to define _XOPEN_SOURCE as follows in order to enable
334 ** recursive mutexes on most unix systems.  But Mac OS X is different.
335 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
336 ** so it is omitted there.  See ticket #2673.
337 **
338 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
339 ** implemented on some systems.  So we avoid defining it at all
340 ** if it is already defined or if it is unneeded because we are
341 ** not doing a threadsafe build.  Ticket #2681.
342 **
343 ** See also ticket #2741.
344 */
345 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && SQLITE_THREADSAFE
346 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
347 #endif
348
349 #if defined(SQLITE_TCL) || defined(TCLSH)
350 # include <tcl.h>
351 #endif
352
353 /*
354 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
355 ** Setting NDEBUG makes the code smaller and run faster.  So the following
356 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
357 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
358 ** feature.
359 */
360 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
361 # define NDEBUG 1
362 #endif
363
364 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
365 /************** Begin file sqlite3.h *****************************************/
366 /*
367 ** 2001 September 15
368 **
369 ** The author disclaims copyright to this source code.  In place of
370 ** a legal notice, here is a blessing:
371 **
372 **    May you do good and not evil.
373 **    May you find forgiveness for yourself and forgive others.
374 **    May you share freely, never taking more than you give.
375 **
376 *************************************************************************
377 ** This header file defines the interface that the SQLite library
378 ** presents to client programs.  If a C-function, structure, datatype,
379 ** or constant definition does not appear in this file, then it is
380 ** not a published API of SQLite, is subject to change without
381 ** notice, and should not be referenced by programs that use SQLite.
382 **
383 ** Some of the definitions that are in this file are marked as
384 ** "experimental".  Experimental interfaces are normally new
385 ** features recently added to SQLite.  We do not anticipate changes 
386 ** to experimental interfaces but reserve to make minor changes if
387 ** experience from use "in the wild" suggest such changes are prudent.
388 **
389 ** The official C-language API documentation for SQLite is derived
390 ** from comments in this file.  This file is the authoritative source
391 ** on how SQLite interfaces are suppose to operate.
392 **
393 ** The name of this file under configuration management is "sqlite.h.in".
394 ** The makefile makes some minor changes to this file (such as inserting
395 ** the version number) and changes its name to "sqlite3.h" as
396 ** part of the build process.
397 **
398 ** @(#) $Id: sqlite.h.in,v 1.278 2007/12/13 21:54:11 drh Exp $
399 */
400 #ifndef _SQLITE3_H_
401 #define _SQLITE3_H_
402 #include <stdarg.h>     /* Needed for the definition of va_list */
403
404 /*
405 ** Make sure we can call this stuff from C++.
406 */
407 #if 0
408 extern "C" {
409 #endif
410
411
412 /*
413 ** Add the ability to override 'extern'
414 */
415 #ifndef SQLITE_EXTERN
416 # define SQLITE_EXTERN extern
417 #endif
418
419 /*
420 ** Make sure these symbols where not defined by some previous header
421 ** file.
422 */
423 #ifdef SQLITE_VERSION
424 # undef SQLITE_VERSION
425 #endif
426 #ifdef SQLITE_VERSION_NUMBER
427 # undef SQLITE_VERSION_NUMBER
428 #endif
429
430 /*
431 ** CAPI3REF: Compile-Time Library Version Numbers {F10010}
432 **
433 ** {F10011} The #define in the sqlite3.h header file named
434 ** SQLITE_VERSION resolves to a string literal that identifies
435 ** the version of the SQLite library in the format "X.Y.Z", where
436 ** X is the major version number, Y is the minor version number and Z
437 ** is the release number.  The X.Y.Z might be followed by "alpha" or "beta".
438 ** {END} For example "3.1.1beta".
439 **
440 ** The X value is always 3 in SQLite.  The X value only changes when
441 ** backwards compatibility is broken and we intend to never break
442 ** backwards compatibility.  The Y value only changes when
443 ** there are major feature enhancements that are forwards compatible
444 ** but not backwards compatible.  The Z value is incremented with
445 ** each release but resets back to 0 when Y is incremented.
446 **
447 ** {F10014} The SQLITE_VERSION_NUMBER #define resolves to an integer
448 ** with the value  (X*1000000 + Y*1000 + Z) where X, Y, and Z are as
449 ** with SQLITE_VERSION. {END} For example, for version "3.1.1beta", 
450 ** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using 
451 ** version 3.1.1 or greater at compile time, programs may use the test 
452 ** (SQLITE_VERSION_NUMBER>=3001001).
453 **
454 ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
455 */
456 #define SQLITE_VERSION         "3.5.4"
457 #define SQLITE_VERSION_NUMBER 3005004
458
459 /*
460 ** CAPI3REF: Run-Time Library Version Numbers {F10020}
461 **
462 ** {F10021} The sqlite3_libversion_number() interface returns an integer
463 ** equal to [SQLITE_VERSION_NUMBER].  {END} The value returned
464 ** by this routine should only be different from the header values
465 ** if the application is compiled using an sqlite3.h header from a
466 ** different version of SQLite than library.  Cautious programmers might
467 ** include a check in their application to verify that 
468 ** sqlite3_libversion_number() always returns the value 
469 ** [SQLITE_VERSION_NUMBER].
470 **
471 ** {F10022} The sqlite3_version[] string constant contains the text of the
472 ** [SQLITE_VERSION] string. {F10023} The sqlite3_libversion() function returns
473 ** a pointer to the sqlite3_version[] string constant. {END} The 
474 ** sqlite3_libversion() function
475 ** is provided for DLL users who can only access functions and not
476 ** constants within the DLL.
477 */
478 SQLITE_EXTERN const char sqlite3_version[];
479 SQLITE_API const char *sqlite3_libversion(void);
480 SQLITE_API int sqlite3_libversion_number(void);
481
482 /*
483 ** CAPI3REF: Test To See If The Library Is Threadsafe {F10100}
484 **
485 ** {F10101} The sqlite3_threadsafe() routine returns nonzero
486 ** if SQLite was compiled with its mutexes enabled or zero if
487 ** SQLite was compiled with mutexes disabled. {END}  If this
488 ** routine returns false, then it is not safe for simultaneously
489 ** running threads to both invoke SQLite interfaces.
490 **
491 ** Really all this routine does is return true if SQLite was
492 ** compiled with the -DSQLITE_THREADSAFE=1 option and false if
493 ** compiled with -DSQLITE_THREADSAFE=0.  If SQLite uses an
494 ** application-defined mutex subsystem, malloc subsystem, collating
495 ** sequence, VFS, SQL function, progress callback, commit hook,
496 ** extension, or other accessories and these add-ons are not
497 ** threadsafe, then clearly the combination will not be threadsafe
498 ** either.  Hence, this routine never reports that the library
499 ** is guaranteed to be threadsafe, only when it is guaranteed not
500 ** to be.
501 */
502 SQLITE_API int sqlite3_threadsafe(void);
503
504 /*
505 ** CAPI3REF: Database Connection Handle {F12000}
506 **
507 ** Each open SQLite database is represented by pointer to an instance of the
508 ** opaque structure named "sqlite3".  It is useful to think of an sqlite3
509 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
510 ** [sqlite3_open_v2()] interfaces are its constructors
511 ** and [sqlite3_close()] is its destructor.  There are many other interfaces
512 ** (such as [sqlite3_prepare_v2()], [sqlite3_create_function()], and
513 ** [sqlite3_busy_timeout()] to name but three) that are methods on this
514 ** object.
515 */
516 typedef struct sqlite3 sqlite3;
517
518
519 /*
520 ** CAPI3REF: 64-Bit Integer Types {F10200}
521 **
522 ** Because there is no cross-platform way to specify such types
523 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
524 ** {F10201} The sqlite_int64 and sqlite3_int64 types specify a
525 ** 64-bit signed integer. {F10202} The sqlite_uint64 and
526 ** sqlite3_uint64 types specify a 64-bit unsigned integer. {END}
527 **
528 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type
529 ** definitions.  The sqlite_int64 and sqlite_uint64 types are
530 ** supported for backwards compatibility only.
531 */
532 #ifdef SQLITE_INT64_TYPE
533   typedef SQLITE_INT64_TYPE sqlite_int64;
534   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
535 #elif defined(_MSC_VER) || defined(__BORLANDC__)
536   typedef __int64 sqlite_int64;
537   typedef unsigned __int64 sqlite_uint64;
538 #else
539   typedef long long int sqlite_int64;
540   typedef unsigned long long int sqlite_uint64;
541 #endif
542 typedef sqlite_int64 sqlite3_int64;
543 typedef sqlite_uint64 sqlite3_uint64;
544
545 /*
546 ** If compiling for a processor that lacks floating point support,
547 ** substitute integer for floating-point
548 */
549 #ifdef SQLITE_OMIT_FLOATING_POINT
550 # define double sqlite3_int64
551 #endif
552
553 /*
554 ** CAPI3REF: Closing A Database Connection {F12010}
555 **
556 ** {F12011} The sqlite3_close() interfaces destroys an [sqlite3] object
557 ** allocated by a prior call to [sqlite3_open()], [sqlite3_open16()], or
558 ** [sqlite3_open_v2()]. {F12012} Sqlite3_close() releases all
559 ** memory used by the connection and closes all open files. {END}.
560 **
561 ** {F12013} If the database connection contains
562 ** [sqlite3_stmt | prepared statements] that have not been finalized
563 ** by [sqlite3_finalize()], then sqlite3_close() returns SQLITE_BUSY
564 ** and leaves the connection open.  {F12014} Giving sqlite3_close()
565 ** a NULL pointer is a harmless no-op. {END}
566 **
567 ** {U12015} Passing this routine a database connection that has already been
568 ** closed results in undefined behavior. {U12016} If other interfaces that
569 ** reference the same database connection are pending (either in the
570 ** same thread or in different threads) when this routine is called,
571 ** then the behavior is undefined and is almost certainly undesirable.
572 */
573 SQLITE_API int sqlite3_close(sqlite3 *);
574
575 /*
576 ** The type for a callback function.
577 ** This is legacy and deprecated.  It is included for historical
578 ** compatibility and is not documented.
579 */
580 typedef int (*sqlite3_callback)(void*,int,char**, char**);
581
582 /*
583 ** CAPI3REF: One-Step Query Execution Interface {F12100}
584 **
585 ** {F12101} The sqlite3_exec() interface evaluates zero or more 
586 ** UTF-8 encoded, semicolon-separated SQL statements in the zero-terminated
587 ** string of its second argument.  {F12102} The SQL
588 ** statements are evaluated in the context of the database connection
589 ** specified by in the first argument.
590 ** {F12103} SQL statements are prepared one by one using
591 ** [sqlite3_prepare()] or the equivalent, evaluated
592 ** using one or more calls to [sqlite3_step()], then destroyed
593 ** using [sqlite3_finalize()]. {F12104} The return value of
594 ** sqlite3_exec() is SQLITE_OK if all SQL statement run
595 ** successfully.
596 **
597 ** {F12105} If one or more of the SQL statements handed to
598 ** sqlite3_exec() are queries, then
599 ** the callback function specified by the 3rd parameter is
600 ** invoked once for each row of the query result. {F12106}
601 ** If the callback returns a non-zero value then the query
602 ** is aborted, all subsequent SQL statements
603 ** are skipped and the sqlite3_exec() function returns the [SQLITE_ABORT].
604 **
605 ** {F12107} The 4th parameter to sqlite3_exec() is an arbitrary pointer
606 ** that is passed through to the callback function as its first parameter.
607 **
608 ** {F12108} The 2nd parameter to the callback function is the number of
609 ** columns in the query result.  {F12109} The 3rd parameter to the callback
610 ** is an array of pointers to strings holding the values for each column
611 ** as extracted using [sqlite3_column_text()].  NULL values in the result
612 ** set result in a NULL pointer.  All other value are in their UTF-8
613 ** string representation. {F12117}
614 ** The 4th parameter to the callback is an array of strings
615 ** obtained using [sqlite3_column_name()] and holding
616 ** the names of each column, also in UTF-8.
617 **
618 ** {F12110} The callback function may be NULL, even for queries.  A NULL
619 ** callback is not an error.  It just means that no callback
620 ** will be invoked. 
621 **
622 ** {F12112} If an error occurs while parsing or evaluating the SQL
623 ** then an appropriate error message is written into memory obtained
624 ** from [sqlite3_malloc()] and *errmsg is made to point to that message
625 ** assuming errmsg is not NULL.  
626 ** {U12113} The calling function is responsible for freeing the memory
627 ** using [sqlite3_free()].
628 ** {F12116} If [sqlite3_malloc()] fails while attempting to generate
629 ** the error message, *errmsg is set to NULL.
630 ** {F12114} If errmsg is NULL then no attempt is made to generate an
631 ** error message. <todo>Is the return code SQLITE_NOMEM or the original
632 ** error code?</todo> <todo>What happens if there are multiple errors?
633 ** Do we get code for the first error, or is the choice of reported
634 ** error arbitrary?</todo>
635 **
636 ** {F12115} The return value is is SQLITE_OK if there are no errors and
637 ** some other [SQLITE_OK | return code] if there is an error.  
638 ** The particular return value depends on the type of error.  {END}
639 */
640 SQLITE_API int sqlite3_exec(
641   sqlite3*,                                  /* An open database */
642   const char *sql,                           /* SQL to be evaluted */
643   int (*callback)(void*,int,char**,char**),  /* Callback function */
644   void *,                                    /* 1st argument to callback */
645   char **errmsg                              /* Error msg written here */
646 );
647
648 /*
649 ** CAPI3REF: Result Codes {F10210}
650 ** KEYWORDS: SQLITE_OK
651 **
652 ** Many SQLite functions return an integer result code from the set shown
653 ** above in order to indicates success or failure.
654 **
655 ** {F10211} The result codes shown here are the only ones returned 
656 ** by SQLite in its default configuration. {F10212} However, the
657 ** [sqlite3_extended_result_codes()] API can be used to set a database
658 ** connectoin to return more detailed result codes. {END}
659 **
660 ** See also: [SQLITE_IOERR_READ | extended result codes]
661 **
662 */
663 #define SQLITE_OK           0   /* Successful result */
664 /* beginning-of-error-codes */
665 #define SQLITE_ERROR        1   /* SQL error or missing database */
666 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
667 #define SQLITE_PERM         3   /* Access permission denied */
668 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
669 #define SQLITE_BUSY         5   /* The database file is locked */
670 #define SQLITE_LOCKED       6   /* A table in the database is locked */
671 #define SQLITE_NOMEM        7   /* A malloc() failed */
672 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
673 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
674 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
675 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
676 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
677 #define SQLITE_FULL        13   /* Insertion failed because database is full */
678 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
679 #define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
680 #define SQLITE_EMPTY       16   /* Database is empty */
681 #define SQLITE_SCHEMA      17   /* The database schema changed */
682 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
683 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
684 #define SQLITE_MISMATCH    20   /* Data type mismatch */
685 #define SQLITE_MISUSE      21   /* Library used incorrectly */
686 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
687 #define SQLITE_AUTH        23   /* Authorization denied */
688 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
689 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
690 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
691 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
692 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
693 /* end-of-error-codes */
694
695 /*
696 ** CAPI3REF: Extended Result Codes {F10220}
697 **
698 ** In its default configuration, SQLite API routines return one of 26 integer
699 ** [SQLITE_OK | result codes].  However, experience has shown that
700 ** many of these result codes are too course-grained.  They do not provide as
701 ** much information about problems as programmers might like.  In an effort to
702 ** address this, newer versions of SQLite (version 3.3.8 and later) include
703 ** support for additional result codes that provide more detailed information
704 ** about errors. {F10221} The extended result codes are enabled or disabled
705 ** for each database connection using the [sqlite3_extended_result_codes()]
706 ** API. {END}
707 ** 
708 ** Some of the available extended result codes are listed above.
709 ** We expect the number of extended result codes will be expand
710 ** over time.  {U10422} Software that uses extended result codes should expect
711 ** to see new result codes in future releases of SQLite. {END}
712 ** 
713 ** {F10223} The symbolic name for an extended result code always contains
714 ** a related primary result code as a prefix. {F10224} Primary result
715 ** codes contain a single "_" character.  {F10225} Extended result codes
716 ** contain two or more "_" characters. {F10226} The numeric value of an
717 ** extended result code can be converted to its
718 ** corresponding primary result code by masking off the lower 8 bytes. {END}
719 **
720 ** The SQLITE_OK result code will never be extended.  It will always
721 ** be exactly zero.
722 */
723 #define SQLITE_IOERR_READ          (SQLITE_IOERR | (1<<8))
724 #define SQLITE_IOERR_SHORT_READ    (SQLITE_IOERR | (2<<8))
725 #define SQLITE_IOERR_WRITE         (SQLITE_IOERR | (3<<8))
726 #define SQLITE_IOERR_FSYNC         (SQLITE_IOERR | (4<<8))
727 #define SQLITE_IOERR_DIR_FSYNC     (SQLITE_IOERR | (5<<8))
728 #define SQLITE_IOERR_TRUNCATE      (SQLITE_IOERR | (6<<8))
729 #define SQLITE_IOERR_FSTAT         (SQLITE_IOERR | (7<<8))
730 #define SQLITE_IOERR_UNLOCK        (SQLITE_IOERR | (8<<8))
731 #define SQLITE_IOERR_RDLOCK        (SQLITE_IOERR | (9<<8))
732 #define SQLITE_IOERR_DELETE        (SQLITE_IOERR | (10<<8))
733 #define SQLITE_IOERR_BLOCKED       (SQLITE_IOERR | (11<<8))
734 #define SQLITE_IOERR_NOMEM         (SQLITE_IOERR | (12<<8))
735
736 /*
737 ** CAPI3REF: Flags For File Open Operations {F10230}
738 **
739 ** {F10231} Some combination of the these bit values are used as the
740 ** third argument to the [sqlite3_open_v2()] interface and
741 ** as fourth argument to the xOpen method of the
742 ** [sqlite3_vfs] object.
743 */
744 #define SQLITE_OPEN_READONLY         0x00000001
745 #define SQLITE_OPEN_READWRITE        0x00000002
746 #define SQLITE_OPEN_CREATE           0x00000004
747 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008
748 #define SQLITE_OPEN_EXCLUSIVE        0x00000010
749 #define SQLITE_OPEN_MAIN_DB          0x00000100
750 #define SQLITE_OPEN_TEMP_DB          0x00000200
751 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400
752 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800
753 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000
754 #define SQLITE_OPEN_SUBJOURNAL       0x00002000
755 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000
756
757 /*
758 ** CAPI3REF: Device Characteristics {F10240}
759 **
760 ** {F10241} The xDeviceCapabilities method of the [sqlite3_io_methods]
761 ** object returns an integer which is a vector of the these
762 ** bit values expressing I/O characteristics of the mass storage
763 ** device that holds the file that the [sqlite3_io_methods]
764 ** refers to. {END}
765 **
766 ** {F10242} The SQLITE_IOCAP_ATOMIC property means that all writes of
767 ** any size are atomic.  {F10243} The SQLITE_IOCAP_ATOMICnnn values
768 ** mean that writes of blocks that are nnn bytes in size and
769 ** are aligned to an address which is an integer multiple of
770 ** nnn are atomic.  {F10244} The SQLITE_IOCAP_SAFE_APPEND value means
771 ** that when data is appended to a file, the data is appended
772 ** first then the size of the file is extended, never the other
773 ** way around.  {F10245} The SQLITE_IOCAP_SEQUENTIAL property means that
774 ** information is written to disk in the same order as calls
775 ** to xWrite().
776 */
777 #define SQLITE_IOCAP_ATOMIC          0x00000001
778 #define SQLITE_IOCAP_ATOMIC512       0x00000002
779 #define SQLITE_IOCAP_ATOMIC1K        0x00000004
780 #define SQLITE_IOCAP_ATOMIC2K        0x00000008
781 #define SQLITE_IOCAP_ATOMIC4K        0x00000010
782 #define SQLITE_IOCAP_ATOMIC8K        0x00000020
783 #define SQLITE_IOCAP_ATOMIC16K       0x00000040
784 #define SQLITE_IOCAP_ATOMIC32K       0x00000080
785 #define SQLITE_IOCAP_ATOMIC64K       0x00000100
786 #define SQLITE_IOCAP_SAFE_APPEND     0x00000200
787 #define SQLITE_IOCAP_SEQUENTIAL      0x00000400
788
789 /*
790 ** CAPI3REF: File Locking Levels {F10250}
791 **
792 ** {F10251} SQLite uses one of the following integer values as the second
793 ** argument to calls it makes to the xLock() and xUnlock() methods
794 ** of an [sqlite3_io_methods] object. {END}
795 */
796 #define SQLITE_LOCK_NONE          0
797 #define SQLITE_LOCK_SHARED        1
798 #define SQLITE_LOCK_RESERVED      2
799 #define SQLITE_LOCK_PENDING       3
800 #define SQLITE_LOCK_EXCLUSIVE     4
801
802 /*
803 ** CAPI3REF: Synchronization Type Flags {F10260}
804 **
805 ** {F10261} When SQLite invokes the xSync() method of an
806 ** [sqlite3_io_methods] object it uses a combination of the
807 ** these integer values as the second argument.
808 **
809 ** {F10262} When the SQLITE_SYNC_DATAONLY flag is used, it means that the
810 ** sync operation only needs to flush data to mass storage.  Inode
811 ** information need not be flushed. {F10263} The SQLITE_SYNC_NORMAL means 
812 ** to use normal fsync() semantics. {F10264} The SQLITE_SYNC_FULL flag means 
813 ** to use Mac OS-X style fullsync instead of fsync().
814 */
815 #define SQLITE_SYNC_NORMAL        0x00002
816 #define SQLITE_SYNC_FULL          0x00003
817 #define SQLITE_SYNC_DATAONLY      0x00010
818
819
820 /*
821 ** CAPI3REF: OS Interface Open File Handle {F11110}
822 **
823 ** An [sqlite3_file] object represents an open file in the OS
824 ** interface layer.  Individual OS interface implementations will
825 ** want to subclass this object by appending additional fields
826 ** for their own use.  The pMethods entry is a pointer to an
827 ** [sqlite3_io_methods] object that defines methods for performing
828 ** I/O operations on the open file.
829 */
830 typedef struct sqlite3_file sqlite3_file;
831 struct sqlite3_file {
832   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
833 };
834
835 /*
836 ** CAPI3REF: OS Interface File Virtual Methods Object {F11120}
837 **
838 ** Every file opened by the [sqlite3_vfs] xOpen method contains a pointer to
839 ** an instance of the this object.  This object defines the
840 ** methods used to perform various operations against the open file.
841 **
842 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
843 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
844 *  The second choice is an
845 ** OS-X style fullsync.  The SQLITE_SYNC_DATA flag may be ORed in to
846 ** indicate that only the data of the file and not its inode needs to be
847 ** synced.
848 ** 
849 ** The integer values to xLock() and xUnlock() are one of
850 ** <ul>
851 ** <li> [SQLITE_LOCK_NONE],
852 ** <li> [SQLITE_LOCK_SHARED],
853 ** <li> [SQLITE_LOCK_RESERVED],
854 ** <li> [SQLITE_LOCK_PENDING], or
855 ** <li> [SQLITE_LOCK_EXCLUSIVE].
856 ** </ul>
857 ** xLock() increases the lock. xUnlock() decreases the lock.  
858 ** The xCheckReservedLock() method looks
859 ** to see if any database connection, either in this
860 ** process or in some other process, is holding an RESERVED,
861 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
862 ** if such a lock exists and false if not.
863 ** 
864 ** The xFileControl() method is a generic interface that allows custom
865 ** VFS implementations to directly control an open file using the
866 ** [sqlite3_file_control()] interface.  The second "op" argument
867 ** is an integer opcode.   The third
868 ** argument is a generic pointer which is intended to be a pointer
869 ** to a structure that may contain arguments or space in which to
870 ** write return values.  Potential uses for xFileControl() might be
871 ** functions to enable blocking locks with timeouts, to change the
872 ** locking strategy (for example to use dot-file locks), to inquire
873 ** about the status of a lock, or to break stale locks.  The SQLite
874 ** core reserves opcodes less than 100 for its own use. 
875 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
876 ** Applications that define a custom xFileControl method should use opcodes 
877 ** greater than 100 to avoid conflicts.
878 **
879 ** The xSectorSize() method returns the sector size of the
880 ** device that underlies the file.  The sector size is the
881 ** minimum write that can be performed without disturbing
882 ** other bytes in the file.  The xDeviceCharacteristics()
883 ** method returns a bit vector describing behaviors of the
884 ** underlying device:
885 **
886 ** <ul>
887 ** <li> [SQLITE_IOCAP_ATOMIC]
888 ** <li> [SQLITE_IOCAP_ATOMIC512]
889 ** <li> [SQLITE_IOCAP_ATOMIC1K]
890 ** <li> [SQLITE_IOCAP_ATOMIC2K]
891 ** <li> [SQLITE_IOCAP_ATOMIC4K]
892 ** <li> [SQLITE_IOCAP_ATOMIC8K]
893 ** <li> [SQLITE_IOCAP_ATOMIC16K]
894 ** <li> [SQLITE_IOCAP_ATOMIC32K]
895 ** <li> [SQLITE_IOCAP_ATOMIC64K]
896 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
897 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
898 ** </ul>
899 **
900 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
901 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
902 ** mean that writes of blocks that are nnn bytes in size and
903 ** are aligned to an address which is an integer multiple of
904 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
905 ** that when data is appended to a file, the data is appended
906 ** first then the size of the file is extended, never the other
907 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
908 ** information is written to disk in the same order as calls
909 ** to xWrite().
910 */
911 typedef struct sqlite3_io_methods sqlite3_io_methods;
912 struct sqlite3_io_methods {
913   int iVersion;
914   int (*xClose)(sqlite3_file*);
915   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
916   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
917   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
918   int (*xSync)(sqlite3_file*, int flags);
919   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
920   int (*xLock)(sqlite3_file*, int);
921   int (*xUnlock)(sqlite3_file*, int);
922   int (*xCheckReservedLock)(sqlite3_file*);
923   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
924   int (*xSectorSize)(sqlite3_file*);
925   int (*xDeviceCharacteristics)(sqlite3_file*);
926   /* Additional methods may be added in future releases */
927 };
928
929 /*
930 ** CAPI3REF: Standard File Control Opcodes {F11310}
931 **
932 ** These integer constants are opcodes for the xFileControl method
933 ** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()]
934 ** interface.
935 **
936 ** {F11311} The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
937 ** opcode cases the xFileControl method to write the current state of
938 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
939 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
940 ** into an integer that the pArg argument points to. {F11312} This capability
941 ** is used during testing and only needs to be supported when SQLITE_TEST
942 ** is defined.
943 */
944 #define SQLITE_FCNTL_LOCKSTATE        1
945
946 /*
947 ** CAPI3REF: Mutex Handle {F17110}
948 **
949 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
950 ** abstract type for a mutex object.  {F17111} The SQLite core never looks
951 ** at the internal representation of an [sqlite3_mutex]. {END} It only
952 ** deals with pointers to the [sqlite3_mutex] object.
953 **
954 ** Mutexes are created using [sqlite3_mutex_alloc()].
955 */
956 typedef struct sqlite3_mutex sqlite3_mutex;
957
958 /*
959 ** CAPI3REF: OS Interface Object {F11140}
960 **
961 ** An instance of this object defines the interface between the
962 ** SQLite core and the underlying operating system.  The "vfs"
963 ** in the name of the object stands for "virtual file system".
964 **
965 ** The iVersion field is initially 1 but may be larger for future
966 ** versions of SQLite.  Additional fields may be appended to this
967 ** object when the iVersion value is increased.
968 **
969 ** The szOsFile field is the size of the subclassed [sqlite3_file]
970 ** structure used by this VFS.  mxPathname is the maximum length of
971 ** a pathname in this VFS.
972 **
973 ** Registered vfs modules are kept on a linked list formed by
974 ** the pNext pointer.  The [sqlite3_vfs_register()]
975 ** and [sqlite3_vfs_unregister()] interfaces manage this list
976 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
977 ** searches the list.
978 **
979 ** The pNext field is the only fields in the sqlite3_vfs 
980 ** structure that SQLite will ever modify.  SQLite will only access
981 ** or modify this field while holding a particular static mutex.
982 ** The application should never modify anything within the sqlite3_vfs
983 ** object once the object has been registered.
984 **
985 ** The zName field holds the name of the VFS module.  The name must
986 ** be unique across all VFS modules.
987 **
988 ** {F11141} SQLite will guarantee that the zFilename string passed to
989 ** xOpen() is a full pathname as generated by xFullPathname() and
990 ** that the string will be valid and unchanged until xClose() is
991 ** called.  {END} So the [sqlite3_file] can store a pointer to the
992 ** filename if it needs to remember the filename for some reason.
993 **
994 ** {F11142} The flags argument to xOpen() includes all bits set in
995 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
996 ** or [sqlite3_open16()] is used, then flags includes at least
997 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END}
998 ** If xOpen() opens a file read-only then it sets *pOutFlags to
999 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be
1000 ** set.
1001 ** 
1002 ** {F11143} SQLite will also add one of the following flags to the xOpen()
1003 ** call, depending on the object being opened:
1004 ** 
1005 ** <ul>
1006 ** <li>  [SQLITE_OPEN_MAIN_DB]
1007 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1008 ** <li>  [SQLITE_OPEN_TEMP_DB]
1009 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1010 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1011 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1012 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1013 ** </ul> {END}
1014 **
1015 ** The file I/O implementation can use the object type flags to
1016 ** changes the way it deals with files.  For example, an application
1017 ** that does not care about crash recovery or rollback, might make
1018 ** the open of a journal file a no-op.  Writes to this journal are
1019 ** also a no-op.  Any attempt to read the journal return SQLITE_IOERR.
1020 ** Or the implementation might recognize the a database file will
1021 ** be doing page-aligned sector reads and writes in a random order
1022 ** and set up its I/O subsystem accordingly.
1023 ** 
1024 ** {F11144} SQLite might also add one of the following flags to the xOpen
1025 ** method:
1026 ** 
1027 ** <ul>
1028 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1029 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1030 ** </ul>
1031 ** 
1032 ** {F11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1033 ** deleted when it is closed.  {F11146} The [SQLITE_OPEN_DELETEONCLOSE]
1034 ** will be set for TEMP  databases, journals and for subjournals. 
1035 ** {F11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened
1036 ** for exclusive access.  This flag is set for all files except
1037 ** for the main database file. {END}
1038 ** 
1039 ** {F11148} At least szOsFile bytes of memory is allocated by SQLite 
1040 ** to hold the  [sqlite3_file] structure passed as the third 
1041 ** argument to xOpen.  {END}  The xOpen method does not have to
1042 ** allocate the structure; it should just fill it in.
1043 ** 
1044 ** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] 
1045 ** to test for the existance of a file,
1046 ** or [SQLITE_ACCESS_READWRITE] to test to see
1047 ** if a file is readable and writable, or [SQLITE_ACCESS_READ]
1048 ** to test to see if a file is at least readable.  {END} The file can be a 
1049 ** directory.
1050 ** 
1051 ** {F11150} SQLite will always allocate at least mxPathname+1 byte for
1052 ** the output buffers for xGetTempname and xFullPathname. {F11151} The exact
1053 ** size of the output buffer is also passed as a parameter to both 
1054 ** methods. {END} If the output buffer is not large enough, SQLITE_CANTOPEN
1055 ** should be returned. As this is handled as a fatal error by SQLite,
1056 ** vfs implementations should endeavor to prevent this by setting 
1057 ** mxPathname to a sufficiently large value.
1058 ** 
1059 ** The xRandomness(), xSleep(), and xCurrentTime() interfaces
1060 ** are not strictly a part of the filesystem, but they are
1061 ** included in the VFS structure for completeness.
1062 ** The xRandomness() function attempts to return nBytes bytes
1063 ** of good-quality randomness into zOut.  The return value is
1064 ** the actual number of bytes of randomness obtained.  The
1065 ** xSleep() method cause the calling thread to sleep for at
1066 ** least the number of microseconds given.  The xCurrentTime()
1067 ** method returns a Julian Day Number for the current date and
1068 ** time.
1069 */
1070 typedef struct sqlite3_vfs sqlite3_vfs;
1071 struct sqlite3_vfs {
1072   int iVersion;            /* Structure version number */
1073   int szOsFile;            /* Size of subclassed sqlite3_file */
1074   int mxPathname;          /* Maximum file pathname length */
1075   sqlite3_vfs *pNext;      /* Next registered VFS */
1076   const char *zName;       /* Name of this virtual file system */
1077   void *pAppData;          /* Pointer to application-specific data */
1078   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1079                int flags, int *pOutFlags);
1080   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1081   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags);
1082   int (*xGetTempname)(sqlite3_vfs*, int nOut, char *zOut);
1083   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1084   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1085   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1086   void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol);
1087   void (*xDlClose)(sqlite3_vfs*, void*);
1088   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1089   int (*xSleep)(sqlite3_vfs*, int microseconds);
1090   int (*xCurrentTime)(sqlite3_vfs*, double*);
1091   /* New fields may be appended in figure versions.  The iVersion
1092   ** value will increment whenever this happens. */
1093 };
1094
1095 /*
1096 ** CAPI3REF: Flags for the xAccess VFS method {F11190}
1097 **
1098 ** {F11191} These integer constants can be used as the third parameter to
1099 ** the xAccess method of an [sqlite3_vfs] object. {END}  They determine
1100 ** the kind of what kind of permissions the xAccess method is
1101 ** looking for.  {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method
1102 ** simply checks to see if the file exists. {F11193} With
1103 ** SQLITE_ACCESS_READWRITE, the xAccess method checks to see
1104 ** if the file is both readable and writable.  {F11194} With
1105 ** SQLITE_ACCESS_READ the xAccess method
1106 ** checks to see if the file is readable.
1107 */
1108 #define SQLITE_ACCESS_EXISTS    0
1109 #define SQLITE_ACCESS_READWRITE 1
1110 #define SQLITE_ACCESS_READ      2
1111
1112 /*
1113 ** CAPI3REF: Enable Or Disable Extended Result Codes {F12200}
1114 **
1115 ** {F12201} The sqlite3_extended_result_codes() routine enables or disables the
1116 ** [SQLITE_IOERR_READ | extended result codes] feature on a database
1117 ** connection if its 2nd parameter is
1118 ** non-zero or zero, respectively. {F12202}
1119 ** By default, SQLite API routines return one of only 26 integer
1120 ** [SQLITE_OK | result codes].  {F12203} When extended result codes
1121 ** are enabled by this routine, the repetoire of result codes can be
1122 ** much larger and can (hopefully) provide more detailed information
1123 ** about the cause of an error.
1124 **
1125 ** {F12204} The second argument is a boolean value that turns extended result
1126 ** codes on and off. {F12205} Extended result codes are off by default for
1127 ** backwards compatibility with older versions of SQLite.
1128 */
1129 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
1130
1131 /*
1132 ** CAPI3REF: Last Insert Rowid {F12220}
1133 **
1134 ** {F12221} Each entry in an SQLite table has a unique 64-bit signed
1135 ** integer key called the "rowid".  {F12222} The rowid is always available
1136 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
1137 ** names are not also used by explicitly declared columns. {F12223} If
1138 ** the table has a column of type INTEGER PRIMARY KEY then that column
1139 ** is another an alias for the rowid.
1140 **
1141 ** {F12224} This routine returns the rowid of the most recent
1142 ** successful INSERT into the database from the database connection
1143 ** shown in the first argument.  {F12225} If no successful inserts
1144 ** have ever occurred on this database connection, zero is returned.
1145 **
1146 ** {F12226} If an INSERT occurs within a trigger, then the rowid of the
1147 ** inserted row is returned by this routine as long as the trigger
1148 ** is running.  {F12227} But once the trigger terminates, the value returned
1149 ** by this routine reverts to the last value inserted before the
1150 ** trigger fired.
1151 **
1152 ** {F12228} An INSERT that fails due to a constraint violation is not a
1153 ** successful insert and does not change the value returned by this
1154 ** routine.  {F12229} Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
1155 ** and INSERT OR ABORT make no changes to the return value of this
1156 ** routine when their insertion fails.  {F12231} When INSERT OR REPLACE 
1157 ** encounters a constraint violation, it does not fail.  The
1158 ** INSERT continues to completion after deleting rows that caused
1159 ** the constraint problem so INSERT OR REPLACE will always change
1160 ** the return value of this interface. 
1161 **
1162 ** {UF12232} If another thread does a new insert on the same database connection
1163 ** while this routine is running and thus changes the last insert rowid,
1164 ** then the return value of this routine is undefined.
1165 */
1166 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
1167
1168 /*
1169 ** CAPI3REF: Count The Number Of Rows Modified {F12240}
1170 **
1171 ** {F12241} This function returns the number of database rows that were changed
1172 ** or inserted or deleted by the most recently completed SQL statement
1173 ** on the connection specified by the first parameter. {F12242} Only
1174 ** changes that are directly specified by the INSERT, UPDATE, or
1175 ** DELETE statement are counted.  Auxiliary changes caused by
1176 ** triggers are not counted. {F12243} Use the [sqlite3_total_changes()] function
1177 ** to find the total number of changes including changes caused by triggers.
1178 **
1179 ** {F12244} Within the body of a trigger, the sqlite3_changes() interface
1180 ** can be called to find the number of
1181 ** changes in the most recently completed INSERT, UPDATE, or DELETE
1182 ** statement within the body of the same trigger.
1183 **
1184 ** {F12245} All changes are counted, even if they are later undone by a
1185 ** ROLLBACK or ABORT.  {F12246} Except, changes associated with creating and
1186 ** dropping tables are not counted.
1187 **
1188 ** {F12247} If a callback invokes [sqlite3_exec()] or [sqlite3_step()]
1189 ** recursively, then the changes in the inner, recursive call are
1190 ** counted together with the changes in the outer call.
1191 **
1192 ** {F12248} SQLite implements the command "DELETE FROM table" without
1193 ** a WHERE clause by dropping and recreating the table.  (This is much
1194 ** faster than going through and deleting individual elements from the
1195 ** table.)  Because of this optimization, the change count for 
1196 ** "DELETE FROM table" will be zero regardless of the number of elements
1197 ** that were originally in the table. {F12251} To get an accurate count
1198 ** of the number of rows deleted, use
1199 ** "DELETE FROM table WHERE 1" instead.
1200 **
1201 ** {UF12252} If another thread makes changes on the same database connection
1202 ** while this routine is running then the return value of this routine
1203 ** is undefined.
1204 */
1205 SQLITE_API int sqlite3_changes(sqlite3*);
1206
1207 /*
1208 ** CAPI3REF: Total Number Of Rows Modified {F12260}
1209 ***
1210 ** {F12261} This function returns the number of database rows that have been
1211 ** modified by INSERT, UPDATE or DELETE statements since the database handle
1212 ** was opened. {F12262} The count includes UPDATE, INSERT and DELETE 
1213 ** statements executed as part of trigger programs.  {F12263} All changes
1214 ** are counted as soon as the statement that makes them is completed 
1215 ** (when the statement handle is passed to [sqlite3_reset()] or 
1216 ** [sqlite3_finalize()]). {END}
1217 **
1218 ** See also the [sqlite3_change()] interface.
1219 **
1220 ** {F12265} SQLite implements the command "DELETE FROM table" without
1221 ** a WHERE clause by dropping and recreating the table.  (This is much
1222 ** faster than going
1223 ** through and deleting individual elements form the table.)  Because of
1224 ** this optimization, the change count for "DELETE FROM table" will be
1225 ** zero regardless of the number of elements that were originally in the
1226 ** table. To get an accurate count of the number of rows deleted, use
1227 ** "DELETE FROM table WHERE 1" instead.
1228 **
1229 ** {U12264} If another thread makes changes on the same database connection
1230 ** while this routine is running then the return value of this routine
1231 ** is undefined. {END}
1232 */
1233 SQLITE_API int sqlite3_total_changes(sqlite3*);
1234
1235 /*
1236 ** CAPI3REF: Interrupt A Long-Running Query {F12270}
1237 **
1238 ** {F12271} This function causes any pending database operation to abort and
1239 ** return at its earliest opportunity. {END} This routine is typically
1240 ** called in response to a user action such as pressing "Cancel"
1241 ** or Ctrl-C where the user wants a long query operation to halt
1242 ** immediately.
1243 **
1244 ** {F12272} It is safe to call this routine from a thread different from the
1245 ** thread that is currently running the database operation. {U12273} But it
1246 ** is not safe to call this routine with a database connection that
1247 ** is closed or might close before sqlite3_interrupt() returns.
1248 **
1249 ** If an SQL is very nearly finished at the time when sqlite3_interrupt()
1250 ** is called, then it might not have an opportunity to be interrupted.
1251 ** It might continue to completion.
1252 ** {F12274} The SQL operation that is interrupted will return
1253 ** [SQLITE_INTERRUPT].  {F12275} If the interrupted SQL operation is an
1254 ** INSERT, UPDATE, or DELETE that is inside an explicit transaction, 
1255 ** then the entire transaction will be rolled back automatically.
1256 ** {F12276} A call to sqlite3_interrupt() has no effect on SQL statements
1257 ** that are started after sqlite3_interrupt() returns.
1258 */
1259 SQLITE_API void sqlite3_interrupt(sqlite3*);
1260
1261 /*
1262 ** CAPI3REF: Determine If An SQL Statement Is Complete {F10510}
1263 **
1264 ** These routines are useful for command-line input to determine if the
1265 ** currently entered text seems to form complete a SQL statement or
1266 ** if additional input is needed before sending the text into
1267 ** SQLite for parsing.  These routines return true if the input string
1268 ** appears to be a complete SQL statement.  A statement is judged to be
1269 ** complete if it ends with a semicolon and is not a fragment of a
1270 ** CREATE TRIGGER statement.  These routines do not parse the SQL and
1271 ** so will not detect syntactically incorrect SQL.
1272 **
1273 ** {F10511} These functions return true if the given input string 
1274 ** ends with a semicolon optionally followed by whitespace or
1275 ** comments. {F10512} For sqlite3_complete(),
1276 ** the parameter must be a zero-terminated UTF-8 string. {F10513} For
1277 ** sqlite3_complete16(), a zero-terminated machine byte order UTF-16 string
1278 ** is required.  {F10514} These routines return false if the terminal
1279 ** semicolon is within a comment, a string literal or a quoted identifier
1280 ** (in other words if the final semicolon is not really a separate token
1281 ** but part of a larger token) or if the final semicolon is
1282 ** in between the BEGIN and END keywords of a CREATE TRIGGER statement.
1283 ** {END}
1284 */
1285 SQLITE_API int sqlite3_complete(const char *sql);
1286 SQLITE_API int sqlite3_complete16(const void *sql);
1287
1288 /*
1289 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310}
1290 **
1291 ** {F12311} This routine identifies a callback function that might be
1292 ** invoked whenever an attempt is made to open a database table 
1293 ** that another thread or process has locked.
1294 ** {F12312} If the busy callback is NULL, then [SQLITE_BUSY]
1295 ** or [SQLITE_IOERR_BLOCKED]
1296 ** is returned immediately upon encountering the lock.
1297 ** {F12313} If the busy callback is not NULL, then the
1298 ** callback will be invoked with two arguments.  {F12314} The
1299 ** first argument to the handler is a copy of the void* pointer which
1300 ** is the third argument to this routine.  {F12315} The second argument to
1301 ** the handler is the number of times that the busy handler has
1302 ** been invoked for this locking event.  {F12316} If the
1303 ** busy callback returns 0, then no additional attempts are made to
1304 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
1305 ** {F12317} If the callback returns non-zero, then another attempt
1306 ** is made to open the database for reading and the cycle repeats.
1307 **
1308 ** The presence of a busy handler does not guarantee that
1309 ** it will be invoked when there is lock contention. {F12319}
1310 ** If SQLite determines that invoking the busy handler could result in
1311 ** a deadlock, it will go ahead and return [SQLITE_BUSY] or
1312 ** [SQLITE_IOERR_BLOCKED] instead of invoking the
1313 ** busy handler. {END}
1314 ** Consider a scenario where one process is holding a read lock that
1315 ** it is trying to promote to a reserved lock and
1316 ** a second process is holding a reserved lock that it is trying
1317 ** to promote to an exclusive lock.  The first process cannot proceed
1318 ** because it is blocked by the second and the second process cannot
1319 ** proceed because it is blocked by the first.  If both processes
1320 ** invoke the busy handlers, neither will make any progress.  Therefore,
1321 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
1322 ** will induce the first process to release its read lock and allow
1323 ** the second process to proceed.
1324 **
1325 ** {F12321} The default busy callback is NULL. {END}
1326 **
1327 ** {F12322} The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
1328 ** when SQLite is in the middle of a large transaction where all the
1329 ** changes will not fit into the in-memory cache.  {F12323} SQLite will
1330 ** already hold a RESERVED lock on the database file, but it needs
1331 ** to promote this lock to EXCLUSIVE so that it can spill cache
1332 ** pages into the database file without harm to concurrent
1333 ** readers.  {F12324} If it is unable to promote the lock, then the in-memory
1334 ** cache will be left in an inconsistent state and so the error
1335 ** code is promoted from the relatively benign [SQLITE_BUSY] to
1336 ** the more severe [SQLITE_IOERR_BLOCKED].  {F12325} This error code promotion
1337 ** forces an automatic rollback of the changes. {END} See the
1338 ** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError">
1339 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
1340 ** this is important.
1341 **      
1342 ** {F12326} Sqlite is re-entrant, so the busy handler may start a new
1343 ** query. {END} (It is not clear why anyone would every want to do this,
1344 ** but it is allowed, in theory.) {U12327} But the busy handler may not
1345 ** close the database.  Closing the database from a busy handler will delete 
1346 ** data structures out from under the executing query and will 
1347 ** probably result in a segmentation fault or other runtime error. {END}
1348 **
1349 ** {F12328} There can only be a single busy handler defined for each database
1350 ** connection.  Setting a new busy handler clears any previous one. 
1351 ** {F12329} Note that calling [sqlite3_busy_timeout()] will also set or clear
1352 ** the busy handler.
1353 **
1354 ** {F12331} When operating in [sqlite3_enable_shared_cache | shared cache mode],
1355 ** only a single busy handler can be defined for each database file.
1356 ** So if two database connections share a single cache, then changing
1357 ** the busy handler on one connection will also change the busy
1358 ** handler in the other connection.  {F12332} The busy handler is invoked
1359 ** in the thread that was running when the lock contention occurs.
1360 */
1361 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
1362
1363 /*
1364 ** CAPI3REF: Set A Busy Timeout {F12340}
1365 **
1366 ** {F12341} This routine sets a [sqlite3_busy_handler | busy handler]
1367 ** that sleeps for a while when a
1368 ** table is locked.  {F12342} The handler will sleep multiple times until 
1369 ** at least "ms" milliseconds of sleeping have been done. {F12343} After
1370 ** "ms" milliseconds of sleeping, the handler returns 0 which
1371 ** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
1372 **
1373 ** {F12344} Calling this routine with an argument less than or equal to zero
1374 ** turns off all busy handlers.
1375 **
1376 ** {F12345} There can only be a single busy handler for a particular database
1377 ** connection.  If another busy handler was defined  
1378 ** (using [sqlite3_busy_handler()]) prior to calling
1379 ** this routine, that other busy handler is cleared.
1380 */
1381 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
1382
1383 /*
1384 ** CAPI3REF: Convenience Routines For Running Queries {F12370}
1385 **
1386 ** This next routine is a convenience wrapper around [sqlite3_exec()].
1387 ** {F12371} Instead of invoking a user-supplied callback for each row of the
1388 ** result, this routine remembers each row of the result in memory
1389 ** obtained from [sqlite3_malloc()], then returns all of the result after the
1390 ** query has finished. {F12372}
1391 **
1392 ** As an example, suppose the query result where this table:
1393 **
1394 ** <blockquote><pre>
1395 **        Name        | Age
1396 **        -----------------------
1397 **        Alice       | 43
1398 **        Bob         | 28
1399 **        Cindy       | 21
1400 ** </pre></blockquote>
1401 **
1402 ** If the 3rd argument were &azResult then after the function returns
1403 ** azResult will contain the following data:
1404 **
1405 ** <blockquote><pre>
1406 **        azResult&#91;0] = "Name";
1407 **        azResult&#91;1] = "Age";
1408 **        azResult&#91;2] = "Alice";
1409 **        azResult&#91;3] = "43";
1410 **        azResult&#91;4] = "Bob";
1411 **        azResult&#91;5] = "28";
1412 **        azResult&#91;6] = "Cindy";
1413 **        azResult&#91;7] = "21";
1414 ** </pre></blockquote>
1415 **
1416 ** Notice that there is an extra row of data containing the column
1417 ** headers.  But the *nrow return value is still 3.  *ncolumn is
1418 ** set to 2.  In general, the number of values inserted into azResult
1419 ** will be ((*nrow) + 1)*(*ncolumn).
1420 **
1421 ** {U12374} After the calling function has finished using the result, it should 
1422 ** pass the result data pointer to sqlite3_free_table() in order to 
1423 ** release the memory that was malloc-ed.  Because of the way the 
1424 ** [sqlite3_malloc()] happens, the calling function must not try to call 
1425 ** [sqlite3_free()] directly.  Only [sqlite3_free_table()] is able to release 
1426 ** the memory properly and safely. {END}
1427 **
1428 ** {F12373} The return value of this routine is the same as
1429 ** from [sqlite3_exec()].
1430 */
1431 SQLITE_API int sqlite3_get_table(
1432   sqlite3*,              /* An open database */
1433   const char *sql,       /* SQL to be executed */
1434   char ***resultp,       /* Result written to a char *[]  that this points to */
1435   int *nrow,             /* Number of result rows written here */
1436   int *ncolumn,          /* Number of result columns written here */
1437   char **errmsg          /* Error msg written here */
1438 );
1439 SQLITE_API void sqlite3_free_table(char **result);
1440
1441 /*
1442 ** CAPI3REF: Formatted String Printing Functions {F17400}
1443 **
1444 ** These routines are workalikes of the "printf()" family of functions
1445 ** from the standard C library.
1446 **
1447 ** {F17401} The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
1448 ** results into memory obtained from [sqlite3_malloc()].
1449 ** {U17402} The strings returned by these two routines should be
1450 ** released by [sqlite3_free()]. {F17403}  Both routines return a
1451 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
1452 ** memory to hold the resulting string.
1453 **
1454 ** {F17404} In sqlite3_snprintf() routine is similar to "snprintf()" from
1455 ** the standard C library.  The result is written into the
1456 ** buffer supplied as the second parameter whose size is given by
1457 ** the first parameter. {END} Note that the order of the
1458 ** first two parameters is reversed from snprintf().  This is an
1459 ** historical accident that cannot be fixed without breaking
1460 ** backwards compatibility.  {F17405} Note also that sqlite3_snprintf()
1461 ** returns a pointer to its buffer instead of the number of
1462 ** characters actually written into the buffer. {END} We admit that
1463 ** the number of characters written would be a more useful return
1464 ** value but we cannot change the implementation of sqlite3_snprintf()
1465 ** now without breaking compatibility.
1466 **
1467 ** {F17406} As long as the buffer size is greater than zero, sqlite3_snprintf()
1468 ** guarantees that the buffer is always zero-terminated. {F17407} The first
1469 ** parameter "n" is the total size of the buffer, including space for
1470 ** the zero terminator.  {END} So the longest string that can be completely
1471 ** written will be n-1 characters.
1472 **
1473 ** These routines all implement some additional formatting
1474 ** options that are useful for constructing SQL statements.
1475 ** All of the usual printf formatting options apply.  In addition, there
1476 ** is are "%q", "%Q", and "%z" options.
1477 **
1478 ** {F17410} The %q option works like %s in that it substitutes a null-terminated
1479 ** string from the argument list.  But %q also doubles every '\'' character.
1480 ** %q is designed for use inside a string literal. {END} By doubling each '\''
1481 ** character it escapes that character and allows it to be inserted into
1482 ** the string.
1483 **
1484 ** For example, so some string variable contains text as follows:
1485 **
1486 ** <blockquote><pre>
1487 **  char *zText = "It's a happy day!";
1488 ** </pre></blockquote>
1489 **
1490 ** One can use this text in an SQL statement as follows:
1491 **
1492 ** <blockquote><pre>
1493 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
1494 **  sqlite3_exec(db, zSQL, 0, 0, 0);
1495 **  sqlite3_free(zSQL);
1496 ** </pre></blockquote>
1497 **
1498 ** Because the %q format string is used, the '\'' character in zText
1499 ** is escaped and the SQL generated is as follows:
1500 **
1501 ** <blockquote><pre>
1502 **  INSERT INTO table1 VALUES('It''s a happy day!')
1503 ** </pre></blockquote>
1504 **
1505 ** This is correct.  Had we used %s instead of %q, the generated SQL
1506 ** would have looked like this:
1507 **
1508 ** <blockquote><pre>
1509 **  INSERT INTO table1 VALUES('It's a happy day!');
1510 ** </pre></blockquote>
1511 **
1512 ** This second example is an SQL syntax error.  As a general rule you
1513 ** should always use %q instead of %s when inserting text into a string 
1514 ** literal.
1515 **
1516 ** {F17411} The %Q option works like %q except it also adds single quotes around
1517 ** the outside of the total string.  Or if the parameter in the argument
1518 ** list is a NULL pointer, %Q substitutes the text "NULL" (without single
1519 ** quotes) in place of the %Q option. {END}  So, for example, one could say:
1520 **
1521 ** <blockquote><pre>
1522 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
1523 **  sqlite3_exec(db, zSQL, 0, 0, 0);
1524 **  sqlite3_free(zSQL);
1525 ** </pre></blockquote>
1526 **
1527 ** The code above will render a correct SQL statement in the zSQL
1528 ** variable even if the zText variable is a NULL pointer.
1529 **
1530 ** {F17412} The "%z" formatting option works exactly like "%s" with the
1531 ** addition that after the string has been read and copied into
1532 ** the result, [sqlite3_free()] is called on the input string. {END}
1533 */
1534 SQLITE_API char *sqlite3_mprintf(const char*,...);
1535 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
1536 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
1537
1538 /*
1539 ** CAPI3REF: Memory Allocation Subsystem {F17300}
1540 **
1541 ** {F17301} The SQLite core  uses these three routines for all of its own
1542 ** internal memory allocation needs. {END}  "Core" in the previous sentence
1543 ** does not include operating-system specific VFS implementation.  The
1544 ** windows VFS uses native malloc and free for some operations.
1545 **
1546 ** {F17302} The sqlite3_malloc() routine returns a pointer to a block
1547 ** of memory at least N bytes in length, where N is the parameter.
1548 ** {F17303} If sqlite3_malloc() is unable to obtain sufficient free
1549 ** memory, it returns a NULL pointer.  {F17304} If the parameter N to
1550 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
1551 ** a NULL pointer.
1552 **
1553 ** {F17305} Calling sqlite3_free() with a pointer previously returned
1554 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
1555 ** that it might be reused.  {F17306} The sqlite3_free() routine is
1556 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
1557 ** to sqlite3_free() is harmless.  {U17307} After being freed, memory
1558 ** should neither be read nor written.  Even reading previously freed
1559 ** memory might result in a segmentation fault or other severe error.
1560 ** {U17309} Memory corruption, a segmentation fault, or other severe error
1561 ** might result if sqlite3_free() is called with a non-NULL pointer that
1562 ** was not obtained from sqlite3_malloc() or sqlite3_free().
1563 **
1564 ** {F17310} The sqlite3_realloc() interface attempts to resize a
1565 ** prior memory allocation to be at least N bytes, where N is the
1566 ** second parameter.  The memory allocation to be resized is the first
1567 ** parameter.  {F17311} If the first parameter to sqlite3_realloc()
1568 ** is a NULL pointer then its behavior is identical to calling
1569 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
1570 ** {F17312} If the second parameter to sqlite3_realloc() is zero or
1571 ** negative then the behavior is exactly the same as calling
1572 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
1573 ** {F17313} Sqlite3_realloc() returns a pointer to a memory allocation
1574 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
1575 ** {F17314} If M is the size of the prior allocation, then min(N,M) bytes
1576 ** of the prior allocation are copied into the beginning of buffer returned
1577 ** by sqlite3_realloc() and the prior allocation is freed.
1578 ** {F17315} If sqlite3_realloc() returns NULL, then the prior allocation
1579 ** is not freed.
1580 **
1581 ** {F17316} The memory returned by sqlite3_malloc() and sqlite3_realloc()
1582 ** is always aligned to at least an 8 byte boundary. {END}
1583 **
1584 ** {F17381} The default implementation
1585 ** of the memory allocation subsystem uses the malloc(), realloc()
1586 ** and free() provided by the standard C library. {F17382} However, if 
1587 ** SQLite is compiled with the following C preprocessor macro
1588 **
1589 ** <blockquote> SQLITE_MEMORY_SIZE=<i>NNN</i> </blockquote>
1590 **
1591 ** where <i>NNN</i> is an integer, then SQLite create a static
1592 ** array of at least <i>NNN</i> bytes in size and use that array
1593 ** for all of its dynamic memory allocation needs. {END}  Additional
1594 ** memory allocator options may be added in future releases.
1595 **
1596 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
1597 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
1598 ** implementation of these routines to be omitted.  That capability
1599 ** is no longer provided.  Only built-in memory allocators can be
1600 ** used.
1601 **
1602 ** The windows OS interface layer calls
1603 ** the system malloc() and free() directly when converting
1604 ** filenames between the UTF-8 encoding used by SQLite
1605 ** and whatever filename encoding is used by the particular windows
1606 ** installation.  Memory allocation errors are detected, but
1607 ** they are reported back as [SQLITE_CANTOPEN] or
1608 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
1609 */
1610 SQLITE_API void *sqlite3_malloc(int);
1611 SQLITE_API void *sqlite3_realloc(void*, int);
1612 SQLITE_API void sqlite3_free(void*);
1613
1614 /*
1615 ** CAPI3REF: Memory Allocator Statistics {F17370}
1616 **
1617 ** In addition to the basic three allocation routines 
1618 ** [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()],
1619 ** the memory allocation subsystem included with the SQLite
1620 ** sources provides the interfaces shown here.
1621 **
1622 ** {F17371} The sqlite3_memory_used() routine returns the
1623 ** number of bytes of memory currently outstanding (malloced but not freed).
1624 ** {F17372} The value returned by sqlite3_memory_used() includes
1625 ** any overhead added by SQLite, but not overhead added by the
1626 ** library malloc() that backs the sqlite3_malloc() implementation.
1627 ** {F17373} The sqlite3_memory_highwater() routines returns the
1628 ** maximum number of bytes that have been outstanding at any time
1629 ** since the highwater mark was last reset.
1630 ** {F17374} The byte count returned by sqlite3_memory_highwater()
1631 ** uses the same byte counting rules as sqlite3_memory_used(). {END}
1632 ** In other words, overhead added internally by SQLite is counted,
1633 ** but overhead from the underlying system malloc is not.
1634 ** {F17375} If the parameter to sqlite3_memory_highwater() is true,
1635 ** then the highwater mark is reset to the current value of
1636 ** sqlite3_memory_used() and the prior highwater mark (before the
1637 ** reset) is returned.  {F17376}  If the parameter to 
1638 ** sqlite3_memory_highwater() is zero, then the highwater mark is
1639 ** unchanged.
1640 */
1641 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
1642 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
1643
1644 /*
1645 ** CAPI3REF: Compile-Time Authorization Callbacks {F12500}
1646 **
1647 ** {F12501} This routine registers a authorizer callback with a particular
1648 ** database connection, supplied in the first argument. {F12502}
1649 ** The authorizer callback is invoked as SQL statements are being compiled
1650 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
1651 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  {F12503} At various
1652 ** points during the compilation process, as logic is being created
1653 ** to perform various actions, the authorizer callback is invoked to
1654 ** see if those actions are allowed.  The authorizer callback should
1655 ** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the
1656 ** specific action but allow the SQL statement to continue to be
1657 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
1658 ** rejected with an error.  {F12504} If the authorizer callback returns
1659 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
1660 ** then [sqlite3_prepare_v2()] or equivalent call that triggered
1661 ** the authorizer shall
1662 ** fail with an SQLITE_ERROR error code and an appropriate error message. {END}
1663 **
1664 ** When the callback returns [SQLITE_OK], that means the operation
1665 ** requested is ok.  {F12505} When the callback returns [SQLITE_DENY], the
1666 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
1667 ** authorizer shall fail
1668 ** with an SQLITE_ERROR error code and an error message explaining that
1669 ** access is denied. {F12506} If the authorizer code (the 2nd parameter
1670 ** to the authorizer callback is anything other than [SQLITE_READ], then
1671 ** a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. 
1672 ** If the authorizer code is [SQLITE_READ] and the callback returns
1673 ** [SQLITE_IGNORE] then the prepared statement is constructed to
1674 ** insert a NULL value in place of the table column that would have
1675 ** been read if [SQLITE_OK] had been returned. {END}
1676 **
1677 ** {F12510} The first parameter to the authorizer callback is a copy of
1678 ** the third parameter to the sqlite3_set_authorizer() interface.
1679 ** {F12511} The second parameter to the callback is an integer 
1680 ** [SQLITE_COPY | action code] that specifies the particular action
1681 ** to be authorized. {END} The available action codes are
1682 ** [SQLITE_COPY | documented separately].  {F12512} The third through sixth
1683 ** parameters to the callback are zero-terminated strings that contain 
1684 ** additional details about the action to be authorized. {END}
1685 **
1686 ** An authorizer is used when preparing SQL statements from an untrusted
1687 ** source, to ensure that the SQL statements do not try to access data
1688 ** that they are not allowed to see, or that they do not try to
1689 ** execute malicious statements that damage the database.  For
1690 ** example, an application may allow a user to enter arbitrary
1691 ** SQL queries for evaluation by a database.  But the application does
1692 ** not want the user to be able to make arbitrary changes to the
1693 ** database.  An authorizer could then be put in place while the
1694 ** user-entered SQL is being prepared that disallows everything
1695 ** except SELECT statements.  
1696 **
1697 ** {F12520} Only a single authorizer can be in place on a database connection
1698 ** at a time.  Each call to sqlite3_set_authorizer overrides the
1699 ** previous call. {F12521}  A NULL authorizer means that no authorization
1700 ** callback is invoked.  {F12522} The default authorizer is NULL. {END}
1701 **
1702 ** Note that the authorizer callback is invoked only during 
1703 ** [sqlite3_prepare()] or its variants.  {F12523} Authorization is not
1704 ** performed during statement evaluation in [sqlite3_step()]. {END}
1705 */
1706 SQLITE_API int sqlite3_set_authorizer(
1707   sqlite3*,
1708   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
1709   void *pUserData
1710 );
1711
1712 /*
1713 ** CAPI3REF: Authorizer Return Codes {F12590}
1714 **
1715 ** The [sqlite3_set_authorizer | authorizer callback function] must
1716 ** return either [SQLITE_OK] or one of these two constants in order
1717 ** to signal SQLite whether or not the action is permitted.  See the
1718 ** [sqlite3_set_authorizer | authorizer documentation] for additional
1719 ** information.
1720 */
1721 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
1722 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
1723
1724 /*
1725 ** CAPI3REF: Authorizer Action Codes {F12550}
1726 **
1727 ** The [sqlite3_set_authorizer()] interface registers a callback function
1728 ** that is invoked to authorizer certain SQL statement actions.  {F12551} The
1729 ** second parameter to the callback is an integer code that specifies
1730 ** what action is being authorized.  These are the integer action codes that
1731 ** the authorizer callback may be passed. {END}
1732 **
1733 ** These action code values signify what kind of operation is to be 
1734 ** authorized.  {F12552} The 3rd and 4th parameters to the authorization
1735 ** callback function will be parameters or NULL depending on which of these
1736 ** codes is used as the second parameter. {F12553} The 5th parameter to the
1737 ** authorizer callback is the name of the database ("main", "temp", 
1738 ** etc.) if applicable. {F12554} The 6th parameter to the authorizer callback
1739 ** is the name of the inner-most trigger or view that is responsible for
1740 ** the access attempt or NULL if this access attempt is directly from 
1741 ** top-level SQL code.
1742 */
1743 /******************************************* 3rd ************ 4th ***********/
1744 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
1745 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
1746 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
1747 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
1748 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
1749 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
1750 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
1751 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
1752 #define SQLITE_DELETE                9   /* Table Name      NULL            */
1753 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
1754 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
1755 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
1756 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
1757 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
1758 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
1759 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
1760 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
1761 #define SQLITE_INSERT               18   /* Table Name      NULL            */
1762 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
1763 #define SQLITE_READ                 20   /* Table Name      Column Name     */
1764 #define SQLITE_SELECT               21   /* NULL            NULL            */
1765 #define SQLITE_TRANSACTION          22   /* NULL            NULL            */
1766 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
1767 #define SQLITE_ATTACH               24   /* Filename        NULL            */
1768 #define SQLITE_DETACH               25   /* Database Name   NULL            */
1769 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
1770 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
1771 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
1772 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
1773 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
1774 #define SQLITE_FUNCTION             31   /* Function Name   NULL            */
1775 #define SQLITE_COPY                  0   /* No longer used */
1776
1777 /*
1778 ** CAPI3REF: Tracing And Profiling Functions {F12280}
1779 **
1780 ** These routines register callback functions that can be used for
1781 ** tracing and profiling the execution of SQL statements.
1782 **
1783 ** {F12281} The callback function registered by sqlite3_trace() is invoked
1784 ** at the first [sqlite3_step()] for the evaluation of an SQL statement.
1785 ** {F12282} Only a single trace callback can be registered at a time.
1786 ** Each call to sqlite3_trace() overrides the previous.  {F12283} A
1787 ** NULL callback for sqlite3_trace() disables tracing.  {F12284} The
1788 ** first argument to the trace callback is a copy of the pointer which
1789 ** was the 3rd argument to sqlite3_trace.  {F12285} The second argument
1790 ** to the trace callback is a zero-terminated UTF8 string containing
1791 ** the original text of the SQL statement as it was passed into
1792 ** [sqlite3_prepare_v2()] or the equivalent. {END}  Note that the
1793 ** host parameter are not expanded in the SQL statement text.
1794 **
1795 ** {F12287} The callback function registered by sqlite3_profile() is invoked
1796 ** as each SQL statement finishes.  {F12288} The first parameter to the
1797 ** profile callback is a copy of the 3rd parameter to sqlite3_profile().
1798 ** {F12289} The second parameter to the profile callback is a
1799 ** zero-terminated UTF-8 string that contains the complete text of
1800 ** the SQL statement as it was processed by [sqlite3_prepare_v2()] or
1801 ** the equivalent.  {F12290} The third parameter to the profile 
1802 ** callback is an estimate of the number of nanoseconds of
1803 ** wall-clock time required to run the SQL statement from start
1804 ** to finish. {END}  
1805 **
1806 ** The sqlite3_profile() API is currently considered experimental and
1807 ** is subject to change.
1808 */
1809 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
1810 SQLITE_API void *sqlite3_profile(sqlite3*,
1811    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
1812
1813 /*
1814 ** CAPI3REF: Query Progress Callbacks {F12910}
1815 **
1816 ** {F12911} This routine configures a callback function - the
1817 ** progress callback - that is invoked periodically during long
1818 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
1819 ** [sqlite3_get_table()]. {END}  An example use for this 
1820 ** interface is to keep a GUI updated during a large query.
1821 **
1822 ** {F12912} The progress callback is invoked once for every N virtual
1823 ** machine opcodes, where N is the second argument to this function.
1824 ** {F12913} The progress callback itself is identified by the third
1825 ** argument to this function. {F12914} The fourth argument to this
1826 ** function is a void pointer passed to the progress callback
1827 ** function each time it is invoked. {END}
1828 **
1829 ** {F12915} If a call to [sqlite3_exec()], [sqlite3_step()], or
1830 ** [sqlite3_get_table()] results in fewer than N opcodes being executed,
1831 ** then the progress callback is never invoked. {END}
1832 ** 
1833 ** {F12916} Only a single progress callback function may be registered for each
1834 ** open database connection.  Every call to sqlite3_progress_handler()
1835 ** overwrites the results of the previous call. {F12917}
1836 ** To remove the progress callback altogether, pass NULL as the third
1837 ** argument to this function. {END}
1838 **
1839 ** {F12918} If the progress callback returns a result other than 0, then
1840 ** the current query is immediately terminated and any database changes
1841 ** rolled back. {F12919}
1842 ** The containing [sqlite3_exec()], [sqlite3_step()], or
1843 ** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. {END}  This feature
1844 ** can be used, for example, to implement the "Cancel" button on a
1845 ** progress dialog box in a GUI.
1846 */
1847 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
1848
1849 /*
1850 ** CAPI3REF: Opening A New Database Connection {F12700}
1851 **
1852 ** {F12701} These routines open an SQLite database file whose name
1853 ** is given by the filename argument.
1854 ** {F12702} The filename argument is interpreted as UTF-8
1855 ** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16
1856 ** in the native byte order for [sqlite3_open16()].
1857 ** {F12703} An [sqlite3*] handle is returned in *ppDb, even
1858 ** if an error occurs.  {F12723} (Exception: if SQLite is unable
1859 ** to allocate memory to hold the [sqlite3] object, a NULL will
1860 ** be written into *ppDb instead of a pointer to the [sqlite3] object.)
1861 ** {F12704} If the database is opened (and/or created)
1862 ** successfully, then [SQLITE_OK] is returned.  {F12705} Otherwise an
1863 ** error code is returned.  {F12706} The
1864 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()]  routines can be used to obtain
1865 ** an English language description of the error.
1866 **
1867 ** {F12707} The default encoding for the database will be UTF-8 if
1868 ** [sqlite3_open()] or [sqlite3_open_v2()] is called and
1869 ** UTF-16 in the native byte order if [sqlite3_open16()] is used.
1870 **
1871 ** {F12708} Whether or not an error occurs when it is opened, resources
1872 ** associated with the [sqlite3*] handle should be released by passing it
1873 ** to [sqlite3_close()] when it is no longer required.
1874 **
1875 ** {F12709} The [sqlite3_open_v2()] interface works like [sqlite3_open()] 
1876 ** except that it acccepts two additional parameters for additional control
1877 ** over the new database connection.  {F12710} The flags parameter can be
1878 ** one of:
1879 **
1880 ** <ol>
1881 ** <li>  [SQLITE_OPEN_READONLY]
1882 ** <li>  [SQLITE_OPEN_READWRITE]
1883 ** <li>  [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
1884 ** </ol>
1885 **
1886 ** {F12711} The first value opens the database read-only. 
1887 ** {F12712} If the database does not previously exist, an error is returned.
1888 ** {F12713} The second option opens
1889 ** the database for reading and writing if possible, or reading only if
1890 ** if the file is write protected.  {F12714} In either case the database
1891 ** must already exist or an error is returned.  {F12715} The third option
1892 ** opens the database for reading and writing and creates it if it does
1893 ** not already exist. {F12716}
1894 ** The third options is behavior that is always used for [sqlite3_open()]
1895 ** and [sqlite3_open16()].
1896 **
1897 ** {F12717} If the filename is ":memory:", then an private
1898 ** in-memory database is created for the connection. {F12718} This in-memory
1899 ** database will vanish when the database connection is closed. {END}  Future
1900 ** version of SQLite might make use of additional special filenames
1901 ** that begin with the ":" character.  It is recommended that 
1902 ** when a database filename really does begin with
1903 ** ":" that you prefix the filename with a pathname like "./" to
1904 ** avoid ambiguity.
1905 **
1906 ** {F12719} If the filename is an empty string, then a private temporary
1907 ** on-disk database will be created.  {F12720} This private database will be
1908 ** automatically deleted as soon as the database connection is closed.
1909 **
1910 ** {F12721} The fourth parameter to sqlite3_open_v2() is the name of the
1911 ** [sqlite3_vfs] object that defines the operating system 
1912 ** interface that the new database connection should use.  {F12722} If the
1913 ** fourth parameter is a NULL pointer then the default [sqlite3_vfs]
1914 ** object is used. {END}
1915 **
1916 ** <b>Note to windows users:</b>  The encoding used for the filename argument
1917 ** of [sqlite3_open()] and [sqlite3_open_v2()] must be UTF-8, not whatever
1918 ** codepage is currently defined.  Filenames containing international
1919 ** characters must be converted to UTF-8 prior to passing them into
1920 ** [sqlite3_open()] or [sqlite3_open_v2()].
1921 */
1922 SQLITE_API int sqlite3_open(
1923   const char *filename,   /* Database filename (UTF-8) */
1924   sqlite3 **ppDb          /* OUT: SQLite db handle */
1925 );
1926 SQLITE_API int sqlite3_open16(
1927   const void *filename,   /* Database filename (UTF-16) */
1928   sqlite3 **ppDb          /* OUT: SQLite db handle */
1929 );
1930 SQLITE_API int sqlite3_open_v2(
1931   const char *filename,   /* Database filename (UTF-8) */
1932   sqlite3 **ppDb,         /* OUT: SQLite db handle */
1933   int flags,              /* Flags */
1934   const char *zVfs        /* Name of VFS module to use */
1935 );
1936
1937 /*
1938 ** CAPI3REF: Error Codes And Messages {F12800}
1939 **
1940 ** {F12801} The sqlite3_errcode() interface returns the numeric
1941 ** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code]
1942 ** for the most recent failed sqlite3_* API call associated
1943 ** with [sqlite3] handle 'db'. {U12802} If a prior API call failed but the
1944 ** most recent API call succeeded, the return value from sqlite3_errcode()
1945 ** is undefined. {END}
1946 **
1947 ** {F12803} The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
1948 ** text that describes the error, as either UTF8 or UTF16 respectively.
1949 ** {F12804} Memory to hold the error message string is managed internally.
1950 ** {U12805} The 
1951 ** string may be overwritten or deallocated by subsequent calls to SQLite
1952 ** interface functions. {END}
1953 **
1954 ** {F12806} Calls to many sqlite3_* functions set the error code and
1955 ** string returned by [sqlite3_errcode()], [sqlite3_errmsg()], and
1956 ** [sqlite3_errmsg16()] overwriting the previous values.  {F12807}
1957 ** Except, calls to [sqlite3_errcode()],
1958 ** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the
1959 ** results of future invocations.  {F12808} Calls to API routines that
1960 ** do not return an error code (example: [sqlite3_data_count()]) do not
1961 ** change the error code returned by this routine.  {F12809} Interfaces that
1962 ** are not associated with a specific database connection (examples:
1963 ** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change
1964 ** the return code. {END}
1965 **
1966 ** {F12810} Assuming no other intervening sqlite3_* API calls are made,
1967 ** the error code returned by this function is associated with the same
1968 ** error as the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()].
1969 */
1970 SQLITE_API int sqlite3_errcode(sqlite3 *db);
1971 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
1972 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
1973
1974 /*
1975 ** CAPI3REF: SQL Statement Object {F13000}
1976 **
1977 ** An instance of this object represent single SQL statements.  This
1978 ** object is variously known as a "prepared statement" or a 
1979 ** "compiled SQL statement" or simply as a "statement".
1980 ** 
1981 ** The life of a statement object goes something like this:
1982 **
1983 ** <ol>
1984 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
1985 **      function.
1986 ** <li> Bind values to host parameters using
1987 **      [sqlite3_bind_blob | sqlite3_bind_* interfaces].
1988 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
1989 ** <li> Reset the statement using [sqlite3_reset()] then go back
1990 **      to step 2.  Do this zero or more times.
1991 ** <li> Destroy the object using [sqlite3_finalize()].
1992 ** </ol>
1993 **
1994 ** Refer to documentation on individual methods above for additional
1995 ** information.
1996 */
1997 typedef struct sqlite3_stmt sqlite3_stmt;
1998
1999 /*
2000 ** CAPI3REF: Compiling An SQL Statement {F13010}
2001 **
2002 ** To execute an SQL query, it must first be compiled into a byte-code
2003 ** program using one of these routines. 
2004 **
2005 ** {F13011} The first argument "db" is an [sqlite3 | SQLite database handle] 
2006 ** obtained from a prior call to [sqlite3_open()], [sqlite3_open_v2()]
2007 ** or [sqlite3_open16()]. {F13012}
2008 ** The second argument "zSql" is the statement to be compiled, encoded
2009 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
2010 ** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2()
2011 ** use UTF-16. {END}
2012 **
2013 ** {F13013} If the nByte argument is less
2014 ** than zero, then zSql is read up to the first zero terminator.
2015 ** {F13014} If nByte is non-negative, then it is the maximum number of 
2016 ** bytes read from zSql.  When nByte is non-negative, the
2017 ** zSql string ends at either the first '\000' or '\u0000' character or 
2018 ** until the nByte-th byte, whichever comes first. {END}
2019 **
2020 ** {F13015} *pzTail is made to point to the first byte past the end of the
2021 ** first SQL statement in zSql.  These routines only compiles the first
2022 ** statement in zSql, so *pzTail is left pointing to what remains
2023 ** uncompiled. {END}
2024 **
2025 ** {F13016} *ppStmt is left pointing to a compiled 
2026 ** [sqlite3_stmt | SQL statement structure] that can be
2027 ** executed using [sqlite3_step()].  Or if there is an error, *ppStmt may be
2028 ** set to NULL.  {F13017} If the input text contains no SQL (if the input
2029 ** is and empty string or a comment) then *ppStmt is set to NULL.
2030 ** {U13018} The calling procedure is responsible for deleting the
2031 ** compiled SQL statement
2032 ** using [sqlite3_finalize()] after it has finished with it.
2033 **
2034 ** {F13019} On success, [SQLITE_OK] is returned.  Otherwise an 
2035 ** [SQLITE_ERROR | error code] is returned. {END}
2036 **
2037 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
2038 ** recommended for all new programs. The two older interfaces are retained
2039 ** for backwards compatibility, but their use is discouraged.
2040 ** {F13020} In the "v2" interfaces, the prepared statement
2041 ** that is returned (the [sqlite3_stmt] object) contains a copy of the 
2042 ** original SQL text. {END} This causes the [sqlite3_step()] interface to
2043 ** behave a differently in two ways:
2044 **
2045 ** <ol>
2046 ** <li>{F13022}
2047 ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
2048 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
2049 ** statement and try to run it again. {F12023} If the schema has changed in
2050 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
2051 ** return [SQLITE_SCHEMA].  {END} But unlike the legacy behavior, 
2052 ** [SQLITE_SCHEMA] is now a fatal error.  {F12024} Calling
2053 ** [sqlite3_prepare_v2()] again will not make the
2054 ** error go away.  {F12025} Note: use [sqlite3_errmsg()] to find the text
2055 ** of the parsing error that results in an [SQLITE_SCHEMA] return. {END}
2056 ** </li>
2057 **
2058 ** <li>
2059 ** {F13030} When an error occurs, 
2060 ** [sqlite3_step()] will return one of the detailed 
2061 ** [SQLITE_ERROR | result codes] or
2062 ** [SQLITE_IOERR_READ | extended result codes].  {F13031}
2063 ** The legacy behavior was that [sqlite3_step()] would only return a generic
2064 ** [SQLITE_ERROR] result code and you would have to make a second call to
2065 ** [sqlite3_reset()] in order to find the underlying cause of the problem.
2066 ** {F13032}
2067 ** With the "v2" prepare interfaces, the underlying reason for the error is
2068 ** returned immediately. {END}
2069 ** </li>
2070 ** </ol>
2071 */
2072 SQLITE_API int sqlite3_prepare(
2073   sqlite3 *db,            /* Database handle */
2074   const char *zSql,       /* SQL statement, UTF-8 encoded */
2075   int nByte,              /* Maximum length of zSql in bytes. */
2076   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2077   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
2078 );
2079 SQLITE_API int sqlite3_prepare_v2(
2080   sqlite3 *db,            /* Database handle */
2081   const char *zSql,       /* SQL statement, UTF-8 encoded */
2082   int nByte,              /* Maximum length of zSql in bytes. */
2083   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2084   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
2085 );
2086 SQLITE_API int sqlite3_prepare16(
2087   sqlite3 *db,            /* Database handle */
2088   const void *zSql,       /* SQL statement, UTF-16 encoded */
2089   int nByte,              /* Maximum length of zSql in bytes. */
2090   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2091   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
2092 );
2093 SQLITE_API int sqlite3_prepare16_v2(
2094   sqlite3 *db,            /* Database handle */
2095   const void *zSql,       /* SQL statement, UTF-16 encoded */
2096   int nByte,              /* Maximum length of zSql in bytes. */
2097   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2098   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
2099 );
2100
2101 /*
2102 ** CAPIREF: Retrieving Statement SQL {F13100}
2103 **
2104 ** {F13101} If the compiled SQL statement passed as an argument was
2105 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()],
2106 ** then this function returns a pointer to a zero-terminated string
2107 ** containing a copy of the original SQL statement. {F13102} The
2108 ** pointer is valid until the statement
2109 ** is deleted using sqlite3_finalize().
2110 ** {F13103} The string returned by sqlite3_sql() is always UTF8 even
2111 ** if a UTF16 string was originally entered using [sqlite3_prepare16_v2()]
2112 ** or the equivalent.
2113 **
2114 ** {F13104} If the statement was compiled using either of the legacy
2115 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this
2116 ** function returns NULL.
2117 */
2118 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
2119
2120 /*
2121 ** CAPI3REF:  Dynamically Typed Value Object  {F15000}
2122 **
2123 ** {F15001} SQLite uses the sqlite3_value object to represent all values
2124 ** that are or can be stored in a database table. {END}
2125 ** SQLite uses dynamic typing for the values it stores.  
2126 ** {F15002} Values stored in sqlite3_value objects can be
2127 ** be integers, floating point values, strings, BLOBs, or NULL.
2128 */
2129 typedef struct Mem sqlite3_value;
2130
2131 /*
2132 ** CAPI3REF:  SQL Function Context Object {F16001}
2133 **
2134 ** The context in which an SQL function executes is stored in an
2135 ** sqlite3_context object.  {F16002} A pointer to an sqlite3_context
2136 ** object is always first parameter to application-defined SQL functions.
2137 */
2138 typedef struct sqlite3_context sqlite3_context;
2139
2140 /*
2141 ** CAPI3REF:  Binding Values To Prepared Statements {F13500}
2142 **
2143 ** {F13501} In the SQL strings input to [sqlite3_prepare_v2()] and its
2144 ** variants, literals may be replace by a parameter in one
2145 ** of these forms:
2146 **
2147 ** <ul>
2148 ** <li>  ?
2149 ** <li>  ?NNN
2150 ** <li>  :AAA
2151 ** <li>  @AAA
2152 ** <li>  $VVV
2153 ** </ul>
2154 **
2155 ** In the parameter forms shown above NNN is an integer literal,
2156 ** AAA is an alphanumeric identifier and VVV is a variable name according
2157 ** to the syntax rules of the TCL programming language. {END}
2158 ** The values of these parameters (also called "host parameter names")
2159 ** can be set using the sqlite3_bind_*() routines defined here.
2160 **
2161 ** {F13502} The first argument to the sqlite3_bind_*() routines always
2162 ** is a pointer to the [sqlite3_stmt] object returned from
2163 ** [sqlite3_prepare_v2()] or its variants.  {F13503} The second
2164 ** argument is the index of the parameter to be set.  {F13504} The
2165 ** first parameter has an index of 1.  {F13505} When the same named
2166 ** parameter is used more than once, second and subsequent
2167 ** occurrences have the same index as the first occurrence. 
2168 ** {F13506} The index for named parameters can be looked up using the
2169 ** [sqlite3_bind_parameter_name()] API if desired.  {F13507} The index
2170 ** for "?NNN" parameters is the value of NNN.
2171 ** {F13508} The NNN value must be between 1 and the compile-time
2172 ** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). {END}
2173 ** See <a href="limits.html">limits.html</a> for additional information.
2174 **
2175 ** {F13509} The third argument is the value to bind to the parameter. {END}
2176 **
2177 ** {F13510} In those
2178 ** routines that have a fourth argument, its value is the number of bytes
2179 ** in the parameter.  To be clear: the value is the number of bytes in the
2180 ** string, not the number of characters. {F13511}  The number
2181 ** of bytes does not include the zero-terminator at the end of strings.
2182 ** {F13512}
2183 ** If the fourth parameter is negative, the length of the string is
2184 ** number of bytes up to the first zero terminator. {END}
2185 **
2186 ** {F13513}
2187 ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
2188 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
2189 ** text after SQLite has finished with it. {F13514} If the fifth argument is
2190 ** the special value [SQLITE_STATIC], then the library assumes that the
2191 ** information is in static, unmanaged space and does not need to be freed.
2192 ** {F13515} If the fifth argument has the value [SQLITE_TRANSIENT], then
2193 ** SQLite makes its own private copy of the data immediately, before
2194 ** the sqlite3_bind_*() routine returns. {END}
2195 **
2196 ** {F13520} The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
2197 ** is filled with zeros.  {F13521} A zeroblob uses a fixed amount of memory
2198 ** (just an integer to hold it size) while it is being processed. {END}
2199 ** Zeroblobs are intended to serve as place-holders for BLOBs whose
2200 ** content is later written using 
2201 ** [sqlite3_blob_open | increment BLOB I/O] routines. {F13522} A negative
2202 ** value for the zeroblob results in a zero-length BLOB. {END}
2203 **
2204 ** {F13530} The sqlite3_bind_*() routines must be called after
2205 ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and
2206 ** before [sqlite3_step()]. {F13531}
2207 ** Bindings are not cleared by the [sqlite3_reset()] routine.
2208 ** {F13532} Unbound parameters are interpreted as NULL. {END}
2209 **
2210 ** {F13540} These routines return [SQLITE_OK] on success or an error code if
2211 ** anything goes wrong.  {F13541} [SQLITE_RANGE] is returned if the parameter
2212 ** index is out of range.  {F13542} [SQLITE_NOMEM] is returned if malloc fails.
2213 ** {F13543} [SQLITE_MISUSE] is returned if these routines are called on a
2214 ** virtual machine that is the wrong state or which has already been finalized.
2215 */
2216 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
2217 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
2218 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
2219 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
2220 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
2221 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
2222 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
2223 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
2224 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
2225
2226 /*
2227 ** CAPI3REF: Number Of Host Parameters {F13600}
2228 **
2229 ** {F13601} Return the largest host parameter index in the precompiled
2230 ** statement given as the argument. {F13602} When the host parameters
2231 ** are of the forms like ":AAA", "$VVV", "@AAA", or "?",
2232 ** then they are assigned sequential increasing numbers beginning
2233 ** with one, so the value returned is the number of parameters.
2234 ** {F13603} However
2235 ** if the same host parameter name is used multiple times, each occurrance
2236 ** is given the same number, so the value returned in that case is the number
2237 ** of unique host parameter names. {F13604} If host parameters of the
2238 ** form "?NNN" are used (where NNN is an integer) then there might be
2239 ** gaps in the numbering and the value returned by this interface is
2240 ** the index of the host parameter with the largest index value. {END}
2241 **
2242 ** {U13605} The prepared statement must not be [sqlite3_finalize | finalized]
2243 ** prior to this routine returning.  Otherwise the results are undefined
2244 ** and probably undesirable.
2245 */
2246 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
2247
2248 /*
2249 ** CAPI3REF: Name Of A Host Parameter {F13620}
2250 **
2251 ** {F13621} This routine returns a pointer to the name of the n-th
2252 ** parameter in a [sqlite3_stmt | prepared statement]. {F13622}
2253 ** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name
2254 ** which is the string ":AAA" or "@AAA" or "$VVV". 
2255 ** In other words, the initial ":" or "$" or "@"
2256 ** is included as part of the name.  {F13626}
2257 ** Parameters of the form "?" or "?NNN" have no name.
2258 **
2259 ** {F13623} The first host parameter has an index of 1, not 0.
2260 **
2261 ** {F13624} If the value n is out of range or if the n-th parameter is
2262 ** nameless, then NULL is returned.  {F13625} The returned string is
2263 ** always in the UTF-8 encoding even if the named parameter was
2264 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
2265 ** [sqlite3_prepare16_v2()].
2266 */
2267 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
2268
2269 /*
2270 ** CAPI3REF: Index Of A Parameter With A Given Name {F13640}
2271 **
2272 ** {F13641} This routine returns the index of a host parameter with the
2273 ** given name.  {F13642} The name must match exactly.  {F13643}
2274 ** If no parameter with the given name is found, return 0.
2275 ** {F13644} Parameter names must be UTF8.
2276 */
2277 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
2278
2279 /*
2280 ** CAPI3REF: Reset All Bindings On A Prepared Statement {F13660}
2281 **
2282 ** {F13661} Contrary to the intuition of many, [sqlite3_reset()] does not
2283 ** reset the [sqlite3_bind_blob | bindings] on a 
2284 ** [sqlite3_stmt | prepared statement]. {F13662} Use this routine to
2285 ** reset all host parameters to NULL.
2286 */
2287 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
2288
2289 /*
2290 ** CAPI3REF: Number Of Columns In A Result Set {F13710}
2291 **
2292 ** {F13711} Return the number of columns in the result set returned by the 
2293 ** [sqlite3_stmt | compiled SQL statement]. {F13712} This routine returns 0
2294 ** if pStmt is an SQL statement that does not return data (for 
2295 ** example an UPDATE).
2296 */
2297 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
2298
2299 /*
2300 ** CAPI3REF: Column Names In A Result Set {F13720}
2301 **
2302 ** {F13721} These routines return the name assigned to a particular column
2303 ** in the result set of a SELECT statement.  {F13722} The sqlite3_column_name()
2304 ** interface returns a pointer to a zero-terminated UTF8 string
2305 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
2306 ** UTF16 string. {F13723}  The first parameter is the
2307 ** [sqlite3_stmt | prepared statement] that implements the SELECT statement.
2308 ** The second parameter is the column number.  The left-most column is
2309 ** number 0.
2310 **
2311 ** {F13724} The returned string pointer is valid until either the 
2312 ** [sqlite3_stmt | prepared statement] is destroyed by [sqlite3_finalize()]
2313 ** or until the next call sqlite3_column_name() or sqlite3_column_name16()
2314 ** on the same column.
2315 **
2316 ** {F13725} If sqlite3_malloc() fails during the processing of either routine
2317 ** (for example during a conversion from UTF-8 to UTF-16) then a
2318 ** NULL pointer is returned.
2319 */
2320 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
2321 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
2322
2323 /*
2324 ** CAPI3REF: Source Of Data In A Query Result {F13740}
2325 **
2326 ** {F13741} These routines provide a means to determine what column of what
2327 ** table in which database a result of a SELECT statement comes from.
2328 ** {F13742} The name of the database or table or column can be returned as
2329 ** either a UTF8 or UTF16 string.  {F13743} The _database_ routines return
2330 ** the database name, the _table_ routines return the table name, and
2331 ** the origin_ routines return the column name. {F13744}
2332 ** The returned string is valid until
2333 ** the [sqlite3_stmt | prepared statement] is destroyed using
2334 ** [sqlite3_finalize()] or until the same information is requested
2335 ** again in a different encoding.
2336 **
2337 ** {F13745} The names returned are the original un-aliased names of the
2338 ** database, table, and column.
2339 **
2340 ** {F13746} The first argument to the following calls is a 
2341 ** [sqlite3_stmt | compiled SQL statement].
2342 ** {F13747} These functions return information about the Nth column returned by 
2343 ** the statement, where N is the second function argument.
2344 **
2345 ** {F13748} If the Nth column returned by the statement is an expression
2346 ** or subquery and is not a column value, then all of these functions
2347 ** return NULL.  {F13749} Otherwise, they return the 
2348 ** name of the attached database, table and column that query result
2349 ** column was extracted from.
2350 **
2351 ** {F13750} As with all other SQLite APIs, those postfixed with "16" return
2352 ** UTF-16 encoded strings, the other functions return UTF-8. {END}
2353 **
2354 ** These APIs are only available if the library was compiled with the 
2355 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
2356 **
2357 ** {U13751}
2358 ** If two or more threads call one or more of these routines against the same
2359 ** prepared statement and column at the same time then the results are
2360 ** undefined.
2361 */
2362 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
2363 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
2364 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
2365 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
2366 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
2367 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
2368
2369 /*
2370 ** CAPI3REF: Declared Datatype Of A Query Result {F13760}
2371 **
2372 ** The first parameter is a [sqlite3_stmt | compiled SQL statement]. 
2373 ** {F13761} If this statement is a SELECT statement and the Nth column of the 
2374 ** returned result set of that SELECT is a table column (not an
2375 ** expression or subquery) then the declared type of the table
2376 ** column is returned.  {F13762} If the Nth column of the result set is an
2377 ** expression or subquery, then a NULL pointer is returned.
2378 ** {F13763} The returned string is always UTF-8 encoded.  {END} 
2379 ** For example, in the database schema:
2380 **
2381 ** CREATE TABLE t1(c1 VARIANT);
2382 **
2383 ** And the following statement compiled:
2384 **
2385 ** SELECT c1 + 1, c1 FROM t1;
2386 **
2387 ** Then this routine would return the string "VARIANT" for the second
2388 ** result column (i==1), and a NULL pointer for the first result column
2389 ** (i==0).
2390 **
2391 ** SQLite uses dynamic run-time typing.  So just because a column
2392 ** is declared to contain a particular type does not mean that the
2393 ** data stored in that column is of the declared type.  SQLite is
2394 ** strongly typed, but the typing is dynamic not static.  Type
2395 ** is associated with individual values, not with the containers
2396 ** used to hold those values.
2397 */
2398 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *, int i);
2399 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
2400
2401 /* 
2402 ** CAPI3REF:  Evaluate An SQL Statement {F13200}
2403 **
2404 ** After an [sqlite3_stmt | SQL statement] has been prepared with a call
2405 ** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of
2406 ** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()],
2407 ** then this function must be called one or more times to evaluate the 
2408 ** statement.
2409 **
2410 ** The details of the behavior of this sqlite3_step() interface depend
2411 ** on whether the statement was prepared using the newer "v2" interface
2412 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
2413 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
2414 ** new "v2" interface is recommended for new applications but the legacy
2415 ** interface will continue to be supported.
2416 **
2417 ** In the lagacy interface, the return value will be either [SQLITE_BUSY], 
2418 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
2419 ** With the "v2" interface, any of the other [SQLITE_OK | result code]
2420 ** or [SQLITE_IOERR_READ | extended result code] might be returned as
2421 ** well.
2422 **
2423 ** [SQLITE_BUSY] means that the database engine was unable to acquire the
2424 ** database locks it needs to do its job.  If the statement is a COMMIT
2425 ** or occurs outside of an explicit transaction, then you can retry the
2426 ** statement.  If the statement is not a COMMIT and occurs within a
2427 ** explicit transaction then you should rollback the transaction before
2428 ** continuing.
2429 **
2430 ** [SQLITE_DONE] means that the statement has finished executing
2431 ** successfully.  sqlite3_step() should not be called again on this virtual
2432 ** machine without first calling [sqlite3_reset()] to reset the virtual
2433 ** machine back to its initial state.
2434 **
2435 ** If the SQL statement being executed returns any data, then 
2436 ** [SQLITE_ROW] is returned each time a new row of data is ready
2437 ** for processing by the caller. The values may be accessed using
2438 ** the [sqlite3_column_int | column access functions].
2439 ** sqlite3_step() is called again to retrieve the next row of data.
2440 ** 
2441 ** [SQLITE_ERROR] means that a run-time error (such as a constraint
2442 ** violation) has occurred.  sqlite3_step() should not be called again on
2443 ** the VM. More information may be found by calling [sqlite3_errmsg()].
2444 ** With the legacy interface, a more specific error code (example:
2445 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
2446 ** can be obtained by calling [sqlite3_reset()] on the
2447 ** [sqlite3_stmt | prepared statement].  In the "v2" interface,
2448 ** the more specific error code is returned directly by sqlite3_step().
2449 **
2450 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
2451 ** Perhaps it was called on a [sqlite3_stmt | prepared statement] that has
2452 ** already been [sqlite3_finalize | finalized] or on one that had 
2453 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
2454 ** be the case that the same database connection is being used by two or
2455 ** more threads at the same moment in time.
2456 **
2457 ** <b>Goofy Interface Alert:</b>
2458 ** In the legacy interface, 
2459 ** the sqlite3_step() API always returns a generic error code,
2460 ** [SQLITE_ERROR], following any error other than [SQLITE_BUSY]
2461 ** and [SQLITE_MISUSE].  You must call [sqlite3_reset()] or
2462 ** [sqlite3_finalize()] in order to find one of the specific
2463 ** [SQLITE_ERROR | result codes] that better describes the error.
2464 ** We admit that this is a goofy design.  The problem has been fixed
2465 ** with the "v2" interface.  If you prepare all of your SQL statements
2466 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
2467 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the 
2468 ** more specific [SQLITE_ERROR | result codes] are returned directly
2469 ** by sqlite3_step().  The use of the "v2" interface is recommended.
2470 */
2471 SQLITE_API int sqlite3_step(sqlite3_stmt*);
2472
2473 /*
2474 ** CAPI3REF: Number of columns in a result set {F13770}
2475 **
2476 ** Return the number of values in the current row of the result set.
2477 **
2478 ** {F13771} After a call to [sqlite3_step()] that returns [SQLITE_ROW],
2479 ** this routine
2480 ** will return the same value as the [sqlite3_column_count()] function.
2481 ** {F13772}
2482 ** After [sqlite3_step()] has returned an [SQLITE_DONE], [SQLITE_BUSY], or
2483 ** a [SQLITE_ERROR | error code], or before [sqlite3_step()] has been 
2484 ** called on the [sqlite3_stmt | prepared statement] for the first time,
2485 ** this routine returns zero.
2486 */
2487 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
2488
2489 /*
2490 ** CAPI3REF: Fundamental Datatypes {F10265}
2491 **
2492 ** {F10266}Every value in SQLite has one of five fundamental datatypes:
2493 **
2494 ** <ul>
2495 ** <li> 64-bit signed integer
2496 ** <li> 64-bit IEEE floating point number
2497 ** <li> string
2498 ** <li> BLOB
2499 ** <li> NULL
2500 ** </ul> {END}
2501 **
2502 ** These constants are codes for each of those types.
2503 **
2504 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
2505 ** for a completely different meaning.  Software that links against both
2506 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not
2507 ** SQLITE_TEXT.
2508 */
2509 #define SQLITE_INTEGER  1
2510 #define SQLITE_FLOAT    2
2511 #define SQLITE_BLOB     4
2512 #define SQLITE_NULL     5
2513 #ifdef SQLITE_TEXT
2514 # undef SQLITE_TEXT
2515 #else
2516 # define SQLITE_TEXT     3
2517 #endif
2518 #define SQLITE3_TEXT     3
2519
2520 /*
2521 ** CAPI3REF: Results Values From A Query {F13800}
2522 **
2523 ** These routines return information about
2524 ** a single column of the current result row of a query.  In every
2525 ** case the first argument is a pointer to the 
2526 ** [sqlite3_stmt | SQL statement] that is being
2527 ** evaluated (the [sqlite3_stmt*] that was returned from 
2528 ** [sqlite3_prepare_v2()] or one of its variants) and
2529 ** the second argument is the index of the column for which information 
2530 ** should be returned.  The left-most column of the result set
2531 ** has an index of 0.
2532 **
2533 ** If the SQL statement is not currently point to a valid row, or if the
2534 ** the column index is out of range, the result is undefined. 
2535 ** These routines may only be called when the most recent call to
2536 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
2537 ** [sqlite3_reset()] nor [sqlite3_finalize()] has been call subsequently.
2538 ** If any of these routines are called after [sqlite3_reset()] or
2539 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
2540 ** something other than [SQLITE_ROW], the results are undefined.
2541 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
2542 ** are called from a different thread while any of these routines
2543 ** are pending, then the results are undefined.  
2544 **
2545 ** The sqlite3_column_type() routine returns 
2546 ** [SQLITE_INTEGER | datatype code] for the initial data type
2547 ** of the result column.  The returned value is one of [SQLITE_INTEGER],
2548 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
2549 ** returned by sqlite3_column_type() is only meaningful if no type
2550 ** conversions have occurred as described below.  After a type conversion,
2551 ** the value returned by sqlite3_column_type() is undefined.  Future
2552 ** versions of SQLite may change the behavior of sqlite3_column_type()
2553 ** following a type conversion.
2554 **
2555 ** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() 
2556 ** routine returns the number of bytes in that BLOB or string.
2557 ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
2558 ** the string to UTF-8 and then returns the number of bytes.
2559 ** If the result is a numeric value then sqlite3_column_bytes() uses
2560 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
2561 ** the number of bytes in that string.
2562 ** The value returned does not include the zero terminator at the end
2563 ** of the string.  For clarity: the value returned is the number of
2564 ** bytes in the string, not the number of characters.
2565 **
2566 ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
2567 ** even zero-length strings, are always zero terminated.  The return
2568 ** value from sqlite3_column_blob() for a zero-length blob is an arbitrary
2569 ** pointer, possibly even a NULL pointer.
2570 **
2571 ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
2572 ** but leaves the result in UTF-16 instead of UTF-8.  
2573 ** The zero terminator is not included in this count.
2574 **
2575 ** These routines attempt to convert the value where appropriate.  For
2576 ** example, if the internal representation is FLOAT and a text result
2577 ** is requested, [sqlite3_snprintf()] is used internally to do the conversion
2578 ** automatically.  The following table details the conversions that
2579 ** are applied:
2580 **
2581 ** <blockquote>
2582 ** <table border="1">
2583 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
2584 **
2585 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
2586 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
2587 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
2588 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
2589 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
2590 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
2591 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as for INTEGER->TEXT
2592 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
2593 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
2594 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
2595 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
2596 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
2597 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
2598 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
2599 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
2600 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
2601 ** </table>
2602 ** </blockquote>
2603 **
2604 ** The table above makes reference to standard C library functions atoi()
2605 ** and atof().  SQLite does not really use these functions.  It has its
2606 ** on equavalent internal routines.  The atoi() and atof() names are
2607 ** used in the table for brevity and because they are familiar to most
2608 ** C programmers.
2609 **
2610 ** Note that when type conversions occur, pointers returned by prior
2611 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
2612 ** sqlite3_column_text16() may be invalidated. 
2613 ** Type conversions and pointer invalidations might occur
2614 ** in the following cases:
2615 **
2616 ** <ul>
2617 ** <li><p>  The initial content is a BLOB and sqlite3_column_text() 
2618 **          or sqlite3_column_text16() is called.  A zero-terminator might
2619 **          need to be added to the string.</p></li>
2620 **
2621 ** <li><p>  The initial content is UTF-8 text and sqlite3_column_bytes16() or
2622 **          sqlite3_column_text16() is called.  The content must be converted
2623 **          to UTF-16.</p></li>
2624 **
2625 ** <li><p>  The initial content is UTF-16 text and sqlite3_column_bytes() or
2626 **          sqlite3_column_text() is called.  The content must be converted
2627 **          to UTF-8.</p></li>
2628 ** </ul>
2629 **
2630 ** Conversions between UTF-16be and UTF-16le are always done in place and do
2631 ** not invalidate a prior pointer, though of course the content of the buffer
2632 ** that the prior pointer points to will have been modified.  Other kinds
2633 ** of conversion are done in place when it is possible, but sometime it is
2634 ** not possible and in those cases prior pointers are invalidated.  
2635 **
2636 ** The safest and easiest to remember policy is to invoke these routines
2637 ** in one of the following ways:
2638 **
2639 **  <ul>
2640 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
2641 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
2642 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
2643 **  </ul>
2644 **
2645 ** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(),
2646 ** or sqlite3_column_text16() first to force the result into the desired
2647 ** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to
2648 ** find the size of the result.  Do not mix call to sqlite3_column_text() or
2649 ** sqlite3_column_blob() with calls to sqlite3_column_bytes16().  And do not
2650 ** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes().
2651 **
2652 ** The pointers returned are valid until a type conversion occurs as
2653 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
2654 ** [sqlite3_finalize()] is called.  The memory space used to hold strings
2655 ** and blobs is freed automatically.  Do <b>not</b> pass the pointers returned
2656 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into 
2657 ** [sqlite3_free()].
2658 **
2659 ** If a memory allocation error occurs during the evaluation of any
2660 ** of these routines, a default value is returned.  The default value
2661 ** is either the integer 0, the floating point number 0.0, or a NULL
2662 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
2663 ** [SQLITE_NOMEM].
2664 */
2665 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
2666 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
2667 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
2668 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
2669 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
2670 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
2671 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
2672 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
2673 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
2674 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
2675
2676 /*
2677 ** CAPI3REF: Destroy A Prepared Statement Object {F13300}
2678 **
2679 ** The sqlite3_finalize() function is called to delete a 
2680 ** [sqlite3_stmt | compiled SQL statement]. If the statement was
2681 ** executed successfully, or not executed at all, then SQLITE_OK is returned.
2682 ** If execution of the statement failed then an 
2683 ** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code]
2684 ** is returned. 
2685 **
2686 ** This routine can be called at any point during the execution of the
2687 ** [sqlite3_stmt | virtual machine].  If the virtual machine has not 
2688 ** completed execution when this routine is called, that is like
2689 ** encountering an error or an interrupt.  (See [sqlite3_interrupt()].) 
2690 ** Incomplete updates may be rolled back and transactions cancelled,  
2691 ** depending on the circumstances, and the 
2692 ** [SQLITE_ERROR | result code] returned will be [SQLITE_ABORT].
2693 */
2694 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
2695
2696 /*
2697 ** CAPI3REF: Reset A Prepared Statement Object {F13330}
2698 **
2699 ** The sqlite3_reset() function is called to reset a 
2700 ** [sqlite3_stmt | compiled SQL statement] object.
2701 ** back to its initial state, ready to be re-executed.
2702 ** Any SQL statement variables that had values bound to them using
2703 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
2704 ** Use [sqlite3_clear_bindings()] to reset the bindings.
2705 */
2706 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
2707
2708 /*
2709 ** CAPI3REF: Create Or Redefine SQL Functions {F16100}
2710 **
2711 ** The following two functions are used to add SQL functions or aggregates
2712 ** or to redefine the behavior of existing SQL functions or aggregates.  The
2713 ** difference only between the two is that the second parameter, the
2714 ** name of the (scalar) function or aggregate, is encoded in UTF-8 for
2715 ** sqlite3_create_function() and UTF-16 for sqlite3_create_function16().
2716 **
2717 ** The first argument is the [sqlite3 | database handle] that holds the
2718 ** SQL function or aggregate is to be added or redefined. If a single
2719 ** program uses more than one database handle internally, then SQL
2720 ** functions or aggregates must be added individually to each database
2721 ** handle with which they will be used.
2722 **
2723 ** The second parameter is the name of the SQL function to be created
2724 ** or redefined.
2725 ** The length of the name is limited to 255 bytes, exclusive of the 
2726 ** zero-terminator.  Note that the name length limit is in bytes, not
2727 ** characters.  Any attempt to create a function with a longer name
2728 ** will result in an SQLITE_ERROR error.
2729 **
2730 ** The third parameter is the number of arguments that the SQL function or
2731 ** aggregate takes. If this parameter is negative, then the SQL function or
2732 ** aggregate may take any number of arguments.
2733 **
2734 ** The fourth parameter, eTextRep, specifies what 
2735 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
2736 ** its parameters.  Any SQL function implementation should be able to work
2737 ** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
2738 ** more efficient with one encoding than another.  It is allowed to
2739 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
2740 ** times with the same function but with different values of eTextRep.
2741 ** When multiple implementations of the same function are available, SQLite
2742 ** will pick the one that involves the least amount of data conversion.
2743 ** If there is only a single implementation which does not care what
2744 ** text encoding is used, then the fourth argument should be
2745 ** [SQLITE_ANY].
2746 **
2747 ** The fifth parameter is an arbitrary pointer.  The implementation
2748 ** of the function can gain access to this pointer using
2749 ** [sqlite3_user_data()].
2750 **
2751 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
2752 ** pointers to C-language functions that implement the SQL
2753 ** function or aggregate. A scalar SQL function requires an implementation of
2754 ** the xFunc callback only, NULL pointers should be passed as the xStep
2755 ** and xFinal parameters. An aggregate SQL function requires an implementation
2756 ** of xStep and xFinal and NULL should be passed for xFunc. To delete an
2757 ** existing SQL function or aggregate, pass NULL for all three function
2758 ** callback.
2759 **
2760 ** It is permitted to register multiple implementations of the same
2761 ** functions with the same name but with either differing numbers of
2762 ** arguments or differing perferred text encodings.  SQLite will use
2763 ** the implementation most closely matches the way in which the
2764 ** SQL function is used.
2765 */
2766 SQLITE_API int sqlite3_create_function(
2767   sqlite3 *,
2768   const char *zFunctionName,
2769   int nArg,
2770   int eTextRep,
2771   void*,
2772   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
2773   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
2774   void (*xFinal)(sqlite3_context*)
2775 );
2776 SQLITE_API int sqlite3_create_function16(
2777   sqlite3*,
2778   const void *zFunctionName,
2779   int nArg,
2780   int eTextRep,
2781   void*,
2782   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
2783   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
2784   void (*xFinal)(sqlite3_context*)
2785 );
2786
2787 /*
2788 ** CAPI3REF: Text Encodings {F10267}
2789 **
2790 ** These constant define integer codes that represent the various
2791 ** text encodings supported by SQLite.
2792 */
2793 #define SQLITE_UTF8           1
2794 #define SQLITE_UTF16LE        2
2795 #define SQLITE_UTF16BE        3
2796 #define SQLITE_UTF16          4    /* Use native byte order */
2797 #define SQLITE_ANY            5    /* sqlite3_create_function only */
2798 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
2799
2800 /*
2801 ** CAPI3REF: Obsolete Functions
2802 **
2803 ** These functions are all now obsolete.  In order to maintain
2804 ** backwards compatibility with older code, we continue to support
2805 ** these functions.  However, new development projects should avoid
2806 ** the use of these functions.  To help encourage people to avoid
2807 ** using these functions, we are not going to tell you want they do.
2808 */
2809 SQLITE_API int sqlite3_aggregate_count(sqlite3_context*);
2810 SQLITE_API int sqlite3_expired(sqlite3_stmt*);
2811 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
2812 SQLITE_API int sqlite3_global_recover(void);
2813 SQLITE_API void sqlite3_thread_cleanup(void);
2814 SQLITE_API int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
2815
2816 /*
2817 ** CAPI3REF: Obtaining SQL Function Parameter Values {F15100}
2818 **
2819 ** The C-language implementation of SQL functions and aggregates uses
2820 ** this set of interface routines to access the parameter values on
2821 ** the function or aggregate.
2822 **
2823 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
2824 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
2825 ** define callbacks that implement the SQL functions and aggregates.
2826 ** The 4th parameter to these callbacks is an array of pointers to
2827 ** [sqlite3_value] objects.  There is one [sqlite3_value] object for
2828 ** each parameter to the SQL function.  These routines are used to
2829 ** extract values from the [sqlite3_value] objects.
2830 **
2831 ** These routines work just like the corresponding 
2832 ** [sqlite3_column_blob | sqlite3_column_* routines] except that 
2833 ** these routines take a single [sqlite3_value*] pointer instead
2834 ** of an [sqlite3_stmt*] pointer and an integer column number.
2835 **
2836 ** The sqlite3_value_text16() interface extracts a UTF16 string
2837 ** in the native byte-order of the host machine.  The
2838 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
2839 ** extract UTF16 strings as big-endian and little-endian respectively.
2840 **
2841 ** The sqlite3_value_numeric_type() interface attempts to apply
2842 ** numeric affinity to the value.  This means that an attempt is
2843 ** made to convert the value to an integer or floating point.  If
2844 ** such a conversion is possible without loss of information (in other
2845 ** words if the value is a string that looks like a number)
2846 ** then the conversion is done.  Otherwise no conversion occurs.  The 
2847 ** [SQLITE_INTEGER | datatype] after conversion is returned.
2848 **
2849 ** Please pay particular attention to the fact that the pointer that
2850 ** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or
2851 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
2852 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
2853 ** or [sqlite3_value_text16()].  
2854 **
2855 ** These routines must be called from the same thread as
2856 ** the SQL function that supplied the sqlite3_value* parameters.
2857 ** Or, if the sqlite3_value* argument comes from the [sqlite3_column_value()]
2858 ** interface, then these routines should be called from the same thread
2859 ** that ran [sqlite3_column_value()].
2860 **
2861 */
2862 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
2863 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
2864 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
2865 SQLITE_API double sqlite3_value_double(sqlite3_value*);
2866 SQLITE_API int sqlite3_value_int(sqlite3_value*);
2867 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
2868 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
2869 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
2870 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
2871 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
2872 SQLITE_API int sqlite3_value_type(sqlite3_value*);
2873 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
2874
2875 /*
2876 ** CAPI3REF: Obtain Aggregate Function Context {F16210}
2877 **
2878 ** The implementation of aggregate SQL functions use this routine to allocate
2879 ** a structure for storing their state.  
2880 ** {F16211} The first time the sqlite3_aggregate_context() routine is
2881 ** is called for a particular aggregate, SQLite allocates nBytes of memory
2882 ** zeros that memory, and returns a pointer to it.
2883 ** {F16212} On second and subsequent calls to sqlite3_aggregate_context()
2884 ** for the same aggregate function index, the same buffer is returned. {END}
2885 ** The implementation
2886 ** of the aggregate can use the returned buffer to accumulate data.
2887 **
2888 ** {F16213} SQLite automatically frees the allocated buffer when the aggregate
2889 ** query concludes. {END}
2890 **
2891 ** The first parameter should be a copy of the 
2892 ** [sqlite3_context | SQL function context] that is the first
2893 ** parameter to the callback routine that implements the aggregate
2894 ** function.
2895 **
2896 ** This routine must be called from the same thread in which
2897 ** the aggregate SQL function is running.
2898 */
2899 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
2900
2901 /*
2902 ** CAPI3REF: User Data For Functions {F16240}
2903 **
2904 ** {F16241} The sqlite3_user_data() interface returns a copy of
2905 ** the pointer that was the pUserData parameter (the 5th parameter)
2906 ** of the the [sqlite3_create_function()]
2907 ** and [sqlite3_create_function16()] routines that originally
2908 ** registered the application defined function. {END}
2909 **
2910 ** {U16243} This routine must be called from the same thread in which
2911 ** the application-defined function is running.
2912 */
2913 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
2914
2915 /*
2916 ** CAPI3REF: Function Auxiliary Data {F16270}
2917 **
2918 ** The following two functions may be used by scalar SQL functions to
2919 ** associate meta-data with argument values. If the same value is passed to
2920 ** multiple invocations of the same SQL function during query execution, under
2921 ** some circumstances the associated meta-data may be preserved. This may
2922 ** be used, for example, to add a regular-expression matching scalar
2923 ** function. The compiled version of the regular expression is stored as
2924 ** meta-data associated with the SQL value passed as the regular expression
2925 ** pattern.  The compiled regular expression can be reused on multiple
2926 ** invocations of the same function so that the original pattern string
2927 ** does not need to be recompiled on each invocation.
2928 **
2929 ** {F16271}
2930 ** The sqlite3_get_auxdata() interface returns a pointer to the meta-data
2931 ** associated by the sqlite3_set_auxdata() function with the Nth argument
2932 ** value to the application-defined function.
2933 ** {F16272} If no meta-data has been ever been set for the Nth
2934 ** argument of the function, or if the cooresponding function parameter
2935 ** has changed since the meta-data was set, then sqlite3_get_auxdata()
2936 ** returns a NULL pointer.
2937 **
2938 ** {F16275} The sqlite3_set_auxdata() interface saves the meta-data
2939 ** pointed to by its 3rd parameter as the meta-data for the N-th
2940 ** argument of the application-defined function. {END} Subsequent
2941 ** calls to sqlite3_get_auxdata() might return this data, if it has
2942 ** not been destroyed. 
2943 ** {F16277} If it is not NULL, SQLite will invoke the destructor 
2944 ** function given by the 4th parameter to sqlite3_set_auxdata() on
2945 ** the meta-data when the corresponding function parameter changes
2946 ** or when the SQL statement completes, whichever comes first. {END}
2947 **
2948 ** In practice, meta-data is preserved between function calls for
2949 ** expressions that are constant at compile time. This includes literal
2950 ** values and SQL variables.
2951 **
2952 ** These routines must be called from the same thread in which
2953 ** the SQL function is running.
2954 */
2955 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
2956 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
2957
2958
2959 /*
2960 ** CAPI3REF: Constants Defining Special Destructor Behavior {F10280}
2961 **
2962 ** These are special value for the destructor that is passed in as the
2963 ** final argument to routines like [sqlite3_result_blob()].  If the destructor
2964 ** argument is SQLITE_STATIC, it means that the content pointer is constant
2965 ** and will never change.  It does not need to be destroyed.  The 
2966 ** SQLITE_TRANSIENT value means that the content will likely change in
2967 ** the near future and that SQLite should make its own private copy of
2968 ** the content before returning.
2969 **
2970 ** The typedef is necessary to work around problems in certain
2971 ** C++ compilers.  See ticket #2191.
2972 */
2973 typedef void (*sqlite3_destructor_type)(void*);
2974 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
2975 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
2976
2977 /*
2978 ** CAPI3REF: Setting The Result Of An SQL Function {F16400}
2979 **
2980 ** These routines are used by the xFunc or xFinal callbacks that
2981 ** implement SQL functions and aggregates.  See
2982 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
2983 ** for additional information.
2984 **
2985 ** These functions work very much like the 
2986 ** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used
2987 ** to bind values to host parameters in prepared statements.
2988 ** Refer to the
2989 ** [sqlite3_bind_blob | sqlite3_bind_* documentation] for
2990 ** additional information.
2991 **
2992 ** {F16402} The sqlite3_result_blob() interface sets the result from
2993 ** an application defined function to be the BLOB whose content is pointed
2994 ** to by the second parameter and which is N bytes long where N is the
2995 ** third parameter. 
2996 ** {F16403} The sqlite3_result_zeroblob() inerfaces set the result of
2997 ** the application defined function to be a BLOB containing all zero
2998 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
2999 **
3000 ** {F16407} The sqlite3_result_double() interface sets the result from
3001 ** an application defined function to be a floating point value specified
3002 ** by its 2nd argument.
3003 **
3004 ** {F16409} The sqlite3_result_error() and sqlite3_result_error16() functions
3005 ** cause the implemented SQL function to throw an exception.
3006 ** {F16411} SQLite uses the string pointed to by the
3007 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
3008 ** as the text of an error message. {F16412} SQLite interprets the error
3009 ** message string from sqlite3_result_error() as UTF8.  {F16413} SQLite
3010 ** interprets the string from sqlite3_result_error16() as UTF16 in native
3011 ** byte order.  {F16414} If the third parameter to sqlite3_result_error()
3012 ** or sqlite3_result_error16() is negative then SQLite takes as the error
3013 ** message all text up through the first zero character.
3014 ** {F16415} If the third parameter to sqlite3_result_error() or
3015 ** sqlite3_result_error16() is non-negative then SQLite takes that many
3016 ** bytes (not characters) from the 2nd parameter as the error message.
3017 ** {F16417} The sqlite3_result_error() and sqlite3_result_error16()
3018 ** routines make a copy private copy of the error message text before
3019 ** they return.  {END} Hence, the calling function can deallocate or
3020 ** modify the text after they return without harm.
3021 **
3022 ** {F16421} The sqlite3_result_toobig() interface causes SQLite
3023 ** to throw an error indicating that a string or BLOB is to long
3024 ** to represent.  {F16422} The sqlite3_result_nomem() interface
3025 ** causes SQLite to throw an exception indicating that the a
3026 ** memory allocation failed.
3027 **
3028 ** {F16431} The sqlite3_result_int() interface sets the return value
3029 ** of the application-defined function to be the 32-bit signed integer
3030 ** value given in the 2nd argument.
3031 ** {F16432} The sqlite3_result_int64() interface sets the return value
3032 ** of the application-defined function to be the 64-bit signed integer
3033 ** value given in the 2nd argument.
3034 **
3035 ** {F16437} The sqlite3_result_null() interface sets the return value
3036 ** of the application-defined function to be NULL.
3037 **
3038 ** {F16441} The sqlite3_result_text(), sqlite3_result_text16(), 
3039 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
3040 ** set the return value of the application-defined function to be
3041 ** a text string which is represented as UTF-8, UTF-16 native byte order,
3042 ** UTF-16 little endian, or UTF-16 big endian, respectively.
3043 ** {F16442} SQLite takes the text result from the application from
3044 ** the 2nd parameter of the sqlite3_result_text* interfaces.
3045 ** {F16444} If the 3rd parameter to the sqlite3_result_text* interfaces
3046 ** is negative, then SQLite takes result text from the 2nd parameter 
3047 ** through the first zero character.
3048 ** {F16447} If the 3rd parameter to the sqlite3_result_text* interfaces
3049 ** is non-negative, then as many bytes (not characters) of the text
3050 ** pointed to by the 2nd parameter are taken as the application-defined
3051 ** function result.
3052 ** {F16451} If the 4th parameter to the sqlite3_result_text* interfaces
3053 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
3054 ** function as the destructor on the text or blob result when it has
3055 ** finished using that result.
3056 ** {F16453} If the 4th parameter to the sqlite3_result_text* interfaces
3057 ** or sqlite3_result_blob is the special constant SQLITE_STATIC, then
3058 ** SQLite assumes that the text or blob result is constant space and
3059 ** does not copy the space or call a destructor when it has
3060 ** finished using that result.
3061 ** {F16454} If the 4th parameter to the sqlite3_result_text* interfaces
3062 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
3063 ** then SQLite makes a copy of the result into space obtained from
3064 ** from [sqlite3_malloc()] before it returns.
3065 **
3066 ** {F16461} The sqlite3_result_value() interface sets the result of
3067 ** the application-defined function to be a copy the [sqlite3_value]
3068 ** object specified by the 2nd parameter.  {F16463} The
3069 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
3070 ** so that [sqlite3_value] specified in the parameter may change or
3071 ** be deallocated after sqlite3_result_value() returns without harm.
3072 **
3073 ** {U16491} These routines are called from within the different thread 
3074 ** than the one containing the application-defined function that recieved
3075 ** the [sqlite3_context] pointer, the results are undefined.
3076 */
3077 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
3078 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
3079 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
3080 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
3081 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
3082 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
3083 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
3084 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
3085 SQLITE_API void sqlite3_result_null(sqlite3_context*);
3086 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
3087 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
3088 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
3089 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
3090 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
3091 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
3092
3093 /*
3094 ** CAPI3REF: Define New Collating Sequences {F16600}
3095 **
3096 ** {F16601}
3097 ** These functions are used to add new collation sequences to the
3098 ** [sqlite3*] handle specified as the first argument. 
3099 **
3100 ** {F16602}
3101 ** The name of the new collation sequence is specified as a UTF-8 string
3102 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
3103 ** and a UTF-16 string for sqlite3_create_collation16(). {F16603} In all cases
3104 ** the name is passed as the second function argument.
3105 **
3106 ** {F16604}
3107 ** The third argument may be one of the constants [SQLITE_UTF8],
3108 ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
3109 ** routine expects to be passed pointers to strings encoded using UTF-8,
3110 ** UTF-16 little-endian or UTF-16 big-endian respectively. {F16605} The
3111 ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that
3112 ** the routine expects pointers to 16-bit word aligned strings
3113 ** of UTF16 in the native byte order of the host computer.
3114 **
3115 ** {F16607}
3116 ** A pointer to the user supplied routine must be passed as the fifth
3117 ** argument. {F16609} If it is NULL, this is the same as deleting the collation
3118 ** sequence (so that SQLite cannot call it anymore).
3119 ** {F16611} Each time the application
3120 ** supplied function is invoked, it is passed a copy of the void* passed as
3121 ** the fourth argument to sqlite3_create_collation() or
3122 ** sqlite3_create_collation16() as its first parameter.
3123 **
3124 ** {F16612}
3125 ** The remaining arguments to the application-supplied routine are two strings,
3126 ** each represented by a [length, data] pair and encoded in the encoding
3127 ** that was passed as the third argument when the collation sequence was
3128 ** registered. {END} The application defined collation routine should
3129 ** return negative, zero or positive if
3130 ** the first string is less than, equal to, or greater than the second
3131 ** string. i.e. (STRING1 - STRING2).
3132 **
3133 ** {F16615}
3134 ** The sqlite3_create_collation_v2() works like sqlite3_create_collation()
3135 ** excapt that it takes an extra argument which is a destructor for
3136 ** the collation.  {F16617} The destructor is called when the collation is
3137 ** destroyed and is passed a copy of the fourth parameter void* pointer
3138 ** of the sqlite3_create_collation_v2().
3139 ** {F16618}  Collations are destroyed when
3140 ** they are overridden by later calls to the collation creation functions
3141 ** or when the [sqlite3*] database handle is closed using [sqlite3_close()].
3142 */
3143 SQLITE_API int sqlite3_create_collation(
3144   sqlite3*, 
3145   const char *zName, 
3146   int eTextRep, 
3147   void*,
3148   int(*xCompare)(void*,int,const void*,int,const void*)
3149 );
3150 SQLITE_API int sqlite3_create_collation_v2(
3151   sqlite3*, 
3152   const char *zName, 
3153   int eTextRep, 
3154   void*,
3155   int(*xCompare)(void*,int,const void*,int,const void*),
3156   void(*xDestroy)(void*)
3157 );
3158 SQLITE_API int sqlite3_create_collation16(
3159   sqlite3*, 
3160   const char *zName, 
3161   int eTextRep, 
3162   void*,
3163   int(*xCompare)(void*,int,const void*,int,const void*)
3164 );
3165
3166 /*
3167 ** CAPI3REF: Collation Needed Callbacks {F16700}
3168 **
3169 ** {F16701}
3170 ** To avoid having to register all collation sequences before a database
3171 ** can be used, a single callback function may be registered with the
3172 ** database handle to be called whenever an undefined collation sequence is
3173 ** required.
3174 **
3175 ** {F16702}
3176 ** If the function is registered using the sqlite3_collation_needed() API,
3177 ** then it is passed the names of undefined collation sequences as strings
3178 ** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, the names
3179 ** are passed as UTF-16 in machine native byte order. {F16704} A call to either
3180 ** function replaces any existing callback.
3181 **
3182 ** {F16705} When the callback is invoked, the first argument passed is a copy
3183 ** of the second argument to sqlite3_collation_needed() or
3184 ** sqlite3_collation_needed16(). {F16706} The second argument is the database
3185 ** handle.  {F16707} The third argument is one of [SQLITE_UTF8],
3186 ** [SQLITE_UTF16BE], or [SQLITE_UTF16LE], indicating the most
3187 ** desirable form of the collation sequence function required.
3188 ** {F16708} The fourth parameter is the name of the
3189 ** required collation sequence. {END}
3190 **
3191 ** The callback function should register the desired collation using
3192 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
3193 ** [sqlite3_create_collation_v2()].
3194 */
3195 SQLITE_API int sqlite3_collation_needed(
3196   sqlite3*, 
3197   void*, 
3198   void(*)(void*,sqlite3*,int eTextRep,const char*)
3199 );
3200 SQLITE_API int sqlite3_collation_needed16(
3201   sqlite3*, 
3202   void*,
3203   void(*)(void*,sqlite3*,int eTextRep,const void*)
3204 );
3205
3206 /*
3207 ** Specify the key for an encrypted database.  This routine should be
3208 ** called right after sqlite3_open().
3209 **
3210 ** The code to implement this API is not available in the public release
3211 ** of SQLite.
3212 */
3213 SQLITE_API int sqlite3_key(
3214   sqlite3 *db,                   /* Database to be rekeyed */
3215   const void *pKey, int nKey     /* The key */
3216 );
3217
3218 /*
3219 ** Change the key on an open database.  If the current database is not
3220 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
3221 ** database is decrypted.
3222 **
3223 ** The code to implement this API is not available in the public release
3224 ** of SQLite.
3225 */
3226 SQLITE_API int sqlite3_rekey(
3227   sqlite3 *db,                   /* Database to be rekeyed */
3228   const void *pKey, int nKey     /* The new key */
3229 );
3230
3231 /*
3232 ** CAPI3REF:  Suspend Execution For A Short Time {F10530}
3233 **
3234 ** {F10531} The sqlite3_sleep() function
3235 ** causes the current thread to suspend execution
3236 ** for at least a number of milliseconds specified in its parameter.
3237 **
3238 ** {F10532} If the operating system does not support sleep requests with 
3239 ** millisecond time resolution, then the time will be rounded up to 
3240 ** the nearest second. {F10533} The number of milliseconds of sleep actually 
3241 ** requested from the operating system is returned.
3242 **
3243 ** {F10534} SQLite implements this interface by calling the xSleep()
3244 ** method of the default [sqlite3_vfs] object. {END}
3245 */
3246 SQLITE_API int sqlite3_sleep(int);
3247
3248 /*
3249 ** CAPI3REF:  Name Of The Folder Holding Temporary Files {F10310}
3250 **
3251 ** If this global variable is made to point to a string which is
3252 ** the name of a folder (a.ka. directory), then all temporary files
3253 ** created by SQLite will be placed in that directory.  If this variable
3254 ** is NULL pointer, then SQLite does a search for an appropriate temporary
3255 ** file directory.
3256 **
3257 ** It is not safe to modify this variable once a database connection
3258 ** has been opened.  It is intended that this variable be set once
3259 ** as part of process initialization and before any SQLite interface
3260 ** routines have been call and remain unchanged thereafter.
3261 */
3262 SQLITE_EXTERN char *sqlite3_temp_directory;
3263
3264 /*
3265 ** CAPI3REF:  Test To See If The Database Is In Auto-Commit Mode {F12930}
3266 **
3267 ** {F12931} The sqlite3_get_autocommit() interfaces returns non-zero or
3268 ** zero if the given database connection is or is not in autocommit mode,
3269 ** respectively. {F12932}  Autocommit mode is on
3270 ** by default.  {F12933} Autocommit mode is disabled by a BEGIN statement.
3271 ** {F12934} Autocommit mode is reenabled by a COMMIT or ROLLBACK. {END}
3272 **
3273 ** If certain kinds of errors occur on a statement within a multi-statement
3274 ** transactions (errors including [SQLITE_FULL], [SQLITE_IOERR], 
3275 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
3276 ** transaction might be rolled back automatically.  {F12935} The only way to
3277 ** find out if SQLite automatically rolled back the transaction after
3278 ** an error is to use this function. {END}
3279 **
3280 ** {U12936} If another thread changes the autocommit status of the database
3281 ** connection while this routine is running, then the return value
3282 ** is undefined. {END}
3283 */
3284 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
3285
3286 /*
3287 ** CAPI3REF:  Find The Database Handle Of A Prepared Statement {F13120}
3288 **
3289 ** {F13121} The sqlite3_db_handle interface
3290 ** returns the [sqlite3*] database handle to which a
3291 ** [sqlite3_stmt | prepared statement] belongs.
3292 ** {F13122} the database handle returned by sqlite3_db_handle
3293 ** is the same database handle that was
3294 ** the first argument to the [sqlite3_prepare_v2()] or its variants
3295 ** that was used to create the statement in the first place.
3296 */
3297 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
3298
3299
3300 /*
3301 ** CAPI3REF: Commit And Rollback Notification Callbacks {F12950}
3302 **
3303 ** {F12951} The sqlite3_commit_hook() interface registers a callback
3304 ** function to be invoked whenever a transaction is committed.
3305 ** {F12952} Any callback set by a previous call to sqlite3_commit_hook()
3306 ** for the same database connection is overridden.
3307 ** {F12953} The sqlite3_rollback_hook() interface registers a callback
3308 ** function to be invoked whenever a transaction is committed.
3309 ** {F12954} Any callback set by a previous call to sqlite3_commit_hook()
3310 ** for the same database connection is overridden.
3311 ** {F12956} The pArg argument is passed through
3312 ** to the callback.  {F12957} If the callback on a commit hook function 
3313 ** returns non-zero, then the commit is converted into a rollback.
3314 **
3315 ** {F12958} If another function was previously registered, its
3316 ** pArg value is returned.  Otherwise NULL is returned.
3317 **
3318 ** {F12959} Registering a NULL function disables the callback.
3319 **
3320 ** {F12961} For the purposes of this API, a transaction is said to have been 
3321 ** rolled back if an explicit "ROLLBACK" statement is executed, or
3322 ** an error or constraint causes an implicit rollback to occur.
3323 ** {F12962} The rollback callback is not invoked if a transaction is
3324 ** automatically rolled back because the database connection is closed.
3325 ** {F12964} The rollback callback is not invoked if a transaction is
3326 ** rolled back because a commit callback returned non-zero.
3327 ** <todo> Check on this </todo> {END}
3328 **
3329 ** These are experimental interfaces and are subject to change.
3330 */
3331 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
3332 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
3333
3334 /*
3335 ** CAPI3REF: Data Change Notification Callbacks {F12970}
3336 **
3337 ** {F12971} The sqlite3_update_hook() interface
3338 ** registers a callback function with the database connection identified by the 
3339 ** first argument to be invoked whenever a row is updated, inserted or deleted.
3340 ** {F12972} Any callback set by a previous call to this function for the same 
3341 ** database connection is overridden.
3342 **
3343 ** {F12974} The second argument is a pointer to the function to invoke when a 
3344 ** row is updated, inserted or deleted. 
3345 ** {F12976} The first argument to the callback is
3346 ** a copy of the third argument to sqlite3_update_hook().
3347 ** {F12977} The second callback 
3348 ** argument is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
3349 ** depending on the operation that caused the callback to be invoked.
3350 ** {F12978} The third and 
3351 ** fourth arguments to the callback contain pointers to the database and 
3352 ** table name containing the affected row.
3353 ** {F12979} The final callback parameter is 
3354 ** the rowid of the row.
3355 ** {F12981} In the case of an update, this is the rowid after 
3356 ** the update takes place.
3357 **
3358 ** {F12983} The update hook is not invoked when internal system tables are
3359 ** modified (i.e. sqlite_master and sqlite_sequence).
3360 **
3361 ** {F12984} If another function was previously registered, its pArg value
3362 ** is returned.  {F12985} Otherwise NULL is returned.
3363 */
3364 SQLITE_API void *sqlite3_update_hook(
3365   sqlite3*, 
3366   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
3367   void*
3368 );
3369
3370 /*
3371 ** CAPI3REF:  Enable Or Disable Shared Pager Cache {F10330}
3372 **
3373 ** {F10331}
3374 ** This routine enables or disables the sharing of the database cache
3375 ** and schema data structures between connections to the same database.
3376 ** {F10332}
3377 ** Sharing is enabled if the argument is true and disabled if the argument
3378 ** is false.
3379 **
3380 ** {F10333} Cache sharing is enabled and disabled
3381 ** for an entire process. {END} This is a change as of SQLite version 3.5.0.
3382 ** In prior versions of SQLite, sharing was
3383 ** enabled or disabled for each thread separately.
3384 **
3385 ** {F10334}
3386 ** The cache sharing mode set by this interface effects all subsequent
3387 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
3388 ** {F10335} Existing database connections continue use the sharing mode
3389 ** that was in effect at the time they were opened. {END}
3390 **
3391 ** Virtual tables cannot be used with a shared cache.  {F10336} When shared
3392 ** cache is enabled, the [sqlite3_create_module()] API used to register
3393 ** virtual tables will always return an error. {END}
3394 **
3395 ** {F10337} This routine returns [SQLITE_OK] if shared cache was
3396 ** enabled or disabled successfully.  {F10338} An [SQLITE_ERROR | error code]
3397 ** is returned otherwise. {END}
3398 **
3399 ** {F10339} Shared cache is disabled by default. {END} But this might change in
3400 ** future releases of SQLite.  Applications that care about shared
3401 ** cache setting should set it explicitly.
3402 */
3403 SQLITE_API int sqlite3_enable_shared_cache(int);
3404
3405 /*
3406 ** CAPI3REF:  Attempt To Free Heap Memory {F17340}
3407 **
3408 ** {F17341} The sqlite3_release_memory() interface attempts to
3409 ** free N bytes of heap memory by deallocating non-essential memory
3410 ** allocations held by the database labrary. {END}  Memory used
3411 ** to cache database pages to improve performance is an example of
3412 ** non-essential memory.  {F16342} sqlite3_release_memory() returns
3413 ** the number of bytes actually freed, which might be more or less
3414 ** than the amount requested.
3415 */
3416 SQLITE_API int sqlite3_release_memory(int);
3417
3418 /*
3419 ** CAPI3REF:  Impose A Limit On Heap Size {F17350}
3420 **
3421 ** {F16351} The sqlite3_soft_heap_limit() interface
3422 ** places a "soft" limit on the amount of heap memory that may be allocated
3423 ** by SQLite. {F16352} If an internal allocation is requested 
3424 ** that would exceed the soft heap limit, [sqlite3_release_memory()] is
3425 ** invoked one or more times to free up some space before the allocation
3426 ** is made. {END}
3427 **
3428 ** {F16353} The limit is called "soft", because if
3429 ** [sqlite3_release_memory()] cannot
3430 ** free sufficient memory to prevent the limit from being exceeded,
3431 ** the memory is allocated anyway and the current operation proceeds.
3432 **
3433 ** {F16354}
3434 ** A negative or zero value for N means that there is no soft heap limit and
3435 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
3436 ** {F16355} The default value for the soft heap limit is zero.
3437 **
3438 ** SQLite makes a best effort to honor the soft heap limit.  
3439 ** {F16356} But if the soft heap limit cannot honored, execution will
3440 ** continue without error or notification. {END}  This is why the limit is 
3441 ** called a "soft" limit.  It is advisory only.
3442 **
3443 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
3444 ** allocated by a single thread - the same thread in which this routine
3445 ** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
3446 ** applied to all threads. {F16357} The value specified for the soft heap limit
3447 ** is an upper bound on the total memory allocation for all threads. {END}  In
3448 ** version 3.5.0 there is no mechanism for limiting the heap usage for
3449 ** individual threads.
3450 */
3451 SQLITE_API void sqlite3_soft_heap_limit(int);
3452
3453 /*
3454 ** CAPI3REF:  Extract Metadata About A Column Of A Table {F12850}
3455 **
3456 ** This routine
3457 ** returns meta-data about a specific column of a specific database
3458 ** table accessible using the connection handle passed as the first function 
3459 ** argument.
3460 **
3461 ** The column is identified by the second, third and fourth parameters to 
3462 ** this function. The second parameter is either the name of the database
3463 ** (i.e. "main", "temp" or an attached database) containing the specified
3464 ** table or NULL. If it is NULL, then all attached databases are searched
3465 ** for the table using the same algorithm as the database engine uses to 
3466 ** resolve unqualified table references.
3467 **
3468 ** The third and fourth parameters to this function are the table and column 
3469 ** name of the desired column, respectively. Neither of these parameters 
3470 ** may be NULL.
3471 **
3472 ** Meta information is returned by writing to the memory locations passed as
3473 ** the 5th and subsequent parameters to this function. Any of these 
3474 ** arguments may be NULL, in which case the corresponding element of meta 
3475 ** information is ommitted.
3476 **
3477 ** <pre>
3478 ** Parameter     Output Type      Description
3479 ** -----------------------------------
3480 **
3481 **   5th         const char*      Data type
3482 **   6th         const char*      Name of the default collation sequence 
3483 **   7th         int              True if the column has a NOT NULL constraint
3484 **   8th         int              True if the column is part of the PRIMARY KEY
3485 **   9th         int              True if the column is AUTOINCREMENT
3486 ** </pre>
3487 **
3488 **
3489 ** The memory pointed to by the character pointers returned for the 
3490 ** declaration type and collation sequence is valid only until the next 
3491 ** call to any sqlite API function.
3492 **
3493 ** If the specified table is actually a view, then an error is returned.
3494 **
3495 ** If the specified column is "rowid", "oid" or "_rowid_" and an 
3496 ** INTEGER PRIMARY KEY column has been explicitly declared, then the output 
3497 ** parameters are set for the explicitly declared column. If there is no
3498 ** explicitly declared IPK column, then the output parameters are set as 
3499 ** follows:
3500 **
3501 ** <pre>
3502 **     data type: "INTEGER"
3503 **     collation sequence: "BINARY"
3504 **     not null: 0
3505 **     primary key: 1
3506 **     auto increment: 0
3507 ** </pre>
3508 **
3509 ** This function may load one or more schemas from database files. If an
3510 ** error occurs during this process, or if the requested table or column
3511 ** cannot be found, an SQLITE error code is returned and an error message
3512 ** left in the database handle (to be retrieved using sqlite3_errmsg()).
3513 **
3514 ** This API is only available if the library was compiled with the
3515 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
3516 */
3517 SQLITE_API int sqlite3_table_column_metadata(
3518   sqlite3 *db,                /* Connection handle */
3519   const char *zDbName,        /* Database name or NULL */
3520   const char *zTableName,     /* Table name */
3521   const char *zColumnName,    /* Column name */
3522   char const **pzDataType,    /* OUTPUT: Declared data type */
3523   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
3524   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
3525   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
3526   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
3527 );
3528
3529 /*
3530 ** CAPI3REF: Load An Extension {F12600}
3531 **
3532 ** {F12601} The sqlite3_load_extension() interface
3533 ** attempts to load an SQLite extension library contained in the file
3534 ** zFile. {F12602} The entry point is zProc. {F12603} zProc may be 0
3535 ** in which case the name of the entry point defaults
3536 ** to "sqlite3_extension_init".
3537 **
3538 ** {F12604} The sqlite3_load_extension() interface shall
3539 ** return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
3540 **
3541 ** {F12605}
3542 ** If an error occurs and pzErrMsg is not 0, then the
3543 ** sqlite3_load_extension() interface shall attempt to fill *pzErrMsg with 
3544 ** error message text stored in memory obtained from [sqlite3_malloc()].
3545 ** {END}  The calling function should free this memory
3546 ** by calling [sqlite3_free()].
3547 **
3548 ** {F12606}
3549 ** Extension loading must be enabled using [sqlite3_enable_load_extension()]
3550 ** prior to calling this API or an error will be returned.
3551 */
3552 SQLITE_API int sqlite3_load_extension(
3553   sqlite3 *db,          /* Load the extension into this database connection */
3554   const char *zFile,    /* Name of the shared library containing extension */
3555   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
3556   char **pzErrMsg       /* Put error message here if not 0 */
3557 );
3558
3559 /*
3560 ** CAPI3REF:  Enable Or Disable Extension Loading {F12620}
3561 **
3562 ** So as not to open security holes in older applications that are
3563 ** unprepared to deal with extension loading, and as a means of disabling
3564 ** extension loading while evaluating user-entered SQL, the following
3565 ** API is provided to turn the [sqlite3_load_extension()] mechanism on and
3566 ** off.  {F12622} It is off by default. {END} See ticket #1863.
3567 **
3568 ** {F12621} Call the sqlite3_enable_load_extension() routine
3569 ** with onoff==1 to turn extension loading on
3570 ** and call it with onoff==0 to turn it back off again. {END}
3571 */
3572 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
3573
3574 /*
3575 ** CAPI3REF: Make Arrangements To Automatically Load An Extension {F12640}
3576 **
3577 ** {F12641} This function
3578 ** registers an extension entry point that is automatically invoked
3579 ** whenever a new database connection is opened using
3580 ** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. {END}
3581 **
3582 ** This API can be invoked at program startup in order to register
3583 ** one or more statically linked extensions that will be available
3584 ** to all new database connections.
3585 **
3586 ** {F12642} Duplicate extensions are detected so calling this routine multiple
3587 ** times with the same extension is harmless.
3588 **
3589 ** {F12643} This routine stores a pointer to the extension in an array
3590 ** that is obtained from sqlite_malloc(). {END} If you run a memory leak
3591 ** checker on your program and it reports a leak because of this
3592 ** array, then invoke [sqlite3_reset_auto_extension()] prior
3593 ** to shutdown to free the memory.
3594 **
3595 ** {F12644} Automatic extensions apply across all threads. {END}
3596 **
3597 ** This interface is experimental and is subject to change or
3598 ** removal in future releases of SQLite.
3599 */
3600 SQLITE_API int sqlite3_auto_extension(void *xEntryPoint);
3601
3602
3603 /*
3604 ** CAPI3REF: Reset Automatic Extension Loading {F12660}
3605 **
3606 ** {F12661} This function disables all previously registered
3607 ** automatic extensions. {END}  This
3608 ** routine undoes the effect of all prior [sqlite3_automatic_extension()]
3609 ** calls.
3610 **
3611 ** {F12662} This call disabled automatic extensions in all threads. {END}
3612 **
3613 ** This interface is experimental and is subject to change or
3614 ** removal in future releases of SQLite.
3615 */
3616 SQLITE_API void sqlite3_reset_auto_extension(void);
3617
3618
3619 /*
3620 ****** EXPERIMENTAL - subject to change without notice **************
3621 **
3622 ** The interface to the virtual-table mechanism is currently considered
3623 ** to be experimental.  The interface might change in incompatible ways.
3624 ** If this is a problem for you, do not use the interface at this time.
3625 **
3626 ** When the virtual-table mechanism stablizes, we will declare the
3627 ** interface fixed, support it indefinitely, and remove this comment.
3628 */
3629
3630 /*
3631 ** Structures used by the virtual table interface
3632 */
3633 typedef struct sqlite3_vtab sqlite3_vtab;
3634 typedef struct sqlite3_index_info sqlite3_index_info;
3635 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
3636 typedef struct sqlite3_module sqlite3_module;
3637
3638 /*
3639 ** A module is a class of virtual tables.  Each module is defined
3640 ** by an instance of the following structure.  This structure consists
3641 ** mostly of methods for the module.
3642 */
3643 struct sqlite3_module {
3644   int iVersion;
3645   int (*xCreate)(sqlite3*, void *pAux,
3646                int argc, const char *const*argv,
3647                sqlite3_vtab **ppVTab, char**);
3648   int (*xConnect)(sqlite3*, void *pAux,
3649                int argc, const char *const*argv,
3650                sqlite3_vtab **ppVTab, char**);
3651   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
3652   int (*xDisconnect)(sqlite3_vtab *pVTab);
3653   int (*xDestroy)(sqlite3_vtab *pVTab);
3654   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
3655   int (*xClose)(sqlite3_vtab_cursor*);
3656   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
3657                 int argc, sqlite3_value **argv);
3658   int (*xNext)(sqlite3_vtab_cursor*);
3659   int (*xEof)(sqlite3_vtab_cursor*);
3660   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
3661   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
3662   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
3663   int (*xBegin)(sqlite3_vtab *pVTab);
3664   int (*xSync)(sqlite3_vtab *pVTab);
3665   int (*xCommit)(sqlite3_vtab *pVTab);
3666   int (*xRollback)(sqlite3_vtab *pVTab);
3667   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
3668                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
3669                        void **ppArg);
3670
3671   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
3672 };
3673
3674 /*
3675 ** The sqlite3_index_info structure and its substructures is used to
3676 ** pass information into and receive the reply from the xBestIndex
3677 ** method of an sqlite3_module.  The fields under **Inputs** are the
3678 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
3679 ** results into the **Outputs** fields.
3680 **
3681 ** The aConstraint[] array records WHERE clause constraints of the
3682 ** form:
3683 **
3684 **         column OP expr
3685 **
3686 ** Where OP is =, &lt;, &lt;=, &gt;, or &gt;=.  
3687 ** The particular operator is stored
3688 ** in aConstraint[].op.  The index of the column is stored in 
3689 ** aConstraint[].iColumn.  aConstraint[].usable is TRUE if the
3690 ** expr on the right-hand side can be evaluated (and thus the constraint
3691 ** is usable) and false if it cannot.
3692 **
3693 ** The optimizer automatically inverts terms of the form "expr OP column"
3694 ** and makes other simplifications to the WHERE clause in an attempt to
3695 ** get as many WHERE clause terms into the form shown above as possible.
3696 ** The aConstraint[] array only reports WHERE clause terms in the correct
3697 ** form that refer to the particular virtual table being queried.
3698 **
3699 ** Information about the ORDER BY clause is stored in aOrderBy[].
3700 ** Each term of aOrderBy records a column of the ORDER BY clause.
3701 **
3702 ** The xBestIndex method must fill aConstraintUsage[] with information
3703 ** about what parameters to pass to xFilter.  If argvIndex>0 then
3704 ** the right-hand side of the corresponding aConstraint[] is evaluated
3705 ** and becomes the argvIndex-th entry in argv.  If aConstraintUsage[].omit
3706 ** is true, then the constraint is assumed to be fully handled by the
3707 ** virtual table and is not checked again by SQLite.
3708 **
3709 ** The idxNum and idxPtr values are recorded and passed into xFilter.
3710 ** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
3711 **
3712 ** The orderByConsumed means that output from xFilter will occur in
3713 ** the correct order to satisfy the ORDER BY clause so that no separate
3714 ** sorting step is required.
3715 **
3716 ** The estimatedCost value is an estimate of the cost of doing the
3717 ** particular lookup.  A full scan of a table with N entries should have
3718 ** a cost of N.  A binary search of a table of N entries should have a
3719 ** cost of approximately log(N).
3720 */
3721 struct sqlite3_index_info {
3722   /* Inputs */
3723   int nConstraint;           /* Number of entries in aConstraint */
3724   struct sqlite3_index_constraint {
3725      int iColumn;              /* Column on left-hand side of constraint */
3726      unsigned char op;         /* Constraint operator */
3727      unsigned char usable;     /* True if this constraint is usable */
3728      int iTermOffset;          /* Used internally - xBestIndex should ignore */
3729   } *aConstraint;            /* Table of WHERE clause constraints */
3730   int nOrderBy;              /* Number of terms in the ORDER BY clause */
3731   struct sqlite3_index_orderby {
3732      int iColumn;              /* Column number */
3733      unsigned char desc;       /* True for DESC.  False for ASC. */
3734   } *aOrderBy;               /* The ORDER BY clause */
3735
3736   /* Outputs */
3737   struct sqlite3_index_constraint_usage {
3738     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
3739     unsigned char omit;      /* Do not code a test for this constraint */
3740   } *aConstraintUsage;
3741   int idxNum;                /* Number used to identify the index */
3742   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
3743   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
3744   int orderByConsumed;       /* True if output is already ordered */
3745   double estimatedCost;      /* Estimated cost of using this index */
3746 };
3747 #define SQLITE_INDEX_CONSTRAINT_EQ    2
3748 #define SQLITE_INDEX_CONSTRAINT_GT    4
3749 #define SQLITE_INDEX_CONSTRAINT_LE    8
3750 #define SQLITE_INDEX_CONSTRAINT_LT    16
3751 #define SQLITE_INDEX_CONSTRAINT_GE    32
3752 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
3753
3754 /*
3755 ** This routine is used to register a new module name with an SQLite
3756 ** connection.  Module names must be registered before creating new
3757 ** virtual tables on the module, or before using preexisting virtual
3758 ** tables of the module.
3759 */
3760 SQLITE_API int sqlite3_create_module(
3761   sqlite3 *db,               /* SQLite connection to register module with */
3762   const char *zName,         /* Name of the module */
3763   const sqlite3_module *,    /* Methods for the module */
3764   void *                     /* Client data for xCreate/xConnect */
3765 );
3766
3767 /*
3768 ** This routine is identical to the sqlite3_create_module() method above,
3769 ** except that it allows a destructor function to be specified. It is
3770 ** even more experimental than the rest of the virtual tables API.
3771 */
3772 SQLITE_API int sqlite3_create_module_v2(
3773   sqlite3 *db,               /* SQLite connection to register module with */
3774   const char *zName,         /* Name of the module */
3775   const sqlite3_module *,    /* Methods for the module */
3776   void *,                    /* Client data for xCreate/xConnect */
3777   void(*xDestroy)(void*)     /* Module destructor function */
3778 );
3779
3780 /*
3781 ** Every module implementation uses a subclass of the following structure
3782 ** to describe a particular instance of the module.  Each subclass will
3783 ** be tailored to the specific needs of the module implementation.   The
3784 ** purpose of this superclass is to define certain fields that are common
3785 ** to all module implementations.
3786 **
3787 ** Virtual tables methods can set an error message by assigning a
3788 ** string obtained from sqlite3_mprintf() to zErrMsg.  The method should
3789 ** take care that any prior string is freed by a call to sqlite3_free()
3790 ** prior to assigning a new string to zErrMsg.  After the error message
3791 ** is delivered up to the client application, the string will be automatically
3792 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.  Note
3793 ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
3794 ** since virtual tables are commonly implemented in loadable extensions which
3795 ** do not have access to sqlite3MPrintf() or sqlite3Free().
3796 */
3797 struct sqlite3_vtab {
3798   const sqlite3_module *pModule;  /* The module for this virtual table */
3799   int nRef;                       /* Used internally */
3800   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
3801   /* Virtual table implementations will typically add additional fields */
3802 };
3803
3804 /* Every module implementation uses a subclass of the following structure
3805 ** to describe cursors that point into the virtual table and are used
3806 ** to loop through the virtual table.  Cursors are created using the
3807 ** xOpen method of the module.  Each module implementation will define
3808 ** the content of a cursor structure to suit its own needs.
3809 **
3810 ** This superclass exists in order to define fields of the cursor that
3811 ** are common to all implementations.
3812 */
3813 struct sqlite3_vtab_cursor {
3814   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
3815   /* Virtual table implementations will typically add additional fields */
3816 };
3817
3818 /*
3819 ** The xCreate and xConnect methods of a module use the following API
3820 ** to declare the format (the names and datatypes of the columns) of
3821 ** the virtual tables they implement.
3822 */
3823 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
3824
3825 /*
3826 ** Virtual tables can provide alternative implementations of functions
3827 ** using the xFindFunction method.  But global versions of those functions
3828 ** must exist in order to be overloaded.
3829 **
3830 ** This API makes sure a global version of a function with a particular
3831 ** name and number of parameters exists.  If no such function exists
3832 ** before this API is called, a new function is created.  The implementation
3833 ** of the new function always causes an exception to be thrown.  So
3834 ** the new function is not good for anything by itself.  Its only
3835 ** purpose is to be a place-holder function that can be overloaded
3836 ** by virtual tables.
3837 **
3838 ** This API should be considered part of the virtual table interface,
3839 ** which is experimental and subject to change.
3840 */
3841 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
3842
3843 /*
3844 ** The interface to the virtual-table mechanism defined above (back up
3845 ** to a comment remarkably similar to this one) is currently considered
3846 ** to be experimental.  The interface might change in incompatible ways.
3847 ** If this is a problem for you, do not use the interface at this time.
3848 **
3849 ** When the virtual-table mechanism stabilizes, we will declare the
3850 ** interface fixed, support it indefinitely, and remove this comment.
3851 **
3852 ****** EXPERIMENTAL - subject to change without notice **************
3853 */
3854
3855 /*
3856 ** CAPI3REF: A Handle To An Open BLOB {F17800}
3857 **
3858 ** An instance of the following opaque structure is used to 
3859 ** represent an blob-handle.  A blob-handle is created by
3860 ** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()].
3861 ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
3862 ** can be used to read or write small subsections of the blob.
3863 ** The [sqlite3_blob_bytes()] interface returns the size of the
3864 ** blob in bytes.
3865 */
3866 typedef struct sqlite3_blob sqlite3_blob;
3867
3868 /*
3869 ** CAPI3REF: Open A BLOB For Incremental I/O {F17810}
3870 **
3871 ** {F17811} This interfaces opens a handle to the blob located
3872 ** in row iRow,, column zColumn, table zTable in database zDb;
3873 ** in other words,  the same blob that would be selected by:
3874 **
3875 ** <pre>
3876 **     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
3877 ** </pre> {END}
3878 **
3879 ** {F17812} If the flags parameter is non-zero, the blob is opened for 
3880 ** read and write access. If it is zero, the blob is opened for read 
3881 ** access. {END}
3882 **
3883 ** {F17813} On success, [SQLITE_OK] is returned and the new 
3884 ** [sqlite3_blob | blob handle] is written to *ppBlob. 
3885 ** {F17814} Otherwise an error code is returned and 
3886 ** any value written to *ppBlob should not be used by the caller.
3887 ** {F17815} This function sets the database-handle error code and message
3888 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()].
3889 ** <todo>We should go through and mark all interfaces that behave this
3890 ** way with a similar statement</todo>
3891 */
3892 SQLITE_API int sqlite3_blob_open(
3893   sqlite3*,
3894   const char *zDb,
3895   const char *zTable,
3896   const char *zColumn,
3897   sqlite3_int64 iRow,
3898   int flags,
3899   sqlite3_blob **ppBlob
3900 );
3901
3902 /*
3903 ** CAPI3REF:  Close A BLOB Handle {F17830}
3904 **
3905 ** Close an open [sqlite3_blob | blob handle].
3906 **
3907 ** {F17831} Closing a BLOB shall cause the current transaction to commit
3908 ** if there are no other BLOBs, no pending prepared statements, and the
3909 ** database connection is in autocommit mode.
3910 ** {F17832} If any writes were made to the BLOB, they might be held in cache
3911 ** until the close operation if they will fit. {END}
3912 ** Closing the BLOB often forces the changes
3913 ** out to disk and so if any I/O errors occur, they will likely occur
3914 ** at the time when the BLOB is closed.  {F17833} Any errors that occur during
3915 ** closing are reported as a non-zero return value.
3916 **
3917 ** {F17839} The BLOB is closed unconditionally.  Even if this routine returns
3918 ** an error code, the BLOB is still closed.
3919 */
3920 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
3921
3922 /*
3923 ** CAPI3REF:  Return The Size Of An Open BLOB {F17805}
3924 **
3925 ** {F16806} Return the size in bytes of the blob accessible via the open 
3926 ** [sqlite3_blob | blob-handle] passed as an argument.
3927 */
3928 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
3929
3930 /*
3931 ** CAPI3REF:  Read Data From A BLOB Incrementally {F17850}
3932 **
3933 ** This function is used to read data from an open 
3934 ** [sqlite3_blob | blob-handle] into a caller supplied buffer.
3935 ** {F17851} n bytes of data are copied into buffer
3936 ** z from the open blob, starting at offset iOffset.
3937 **
3938 ** {F17852} If offset iOffset is less than n bytes from the end of the blob, 
3939 ** [SQLITE_ERROR] is returned and no data is read.  {F17853} If n is
3940 ** less than zero [SQLITE_ERROR] is returned and no data is read.
3941 **
3942 ** {F17854} On success, SQLITE_OK is returned. Otherwise, an 
3943 ** [SQLITE_ERROR | SQLite error code] or an
3944 ** [SQLITE_IOERR_READ | extended error code] is returned.
3945 */
3946 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset);
3947
3948 /*
3949 ** CAPI3REF:  Write Data Into A BLOB Incrementally {F17870}
3950 **
3951 ** This function is used to write data into an open 
3952 ** [sqlite3_blob | blob-handle] from a user supplied buffer.
3953 ** {F17871} n bytes of data are copied from the buffer
3954 ** pointed to by z into the open blob, starting at offset iOffset.
3955 **
3956 ** {F17872} If the [sqlite3_blob | blob-handle] passed as the first argument
3957 ** was not opened for writing (the flags parameter to [sqlite3_blob_open()]
3958 *** was zero), this function returns [SQLITE_READONLY].
3959 **
3960 ** {F17873} This function may only modify the contents of the blob; it is
3961 ** not possible to increase the size of a blob using this API.
3962 ** {F17874} If offset iOffset is less than n bytes from the end of the blob, 
3963 ** [SQLITE_ERROR] is returned and no data is written.  {F17875} If n is
3964 ** less than zero [SQLITE_ERROR] is returned and no data is written.
3965 **
3966 ** {F17876} On success, SQLITE_OK is returned. Otherwise, an 
3967 ** [SQLITE_ERROR | SQLite error code] or an
3968 ** [SQLITE_IOERR_READ | extended error code] is returned.
3969 */
3970 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
3971
3972 /*
3973 ** CAPI3REF:  Virtual File System Objects {F11200}
3974 **
3975 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
3976 ** that SQLite uses to interact
3977 ** with the underlying operating system.  Most builds come with a
3978 ** single default VFS that is appropriate for the host computer.
3979 ** New VFSes can be registered and existing VFSes can be unregistered.
3980 ** The following interfaces are provided.
3981 **
3982 ** {F11201} The sqlite3_vfs_find() interface returns a pointer to 
3983 ** a VFS given its name.  {F11202} Names are case sensitive.
3984 ** {F11203} Names are zero-terminated UTF-8 strings.
3985 ** {F11204} If there is no match, a NULL
3986 ** pointer is returned. {F11205} If zVfsName is NULL then the default 
3987 ** VFS is returned. {END}
3988 **
3989 ** {F11210} New VFSes are registered with sqlite3_vfs_register().
3990 ** {F11211} Each new VFS becomes the default VFS if the makeDflt flag is set.
3991 ** {F11212} The same VFS can be registered multiple times without injury.
3992 ** {F11213} To make an existing VFS into the default VFS, register it again
3993 ** with the makeDflt flag set. {U11214} If two different VFSes with the
3994 ** same name are registered, the behavior is undefined.  {U11215} If a
3995 ** VFS is registered with a name that is NULL or an empty string,
3996 ** then the behavior is undefined.
3997 ** 
3998 ** {F11220} Unregister a VFS with the sqlite3_vfs_unregister() interface.
3999 ** {F11221} If the default VFS is unregistered, another VFS is chosen as
4000 ** the default.  The choice for the new VFS is arbitrary.
4001 */
4002 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
4003 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
4004 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
4005
4006 /*
4007 ** CAPI3REF: Mutexes {F17000}
4008 **
4009 ** The SQLite core uses these routines for thread
4010 ** synchronization.  Though they are intended for internal
4011 ** use by SQLite, code that links against SQLite is
4012 ** permitted to use any of these routines.
4013 **
4014 ** The SQLite source code contains multiple implementations 
4015 ** of these mutex routines.  An appropriate implementation
4016 ** is selected automatically at compile-time.  The following
4017 ** implementations are available in the SQLite core:
4018 **
4019 ** <ul>
4020 ** <li>   SQLITE_MUTEX_OS2
4021 ** <li>   SQLITE_MUTEX_PTHREAD
4022 ** <li>   SQLITE_MUTEX_W32
4023 ** <li>   SQLITE_MUTEX_NOOP
4024 ** </ul>
4025 **
4026 ** The SQLITE_MUTEX_NOOP implementation is a set of routines 
4027 ** that does no real locking and is appropriate for use in 
4028 ** a single-threaded application.  The SQLITE_MUTEX_OS2,
4029 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
4030 ** are appropriate for use on os/2, unix, and windows.
4031 ** 
4032 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
4033 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
4034 ** implementation is included with the library.  The
4035 ** mutex interface routines defined here become external
4036 ** references in the SQLite library for which implementations
4037 ** must be provided by the application.  This facility allows an
4038 ** application that links against SQLite to provide its own mutex
4039 ** implementation without having to modify the SQLite core.
4040 **
4041 ** {F17011} The sqlite3_mutex_alloc() routine allocates a new
4042 ** mutex and returns a pointer to it. {F17012} If it returns NULL
4043 ** that means that a mutex could not be allocated. {F17013} SQLite
4044 ** will unwind its stack and return an error. {F17014} The argument
4045 ** to sqlite3_mutex_alloc() is one of these integer constants:
4046 **
4047 ** <ul>
4048 ** <li>  SQLITE_MUTEX_FAST
4049 ** <li>  SQLITE_MUTEX_RECURSIVE
4050 ** <li>  SQLITE_MUTEX_STATIC_MASTER
4051 ** <li>  SQLITE_MUTEX_STATIC_MEM
4052 ** <li>  SQLITE_MUTEX_STATIC_MEM2
4053 ** <li>  SQLITE_MUTEX_STATIC_PRNG
4054 ** <li>  SQLITE_MUTEX_STATIC_LRU
4055 ** </ul> {END}
4056 **
4057 ** {F17015} The first two constants cause sqlite3_mutex_alloc() to create
4058 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
4059 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END}
4060 ** The mutex implementation does not need to make a distinction
4061 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
4062 ** not want to.  {F17016} But SQLite will only request a recursive mutex in
4063 ** cases where it really needs one.  {END} If a faster non-recursive mutex
4064 ** implementation is available on the host platform, the mutex subsystem
4065 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
4066 **
4067 ** {F17017} The other allowed parameters to sqlite3_mutex_alloc() each return
4068 ** a pointer to a static preexisting mutex. {END}  Four static mutexes are
4069 ** used by the current version of SQLite.  Future versions of SQLite
4070 ** may add additional static mutexes.  Static mutexes are for internal
4071 ** use by SQLite only.  Applications that use SQLite mutexes should
4072 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
4073 ** SQLITE_MUTEX_RECURSIVE.
4074 **
4075 ** {F17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
4076 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
4077 ** returns a different mutex on every call.  {F17034} But for the static 
4078 ** mutex types, the same mutex is returned on every call that has
4079 ** the same type number. {END}
4080 **
4081 ** {F17019} The sqlite3_mutex_free() routine deallocates a previously
4082 ** allocated dynamic mutex. {F17020} SQLite is careful to deallocate every
4083 ** dynamic mutex that it allocates. {U17021} The dynamic mutexes must not be in 
4084 ** use when they are deallocated. {U17022} Attempting to deallocate a static
4085 ** mutex results in undefined behavior. {F17023} SQLite never deallocates
4086 ** a static mutex. {END}
4087 **
4088 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
4089 ** to enter a mutex. {F17024} If another thread is already within the mutex,
4090 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
4091 ** SQLITE_BUSY. {F17025}  The sqlite3_mutex_try() interface returns SQLITE_OK
4092 ** upon successful entry.  {F17026} Mutexes created using
4093 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
4094 ** {F17027} In such cases the,
4095 ** mutex must be exited an equal number of times before another thread
4096 ** can enter.  {U17028} If the same thread tries to enter any other
4097 ** kind of mutex more than once, the behavior is undefined.
4098 ** {F17029} SQLite will never exhibit
4099 ** such behavior in its own use of mutexes. {END}
4100 **
4101 ** Some systems (ex: windows95) do not the operation implemented by
4102 ** sqlite3_mutex_try().  On those systems, sqlite3_mutex_try() will
4103 ** always return SQLITE_BUSY.  {F17030} The SQLite core only ever uses
4104 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior. {END}
4105 **
4106 ** {F17031} The sqlite3_mutex_leave() routine exits a mutex that was
4107 ** previously entered by the same thread.  {U17032} The behavior
4108 ** is undefined if the mutex is not currently entered by the
4109 ** calling thread or is not currently allocated.  {F17033} SQLite will
4110 ** never do either. {END}
4111 **
4112 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
4113 */
4114 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
4115 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
4116 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
4117 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
4118 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
4119
4120 /*
4121 ** CAPI3REF: Mutex Verifcation Routines {F17080}
4122 **
4123 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
4124 ** are intended for use inside assert() statements. {F17081} The SQLite core
4125 ** never uses these routines except inside an assert() and applications
4126 ** are advised to follow the lead of the core.  {F17082} The core only
4127 ** provides implementations for these routines when it is compiled
4128 ** with the SQLITE_DEBUG flag.  {U17087} External mutex implementations
4129 ** are only required to provide these routines if SQLITE_DEBUG is
4130 ** defined and if NDEBUG is not defined.
4131 **
4132 ** {F17083} These routines should return true if the mutex in their argument
4133 ** is held or not held, respectively, by the calling thread. {END}
4134 **
4135 ** {X17084} The implementation is not required to provided versions of these
4136 ** routines that actually work.
4137 ** If the implementation does not provide working
4138 ** versions of these routines, it should at least provide stubs
4139 ** that always return true so that one does not get spurious
4140 ** assertion failures. {END}
4141 **
4142 ** {F17085} If the argument to sqlite3_mutex_held() is a NULL pointer then
4143 ** the routine should return 1.  {END} This seems counter-intuitive since
4144 ** clearly the mutex cannot be held if it does not exist.  But the
4145 ** the reason the mutex does not exist is because the build is not
4146 ** using mutexes.  And we do not want the assert() containing the
4147 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
4148 ** the appropriate thing to do.  {F17086} The sqlite3_mutex_notheld() 
4149 ** interface should also return 1 when given a NULL pointer.
4150 */
4151 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
4152 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
4153
4154 /*
4155 ** CAPI3REF: Mutex Types {F17001}
4156 **
4157 ** {F17002} The [sqlite3_mutex_alloc()] interface takes a single argument
4158 ** which is one of these integer constants. {END}
4159 */
4160 #define SQLITE_MUTEX_FAST             0
4161 #define SQLITE_MUTEX_RECURSIVE        1
4162 #define SQLITE_MUTEX_STATIC_MASTER    2
4163 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
4164 #define SQLITE_MUTEX_STATIC_MEM2      4  /* sqlite3_release_memory() */
4165 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
4166 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
4167
4168 /*
4169 ** CAPI3REF: Low-Level Control Of Database Files {F11300}
4170 **
4171 ** {F11301} The [sqlite3_file_control()] interface makes a direct call to the
4172 ** xFileControl method for the [sqlite3_io_methods] object associated
4173 ** with a particular database identified by the second argument. {F11302} The
4174 ** name of the database is the name assigned to the database by the
4175 ** <a href="lang_attach.html">ATTACH</a> SQL command that opened the
4176 ** database. {F11303} To control the main database file, use the name "main"
4177 ** or a NULL pointer. {F11304} The third and fourth parameters to this routine
4178 ** are passed directly through to the second and third parameters of
4179 ** the xFileControl method.  {F11305} The return value of the xFileControl
4180 ** method becomes the return value of this routine.
4181 **
4182 ** {F11306} If the second parameter (zDbName) does not match the name of any
4183 ** open database file, then SQLITE_ERROR is returned. {F11307} This error
4184 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
4185 ** or [sqlite3_errmsg()]. {U11308} The underlying xFileControl method might
4186 ** also return SQLITE_ERROR.  {U11309} There is no way to distinguish between
4187 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
4188 ** xFileControl method. {END}
4189 **
4190 ** See also: [SQLITE_FCNTL_LOCKSTATE]
4191 */
4192 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
4193
4194 /*
4195 ** Undo the hack that converts floating point types to integer for
4196 ** builds on processors without floating point support.
4197 */
4198 #ifdef SQLITE_OMIT_FLOATING_POINT
4199 # undef double
4200 #endif
4201
4202 #if 0
4203 }  /* End of the 'extern "C"' block */
4204 #endif
4205 #endif
4206
4207 /************** End of sqlite3.h *********************************************/
4208 /************** Continuing where we left off in sqliteInt.h ******************/
4209 /************** Include hash.h in the middle of sqliteInt.h ******************/
4210 /************** Begin file hash.h ********************************************/
4211 /*
4212 ** 2001 September 22
4213 **
4214 ** The author disclaims copyright to this source code.  In place of
4215 ** a legal notice, here is a blessing:
4216 **
4217 **    May you do good and not evil.
4218 **    May you find forgiveness for yourself and forgive others.
4219 **    May you share freely, never taking more than you give.
4220 **
4221 *************************************************************************
4222 ** This is the header file for the generic hash-table implemenation
4223 ** used in SQLite.
4224 **
4225 ** $Id: hash.h,v 1.11 2007/09/04 14:31:47 danielk1977 Exp $
4226 */
4227 #ifndef _SQLITE_HASH_H_
4228 #define _SQLITE_HASH_H_
4229
4230 /* Forward declarations of structures. */
4231 typedef struct Hash Hash;
4232 typedef struct HashElem HashElem;
4233
4234 /* A complete hash table is an instance of the following structure.
4235 ** The internals of this structure are intended to be opaque -- client
4236 ** code should not attempt to access or modify the fields of this structure
4237 ** directly.  Change this structure only by using the routines below.
4238 ** However, many of the "procedures" and "functions" for modifying and
4239 ** accessing this structure are really macros, so we can't really make
4240 ** this structure opaque.
4241 */
4242 struct Hash {
4243   char keyClass;          /* SQLITE_HASH_INT, _POINTER, _STRING, _BINARY */
4244   char copyKey;           /* True if copy of key made on insert */
4245   int count;              /* Number of entries in this table */
4246   int htsize;             /* Number of buckets in the hash table */
4247   HashElem *first;        /* The first element of the array */
4248   struct _ht {            /* the hash table */
4249     int count;               /* Number of entries with this hash */
4250     HashElem *chain;         /* Pointer to first entry with this hash */
4251   } *ht;
4252 };
4253
4254 /* Each element in the hash table is an instance of the following 
4255 ** structure.  All elements are stored on a single doubly-linked list.
4256 **
4257 ** Again, this structure is intended to be opaque, but it can't really
4258 ** be opaque because it is used by macros.
4259 */
4260 struct HashElem {
4261   HashElem *next, *prev;   /* Next and previous elements in the table */
4262   void *data;              /* Data associated with this element */
4263   void *pKey; int nKey;    /* Key associated with this element */
4264 };
4265
4266 /*
4267 ** There are 4 different modes of operation for a hash table:
4268 **
4269 **   SQLITE_HASH_INT         nKey is used as the key and pKey is ignored.
4270 **
4271 **   SQLITE_HASH_POINTER     pKey is used as the key and nKey is ignored.
4272 **
4273 **   SQLITE_HASH_STRING      pKey points to a string that is nKey bytes long
4274 **                           (including the null-terminator, if any).  Case
4275 **                           is ignored in comparisons.
4276 **
4277 **   SQLITE_HASH_BINARY      pKey points to binary data nKey bytes long. 
4278 **                           memcmp() is used to compare keys.
4279 **
4280 ** A copy of the key is made for SQLITE_HASH_STRING and SQLITE_HASH_BINARY
4281 ** if the copyKey parameter to HashInit is 1.  
4282 */
4283 /* #define SQLITE_HASH_INT       1 // NOT USED */
4284 /* #define SQLITE_HASH_POINTER   2 // NOT USED */
4285 #define SQLITE_HASH_STRING    3
4286 #define SQLITE_HASH_BINARY    4
4287
4288 /*
4289 ** Access routines.  To delete, insert a NULL pointer.
4290 */
4291 SQLITE_PRIVATE void sqlite3HashInit(Hash*, int keytype, int copyKey);
4292 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const void *pKey, int nKey, void *pData);
4293 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const void *pKey, int nKey);
4294 SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash*, const void *pKey, int nKey);
4295 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
4296
4297 /*
4298 ** Macros for looping over all elements of a hash table.  The idiom is
4299 ** like this:
4300 **
4301 **   Hash h;
4302 **   HashElem *p;
4303 **   ...
4304 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
4305 **     SomeStructure *pData = sqliteHashData(p);
4306 **     // do something with pData
4307 **   }
4308 */
4309 #define sqliteHashFirst(H)  ((H)->first)
4310 #define sqliteHashNext(E)   ((E)->next)
4311 #define sqliteHashData(E)   ((E)->data)
4312 #define sqliteHashKey(E)    ((E)->pKey)
4313 #define sqliteHashKeysize(E) ((E)->nKey)
4314
4315 /*
4316 ** Number of entries in a hash table
4317 */
4318 #define sqliteHashCount(H)  ((H)->count)
4319
4320 #endif /* _SQLITE_HASH_H_ */
4321
4322 /************** End of hash.h ************************************************/
4323 /************** Continuing where we left off in sqliteInt.h ******************/
4324 /************** Include parse.h in the middle of sqliteInt.h *****************/
4325 /************** Begin file parse.h *******************************************/
4326 #define TK_SEMI                            1
4327 #define TK_EXPLAIN                         2
4328 #define TK_QUERY                           3
4329 #define TK_PLAN                            4
4330 #define TK_BEGIN                           5
4331 #define TK_TRANSACTION                     6
4332 #define TK_DEFERRED                        7
4333 #define TK_IMMEDIATE                       8
4334 #define TK_EXCLUSIVE                       9
4335 #define TK_COMMIT                         10
4336 #define TK_END                            11
4337 #define TK_ROLLBACK                       12
4338 #define TK_CREATE                         13
4339 #define TK_TABLE                          14
4340 #define TK_IF                             15
4341 #define TK_NOT                            16
4342 #define TK_EXISTS                         17
4343 #define TK_TEMP                           18
4344 #define TK_LP                             19
4345 #define TK_RP                             20
4346 #define TK_AS                             21
4347 #define TK_COMMA                          22
4348 #define TK_ID                             23
4349 #define TK_ABORT                          24
4350 #define TK_AFTER                          25
4351 #define TK_ANALYZE                        26
4352 #define TK_ASC                            27
4353 #define TK_ATTACH                         28
4354 #define TK_BEFORE                         29
4355 #define TK_CASCADE                        30
4356 #define TK_CAST                           31
4357 #define TK_CONFLICT                       32
4358 #define TK_DATABASE                       33
4359 #define TK_DESC                           34
4360 #define TK_DETACH                         35
4361 #define TK_EACH                           36
4362 #define TK_FAIL                           37
4363 #define TK_FOR                            38
4364 #define TK_IGNORE                         39
4365 #define TK_INITIALLY                      40
4366 #define TK_INSTEAD                        41
4367 #define TK_LIKE_KW                        42
4368 #define TK_MATCH                          43
4369 #define TK_KEY                            44
4370 #define TK_OF                             45
4371 #define TK_OFFSET                         46
4372 #define TK_PRAGMA                         47
4373 #define TK_RAISE                          48
4374 #define TK_REPLACE                        49
4375 #define TK_RESTRICT                       50
4376 #define TK_ROW                            51
4377 #define TK_TRIGGER                        52
4378 #define TK_VACUUM                         53
4379 #define TK_VIEW                           54
4380 #define TK_VIRTUAL                        55
4381 #define TK_REINDEX                        56
4382 #define TK_RENAME                         57
4383 #define TK_CTIME_KW                       58
4384 #define TK_ANY                            59
4385 #define TK_OR                             60
4386 #define TK_AND                            61
4387 #define TK_IS                             62
4388 #define TK_BETWEEN                        63
4389 #define TK_IN                             64
4390 #define TK_ISNULL                         65
4391 #define TK_NOTNULL                        66
4392 #define TK_NE                             67
4393 #define TK_EQ                             68
4394 #define TK_GT                             69
4395 #define TK_LE                             70
4396 #define TK_LT                             71
4397 #define TK_GE                             72
4398 #define TK_ESCAPE                         73
4399 #define TK_BITAND                         74
4400 #define TK_BITOR                          75
4401 #define TK_LSHIFT                         76
4402 #define TK_RSHIFT                         77
4403 #define TK_PLUS                           78
4404 #define TK_MINUS                          79
4405 #define TK_STAR                           80
4406 #define TK_SLASH                          81
4407 #define TK_REM                            82
4408 #define TK_CONCAT                         83
4409 #define TK_COLLATE                        84
4410 #define TK_UMINUS                         85
4411 #define TK_UPLUS                          86
4412 #define TK_BITNOT                         87
4413 #define TK_STRING                         88
4414 #define TK_JOIN_KW                        89
4415 #define TK_CONSTRAINT                     90
4416 #define TK_DEFAULT                        91
4417 #define TK_NULL                           92
4418 #define TK_PRIMARY                        93
4419 #define TK_UNIQUE                         94
4420 #define TK_CHECK                          95
4421 #define TK_REFERENCES                     96
4422 #define TK_AUTOINCR                       97
4423 #define TK_ON                             98
4424 #define TK_DELETE                         99
4425 #define TK_UPDATE                         100
4426 #define TK_INSERT                         101
4427 #define TK_SET                            102
4428 #define TK_DEFERRABLE                     103
4429 #define TK_FOREIGN                        104
4430 #define TK_DROP                           105
4431 #define TK_UNION                          106
4432 #define TK_ALL                            107
4433 #define TK_EXCEPT                         108
4434 #define TK_INTERSECT                      109
4435 #define TK_SELECT                         110
4436 #define TK_DISTINCT                       111
4437 #define TK_DOT                            112
4438 #define TK_FROM                           113
4439 #define TK_JOIN                           114
4440 #define TK_USING                          115
4441 #define TK_ORDER                          116
4442 #define TK_BY                             117
4443 #define TK_GROUP                          118
4444 #define TK_HAVING                         119
4445 #define TK_LIMIT                          120
4446 #define TK_WHERE                          121
4447 #define TK_INTO                           122
4448 #define TK_VALUES                         123
4449 #define TK_INTEGER                        124
4450 #define TK_FLOAT                          125
4451 #define TK_BLOB                           126
4452 #define TK_REGISTER                       127
4453 #define TK_VARIABLE                       128
4454 #define TK_CASE                           129
4455 #define TK_WHEN                           130
4456 #define TK_THEN                           131
4457 #define TK_ELSE                           132
4458 #define TK_INDEX                          133
4459 #define TK_ALTER                          134
4460 #define TK_TO                             135
4461 #define TK_ADD                            136
4462 #define TK_COLUMNKW                       137
4463 #define TK_TO_TEXT                        138
4464 #define TK_TO_BLOB                        139
4465 #define TK_TO_NUMERIC                     140
4466 #define TK_TO_INT                         141
4467 #define TK_TO_REAL                        142
4468 #define TK_END_OF_FILE                    143
4469 #define TK_ILLEGAL                        144
4470 #define TK_SPACE                          145
4471 #define TK_UNCLOSED_STRING                146
4472 #define TK_COMMENT                        147
4473 #define TK_FUNCTION                       148
4474 #define TK_COLUMN                         149
4475 #define TK_AGG_FUNCTION                   150
4476 #define TK_AGG_COLUMN                     151
4477 #define TK_CONST_FUNC                     152
4478
4479 /************** End of parse.h ***********************************************/
4480 /************** Continuing where we left off in sqliteInt.h ******************/
4481 #include <stdio.h>
4482 #include <stdlib.h>
4483 #include <string.h>
4484 #include <assert.h>
4485 #include <stddef.h>
4486
4487 #define sqlite3_isnan(X)  ((X)!=(X))
4488
4489 /*
4490 ** If compiling for a processor that lacks floating point support,
4491 ** substitute integer for floating-point
4492 */
4493 #ifdef SQLITE_OMIT_FLOATING_POINT
4494 # define double sqlite_int64
4495 # define LONGDOUBLE_TYPE sqlite_int64
4496 # ifndef SQLITE_BIG_DBL
4497 #   define SQLITE_BIG_DBL (0x7fffffffffffffff)
4498 # endif
4499 # define SQLITE_OMIT_DATETIME_FUNCS 1
4500 # define SQLITE_OMIT_TRACE 1
4501 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
4502 #endif
4503 #ifndef SQLITE_BIG_DBL
4504 # define SQLITE_BIG_DBL (1e99)
4505 #endif
4506
4507 /*
4508 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
4509 ** afterward. Having this macro allows us to cause the C compiler 
4510 ** to omit code used by TEMP tables without messy #ifndef statements.
4511 */
4512 #ifdef SQLITE_OMIT_TEMPDB
4513 #define OMIT_TEMPDB 1
4514 #else
4515 #define OMIT_TEMPDB 0
4516 #endif
4517
4518 /*
4519 ** If the following macro is set to 1, then NULL values are considered
4520 ** distinct when determining whether or not two entries are the same
4521 ** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
4522 ** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
4523 ** is the way things are suppose to work.
4524 **
4525 ** If the following macro is set to 0, the NULLs are indistinct for
4526 ** a UNIQUE index.  In this mode, you can only have a single NULL entry
4527 ** for a column declared UNIQUE.  This is the way Informix and SQL Server
4528 ** work.
4529 */
4530 #define NULL_DISTINCT_FOR_UNIQUE 1
4531
4532 /*
4533 ** The "file format" number is an integer that is incremented whenever
4534 ** the VDBE-level file format changes.  The following macros define the
4535 ** the default file format for new databases and the maximum file format
4536 ** that the library can read.
4537 */
4538 #define SQLITE_MAX_FILE_FORMAT 4
4539 #ifndef SQLITE_DEFAULT_FILE_FORMAT
4540 # define SQLITE_DEFAULT_FILE_FORMAT 1
4541 #endif
4542
4543 /*
4544 ** Provide a default value for TEMP_STORE in case it is not specified
4545 ** on the command-line
4546 */
4547 #ifndef TEMP_STORE
4548 # define TEMP_STORE 1
4549 #endif
4550
4551 /*
4552 ** GCC does not define the offsetof() macro so we'll have to do it
4553 ** ourselves.
4554 */
4555 #ifndef offsetof
4556 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
4557 #endif
4558
4559 /*
4560 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
4561 ** not, there are still machines out there that use EBCDIC.)
4562 */
4563 #if 'A' == '\301'
4564 # define SQLITE_EBCDIC 1
4565 #else
4566 # define SQLITE_ASCII 1
4567 #endif
4568
4569 /*
4570 ** Integers of known sizes.  These typedefs might change for architectures
4571 ** where the sizes very.  Preprocessor macros are available so that the
4572 ** types can be conveniently redefined at compile-type.  Like this:
4573 **
4574 **         cc '-DUINTPTR_TYPE=long long int' ...
4575 */
4576 #ifndef UINT32_TYPE
4577 # define UINT32_TYPE unsigned int
4578 #endif
4579 #ifndef UINT16_TYPE
4580 # define UINT16_TYPE unsigned short int
4581 #endif
4582 #ifndef INT16_TYPE
4583 # define INT16_TYPE short int
4584 #endif
4585 #ifndef UINT8_TYPE
4586 # define UINT8_TYPE unsigned char
4587 #endif
4588 #ifndef INT8_TYPE
4589 # define INT8_TYPE signed char
4590 #endif
4591 #ifndef LONGDOUBLE_TYPE
4592 # define LONGDOUBLE_TYPE long double
4593 #endif
4594 typedef sqlite_int64 i64;          /* 8-byte signed integer */
4595 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
4596 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
4597 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
4598 typedef INT16_TYPE i16;            /* 2-byte signed integer */
4599 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
4600 typedef UINT8_TYPE i8;             /* 1-byte signed integer */
4601
4602 /*
4603 ** Macros to determine whether the machine is big or little endian,
4604 ** evaluated at runtime.
4605 */
4606 #ifdef SQLITE_AMALGAMATION
4607 SQLITE_PRIVATE const int sqlite3One;
4608 #else
4609 SQLITE_PRIVATE const int sqlite3one;
4610 #endif
4611 #if defined(i386) || defined(__i386__) || defined(_M_IX86)
4612 # define SQLITE_BIGENDIAN    0
4613 # define SQLITE_LITTLEENDIAN 1
4614 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
4615 #else
4616 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
4617 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
4618 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
4619 #endif
4620
4621 /*
4622 ** An instance of the following structure is used to store the busy-handler
4623 ** callback for a given sqlite handle. 
4624 **
4625 ** The sqlite.busyHandler member of the sqlite struct contains the busy
4626 ** callback for the database handle. Each pager opened via the sqlite
4627 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
4628 ** callback is currently invoked only from within pager.c.
4629 */
4630 typedef struct BusyHandler BusyHandler;
4631 struct BusyHandler {
4632   int (*xFunc)(void *,int);  /* The busy callback */
4633   void *pArg;                /* First arg to busy callback */
4634   int nBusy;                 /* Incremented with each busy call */
4635 };
4636
4637 /*
4638 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
4639 ** "BusyHandler typedefs.
4640 */
4641 /************** Include btree.h in the middle of sqliteInt.h *****************/
4642 /************** Begin file btree.h *******************************************/
4643 /*
4644 ** 2001 September 15
4645 **
4646 ** The author disclaims copyright to this source code.  In place of
4647 ** a legal notice, here is a blessing:
4648 **
4649 **    May you do good and not evil.
4650 **    May you find forgiveness for yourself and forgive others.
4651 **    May you share freely, never taking more than you give.
4652 **
4653 *************************************************************************
4654 ** This header file defines the interface that the sqlite B-Tree file
4655 ** subsystem.  See comments in the source code for a detailed description
4656 ** of what each interface routine does.
4657 **
4658 ** @(#) $Id: btree.h,v 1.94 2007/12/07 18:55:28 drh Exp $
4659 */
4660 #ifndef _BTREE_H_
4661 #define _BTREE_H_
4662
4663 /* TODO: This definition is just included so other modules compile. It
4664 ** needs to be revisited.
4665 */
4666 #define SQLITE_N_BTREE_META 10
4667
4668 /*
4669 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
4670 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
4671 */
4672 #ifndef SQLITE_DEFAULT_AUTOVACUUM
4673   #define SQLITE_DEFAULT_AUTOVACUUM 0
4674 #endif
4675
4676 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
4677 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
4678 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
4679
4680 /*
4681 ** Forward declarations of structure
4682 */
4683 typedef struct Btree Btree;
4684 typedef struct BtCursor BtCursor;
4685 typedef struct BtShared BtShared;
4686 typedef struct BtreeMutexArray BtreeMutexArray;
4687
4688 /*
4689 ** This structure records all of the Btrees that need to hold
4690 ** a mutex before we enter sqlite3VdbeExec().  The Btrees are
4691 ** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
4692 ** we can always lock and unlock them all quickly.
4693 */
4694 struct BtreeMutexArray {
4695   int nMutex;
4696   Btree *aBtree[SQLITE_MAX_ATTACHED+1];
4697 };
4698
4699
4700 SQLITE_PRIVATE int sqlite3BtreeOpen(
4701   const char *zFilename,   /* Name of database file to open */
4702   sqlite3 *db,             /* Associated database connection */
4703   Btree **,                /* Return open Btree* here */
4704   int flags,               /* Flags */
4705   int vfsFlags             /* Flags passed through to VFS open */
4706 );
4707
4708 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
4709 ** following values.
4710 **
4711 ** NOTE:  These values must match the corresponding PAGER_ values in
4712 ** pager.h.
4713 */
4714 #define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
4715 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
4716 #define BTREE_MEMORY        4  /* In-memory DB.  No argument */
4717 #define BTREE_READONLY      8  /* Open the database in read-only mode */
4718 #define BTREE_READWRITE    16  /* Open for both reading and writing */
4719 #define BTREE_CREATE       32  /* Create the database if it does not exist */
4720
4721 /* Additional values for the 4th argument of sqlite3BtreeOpen that
4722 ** are not associated with PAGER_ values.
4723 */
4724 #define BTREE_PRIVATE      64  /* Never share with other connections */
4725
4726 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
4727 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
4728 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
4729 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
4730 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree*,int,int);
4731 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
4732 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
4733 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
4734 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
4735 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
4736 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
4737 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
4738 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
4739 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
4740 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
4741 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*);
4742 SQLITE_PRIVATE int sqlite3BtreeCommitStmt(Btree*);
4743 SQLITE_PRIVATE int sqlite3BtreeRollbackStmt(Btree*);
4744 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
4745 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
4746 SQLITE_PRIVATE int sqlite3BtreeIsInStmt(Btree*);
4747 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
4748 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
4749 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *);
4750 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *, int, u8);
4751
4752 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
4753 SQLITE_PRIVATE const char *sqlite3BtreeGetDirname(Btree *);
4754 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
4755 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
4756
4757 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
4758
4759 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
4760 ** of the following flags:
4761 */
4762 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
4763 #define BTREE_ZERODATA   2    /* Table has keys only - no data */
4764 #define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */
4765
4766 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
4767 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int);
4768 SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree*, int idx, u32 *pValue);
4769 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
4770 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
4771
4772 SQLITE_PRIVATE int sqlite3BtreeCursor(
4773   Btree*,                              /* BTree containing table to open */
4774   int iTable,                          /* Index of root page */
4775   int wrFlag,                          /* 1 for writing.  0 for read-only */
4776   int(*)(void*,int,const void*,int,const void*),  /* Key comparison function */
4777   void*,                               /* First argument to compare function */
4778   BtCursor **ppCursor                  /* Returned cursor */
4779 );
4780
4781 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
4782 SQLITE_PRIVATE int sqlite3BtreeMoveto(BtCursor*,const void *pKey,i64 nKey,int bias,int *pRes);
4783 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
4784 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
4785                                   const void *pData, int nData,
4786                                   int nZero, int bias);
4787 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
4788 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
4789 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
4790 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
4791 SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor*);
4792 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
4793 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
4794 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
4795 SQLITE_PRIVATE sqlite3 *sqlite3BtreeCursorDb(const BtCursor*);
4796 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
4797 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
4798 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
4799 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
4800
4801 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
4802 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
4803
4804 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
4805 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
4806
4807 #ifdef SQLITE_TEST
4808 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
4809 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
4810 SQLITE_PRIVATE int sqlite3BtreePageDump(Btree*, int, int recursive);
4811 #endif
4812
4813 /*
4814 ** If we are not using shared cache, then there is no need to
4815 ** use mutexes to access the BtShared structures.  So make the
4816 ** Enter and Leave procedures no-ops.
4817 */
4818 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
4819 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
4820 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
4821 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
4822 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
4823 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
4824 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
4825 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
4826 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
4827 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
4828 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
4829 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
4830 #else
4831 # define sqlite3BtreeEnter(X)
4832 # define sqlite3BtreeLeave(X)
4833 # define sqlite3BtreeHoldsMutex(X) 1
4834 # define sqlite3BtreeEnterCursor(X)
4835 # define sqlite3BtreeLeaveCursor(X)
4836 # define sqlite3BtreeEnterAll(X)
4837 # define sqlite3BtreeLeaveAll(X)
4838 # define sqlite3BtreeHoldsAllMutexes(X) 1
4839 # define sqlite3BtreeMutexArrayEnter(X)
4840 # define sqlite3BtreeMutexArrayLeave(X)
4841 # define sqlite3BtreeMutexArrayInsert(X,Y)
4842 #endif
4843
4844
4845 #endif /* _BTREE_H_ */
4846
4847 /************** End of btree.h ***********************************************/
4848 /************** Continuing where we left off in sqliteInt.h ******************/
4849 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
4850 /************** Begin file vdbe.h ********************************************/
4851 /*
4852 ** 2001 September 15
4853 **
4854 ** The author disclaims copyright to this source code.  In place of
4855 ** a legal notice, here is a blessing:
4856 **
4857 **    May you do good and not evil.
4858 **    May you find forgiveness for yourself and forgive others.
4859 **    May you share freely, never taking more than you give.
4860 **
4861 *************************************************************************
4862 ** Header file for the Virtual DataBase Engine (VDBE)
4863 **
4864 ** This header defines the interface to the virtual database engine
4865 ** or VDBE.  The VDBE implements an abstract machine that runs a
4866 ** simple program to access and modify the underlying database.
4867 **
4868 ** $Id: vdbe.h,v 1.115 2007/11/14 06:48:48 danielk1977 Exp $
4869 */
4870 #ifndef _SQLITE_VDBE_H_
4871 #define _SQLITE_VDBE_H_
4872
4873 /*
4874 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
4875 ** in the source file sqliteVdbe.c are allowed to see the insides
4876 ** of this structure.
4877 */
4878 typedef struct Vdbe Vdbe;
4879
4880 /*
4881 ** A single instruction of the virtual machine has an opcode
4882 ** and as many as three operands.  The instruction is recorded
4883 ** as an instance of the following structure:
4884 */
4885 struct VdbeOp {
4886   u8 opcode;          /* What operation to perform */
4887   int p1;             /* First operand */
4888   int p2;             /* Second parameter (often the jump destination) */
4889   char *p3;           /* Third parameter */
4890   int p3type;         /* One of the P3_xxx constants defined below */
4891 #ifdef VDBE_PROFILE
4892   int cnt;            /* Number of times this instruction was executed */
4893   long long cycles;   /* Total time spend executing this instruction */
4894 #endif
4895 };
4896 typedef struct VdbeOp VdbeOp;
4897
4898 /*
4899 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
4900 ** it takes up less space.
4901 */
4902 struct VdbeOpList {
4903   u8 opcode;          /* What operation to perform */
4904   signed char p1;     /* First operand */
4905   short int p2;       /* Second parameter (often the jump destination) */
4906   char *p3;           /* Third parameter */
4907 };
4908 typedef struct VdbeOpList VdbeOpList;
4909
4910 /*
4911 ** Allowed values of VdbeOp.p3type
4912 */
4913 #define P3_NOTUSED    0   /* The P3 parameter is not used */
4914 #define P3_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
4915 #define P3_STATIC   (-2)  /* Pointer to a static string */
4916 #define P3_COLLSEQ  (-4)  /* P3 is a pointer to a CollSeq structure */
4917 #define P3_FUNCDEF  (-5)  /* P3 is a pointer to a FuncDef structure */
4918 #define P3_KEYINFO  (-6)  /* P3 is a pointer to a KeyInfo structure */
4919 #define P3_VDBEFUNC (-7)  /* P3 is a pointer to a VdbeFunc structure */
4920 #define P3_MEM      (-8)  /* P3 is a pointer to a Mem*    structure */
4921 #define P3_TRANSIENT (-9) /* P3 is a pointer to a transient string */
4922 #define P3_VTAB     (-10) /* P3 is a pointer to an sqlite3_vtab structure */
4923 #define P3_MPRINTF  (-11) /* P3 is a string obtained from sqlite3_mprintf() */
4924 #define P3_REAL     (-12) /* P3 is a 64-bit floating point value */
4925 #define P3_INT64    (-13) /* P3 is a 64-bit signed integer */
4926
4927 /* When adding a P3 argument using P3_KEYINFO, a copy of the KeyInfo structure
4928 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
4929 ** argument is P3_KEYINFO_HANDOFF, the passed in pointer is used.  It still
4930 ** gets freed when the Vdbe is finalized so it still should be obtained
4931 ** from a single sqliteMalloc().  But no copy is made and the calling
4932 ** function should *not* try to free the KeyInfo.
4933 */
4934 #define P3_KEYINFO_HANDOFF (-9)
4935
4936 /*
4937 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
4938 ** number of columns of data returned by the statement.
4939 */
4940 #define COLNAME_NAME     0
4941 #define COLNAME_DECLTYPE 1
4942 #define COLNAME_DATABASE 2
4943 #define COLNAME_TABLE    3
4944 #define COLNAME_COLUMN   4
4945 #define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
4946
4947 /*
4948 ** The following macro converts a relative address in the p2 field
4949 ** of a VdbeOp structure into a negative number so that 
4950 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
4951 ** the macro again restores the address.
4952 */
4953 #define ADDR(X)  (-1-(X))
4954
4955 /*
4956 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
4957 ** header file that defines a number for each opcode used by the VDBE.
4958 */
4959 /************** Include opcodes.h in the middle of vdbe.h ********************/
4960 /************** Begin file opcodes.h *****************************************/
4961 /* Automatically generated.  Do not edit */
4962 /* See the mkopcodeh.awk script for details */
4963 #define OP_MemLoad                              1
4964 #define OP_VNext                                2
4965 #define OP_HexBlob                            126   /* same as TK_BLOB     */
4966 #define OP_Column                               3
4967 #define OP_SetCookie                            4
4968 #define OP_IfMemPos                             5
4969 #define OP_Real                               125   /* same as TK_FLOAT    */
4970 #define OP_Sequence                             6
4971 #define OP_MoveGt                               7
4972 #define OP_Ge                                  72   /* same as TK_GE       */
4973 #define OP_RowKey                               8
4974 #define OP_Eq                                  68   /* same as TK_EQ       */
4975 #define OP_OpenWrite                            9
4976 #define OP_NotNull                             66   /* same as TK_NOTNULL  */
4977 #define OP_If                                  10
4978 #define OP_ToInt                              141   /* same as TK_TO_INT   */
4979 #define OP_String8                             88   /* same as TK_STRING   */
4980 #define OP_Pop                                 11
4981 #define OP_VRowid                              12
4982 #define OP_CollSeq                             13
4983 #define OP_OpenRead                            14
4984 #define OP_Expire                              15
4985 #define OP_AutoCommit                          17
4986 #define OP_Gt                                  69   /* same as TK_GT       */
4987 #define OP_IntegrityCk                         18
4988 #define OP_Sort                                19
4989 #define OP_Function                            20
4990 #define OP_And                                 61   /* same as TK_AND      */
4991 #define OP_Subtract                            79   /* same as TK_MINUS    */
4992 #define OP_Noop                                21
4993 #define OP_Return                              22
4994 #define OP_Remainder                           82   /* same as TK_REM      */
4995 #define OP_NewRowid                            23
4996 #define OP_Multiply                            80   /* same as TK_STAR     */
4997 #define OP_IfMemNeg                            24
4998 #define OP_Variable                            25
4999 #define OP_String                              26
5000 #define OP_RealAffinity                        27
5001 #define OP_VRename                             28
5002 #define OP_ParseSchema                         29
5003 #define OP_VOpen                               30
5004 #define OP_Close                               31
5005 #define OP_CreateIndex                         32
5006 #define OP_IsUnique                            33
5007 #define OP_NotFound                            34
5008 #define OP_Int64                               35
5009 #define OP_MustBeInt                           36
5010 #define OP_Halt                                37
5011 #define OP_Rowid                               38
5012 #define OP_IdxLT                               39
5013 #define OP_AddImm                              40
5014 #define OP_Statement                           41
5015 #define OP_RowData                             42
5016 #define OP_MemMax                              43
5017 #define OP_Push                                44
5018 #define OP_Or                                  60   /* same as TK_OR       */
5019 #define OP_NotExists                           45
5020 #define OP_MemIncr                             46
5021 #define OP_Gosub                               47
5022 #define OP_Divide                              81   /* same as TK_SLASH    */
5023 #define OP_Integer                             48
5024 #define OP_ToNumeric                          140   /* same as TK_TO_NUMERIC*/
5025 #define OP_MemInt                              49
5026 #define OP_Prev                                50
5027 #define OP_Concat                              83   /* same as TK_CONCAT   */
5028 #define OP_BitAnd                              74   /* same as TK_BITAND   */
5029 #define OP_VColumn                             51
5030 #define OP_CreateTable                         52
5031 #define OP_Last                                53
5032 #define OP_IsNull                              65   /* same as TK_ISNULL   */
5033 #define OP_IncrVacuum                          54
5034 #define OP_IdxRowid                            55
5035 #define OP_MakeIdxRec                          56
5036 #define OP_ShiftRight                          77   /* same as TK_RSHIFT   */
5037 #define OP_ResetCount                          57
5038 #define OP_FifoWrite                           58
5039 #define OP_Callback                            59
5040 #define OP_ContextPush                         62
5041 #define OP_DropTrigger                         63
5042 #define OP_DropIndex                           64
5043 #define OP_IdxGE                               73
5044 #define OP_IdxDelete                           84
5045 #define OP_Vacuum                              86
5046 #define OP_MoveLe                              89
5047 #define OP_IfNot                               90
5048 #define OP_DropTable                           91
5049 #define OP_MakeRecord                          92
5050 #define OP_ToBlob                             139   /* same as TK_TO_BLOB  */
5051 #define OP_Delete                              93
5052 #define OP_StackDepth                          94
5053 #define OP_AggFinal                            95
5054 #define OP_ShiftLeft                           76   /* same as TK_LSHIFT   */
5055 #define OP_Dup                                 96
5056 #define OP_Goto                                97
5057 #define OP_TableLock                           98
5058 #define OP_FifoRead                            99
5059 #define OP_Clear                              100
5060 #define OP_IdxGT                              101
5061 #define OP_MoveLt                             102
5062 #define OP_Le                                  70   /* same as TK_LE       */
5063 #define OP_VerifyCookie                       103
5064 #define OP_AggStep                            104
5065 #define OP_Pull                               105
5066 #define OP_ToText                             138   /* same as TK_TO_TEXT  */
5067 #define OP_Not                                 16   /* same as TK_NOT      */
5068 #define OP_ToReal                             142   /* same as TK_TO_REAL  */
5069 #define OP_SetNumColumns                      106
5070 #define OP_AbsValue                           107
5071 #define OP_Transaction                        108
5072 #define OP_VFilter                            109
5073 #define OP_Negative                            85   /* same as TK_UMINUS   */
5074 #define OP_Ne                                  67   /* same as TK_NE       */
5075 #define OP_VDestroy                           110
5076 #define OP_ContextPop                         111
5077 #define OP_BitOr                               75   /* same as TK_BITOR    */
5078 #define OP_Next                               112
5079 #define OP_IdxInsert                          113
5080 #define OP_Distinct                           114
5081 #define OP_Lt                                  71   /* same as TK_LT       */
5082 #define OP_Insert                             115
5083 #define OP_Destroy                            116
5084 #define OP_ReadCookie                         117
5085 #define OP_ForceInt                           118
5086 #define OP_LoadAnalysis                       119
5087 #define OP_Explain                            120
5088 #define OP_IfMemZero                          121
5089 #define OP_OpenPseudo                         122
5090 #define OP_OpenEphemeral                      123
5091 #define OP_Null                               124
5092 #define OP_Blob                               127
5093 #define OP_Add                                 78   /* same as TK_PLUS     */
5094 #define OP_MemStore                           128
5095 #define OP_Rewind                             129
5096 #define OP_MoveGe                             130
5097 #define OP_VBegin                             131
5098 #define OP_VUpdate                            132
5099 #define OP_BitNot                              87   /* same as TK_BITNOT   */
5100 #define OP_VCreate                            133
5101 #define OP_MemMove                            134
5102 #define OP_MemNull                            135
5103 #define OP_Found                              136
5104 #define OP_NullRow                            137
5105
5106 /* Opcodes that are guaranteed to never push a value onto the stack
5107 ** contain a 1 their corresponding position of the following mask
5108 ** set.  See the opcodeNoPush() function in vdbeaux.c  */
5109 #define NOPUSH_MASK_0 0xeeb4
5110 #define NOPUSH_MASK_1 0xf96b
5111 #define NOPUSH_MASK_2 0xfbb6
5112 #define NOPUSH_MASK_3 0xfe64
5113 #define NOPUSH_MASK_4 0xffff
5114 #define NOPUSH_MASK_5 0xeef7
5115 #define NOPUSH_MASK_6 0xf7f6
5116 #define NOPUSH_MASK_7 0x0ecf
5117 #define NOPUSH_MASK_8 0x7f3f
5118 #define NOPUSH_MASK_9 0x0000
5119
5120 /************** End of opcodes.h *********************************************/
5121 /************** Continuing where we left off in vdbe.h ***********************/
5122
5123 /*
5124 ** Prototypes for the VDBE interface.  See comments on the implementation
5125 ** for a description of what each of these routines does.
5126 */
5127 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
5128 SQLITE_PRIVATE int sqlite3VdbeAddOp(Vdbe*,int,int,int);
5129 SQLITE_PRIVATE int sqlite3VdbeOp3(Vdbe*,int,int,int,const char *zP3,int);
5130 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
5131 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
5132 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
5133 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
5134 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
5135 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, const char *zP1, int N);
5136 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
5137 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
5138 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
5139 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
5140 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int);
5141 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
5142 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
5143 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
5144 #ifdef SQLITE_DEBUG
5145 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
5146 #endif
5147 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
5148 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
5149 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
5150 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, int);
5151 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
5152 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
5153 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n);
5154 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
5155
5156 #ifndef NDEBUG
5157 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
5158 # define VdbeComment(X)  sqlite3VdbeComment X
5159 #else
5160 # define VdbeComment(X)
5161 #endif
5162
5163 #endif
5164
5165 /************** End of vdbe.h ************************************************/
5166 /************** Continuing where we left off in sqliteInt.h ******************/
5167 /************** Include pager.h in the middle of sqliteInt.h *****************/
5168 /************** Begin file pager.h *******************************************/
5169 /*
5170 ** 2001 September 15
5171 **
5172 ** The author disclaims copyright to this source code.  In place of
5173 ** a legal notice, here is a blessing:
5174 **
5175 **    May you do good and not evil.
5176 **    May you find forgiveness for yourself and forgive others.
5177 **    May you share freely, never taking more than you give.
5178 **
5179 *************************************************************************
5180 ** This header file defines the interface that the sqlite page cache
5181 ** subsystem.  The page cache subsystem reads and writes a file a page
5182 ** at a time and provides a journal for rollback.
5183 **
5184 ** @(#) $Id: pager.h,v 1.68 2007/11/28 16:19:56 drh Exp $
5185 */
5186
5187 #ifndef _PAGER_H_
5188 #define _PAGER_H_
5189
5190 /*
5191 ** The type used to represent a page number.  The first page in a file
5192 ** is called page 1.  0 is used to represent "not a page".
5193 */
5194 typedef unsigned int Pgno;
5195
5196 /*
5197 ** Each open file is managed by a separate instance of the "Pager" structure.
5198 */
5199 typedef struct Pager Pager;
5200
5201 /*
5202 ** Handle type for pages.
5203 */
5204 typedef struct PgHdr DbPage;
5205
5206 /*
5207 ** Allowed values for the flags parameter to sqlite3PagerOpen().
5208 **
5209 ** NOTE: This values must match the corresponding BTREE_ values in btree.h.
5210 */
5211 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
5212 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
5213
5214 /*
5215 ** Valid values for the second argument to sqlite3PagerLockingMode().
5216 */
5217 #define PAGER_LOCKINGMODE_QUERY      -1
5218 #define PAGER_LOCKINGMODE_NORMAL      0
5219 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
5220
5221 /*
5222 ** See source code comments for a detailed description of the following
5223 ** routines:
5224 */
5225 SQLITE_PRIVATE int sqlite3PagerOpen(sqlite3_vfs *, Pager **ppPager, const char*, int,int,int);
5226 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, BusyHandler *pBusyHandler);
5227 SQLITE_PRIVATE void sqlite3PagerSetDestructor(Pager*, void(*)(DbPage*,int));
5228 SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager*, void(*)(DbPage*,int));
5229 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*);
5230 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
5231 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
5232 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
5233 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
5234 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
5235 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
5236 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
5237 SQLITE_PRIVATE int sqlite3PagerRef(DbPage*);
5238 SQLITE_PRIVATE int sqlite3PagerUnref(DbPage*);
5239 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
5240 SQLITE_PRIVATE int sqlite3PagerOverwrite(Pager *pPager, Pgno pgno, void*);
5241 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*);
5242 SQLITE_PRIVATE int sqlite3PagerTruncate(Pager*,Pgno);
5243 SQLITE_PRIVATE int sqlite3PagerBegin(DbPage*, int exFlag);
5244 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, Pgno);
5245 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
5246 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
5247 SQLITE_PRIVATE int sqlite3PagerIsreadonly(Pager*);
5248 SQLITE_PRIVATE int sqlite3PagerStmtBegin(Pager*);
5249 SQLITE_PRIVATE int sqlite3PagerStmtCommit(Pager*);
5250 SQLITE_PRIVATE int sqlite3PagerStmtRollback(Pager*);
5251 SQLITE_PRIVATE void sqlite3PagerDontRollback(DbPage*);
5252 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
5253 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
5254 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
5255 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
5256 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
5257 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
5258 SQLITE_PRIVATE const char *sqlite3PagerDirname(Pager*);
5259 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
5260 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
5261 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno);
5262 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
5263 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
5264 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
5265 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
5266
5267 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) && !defined(SQLITE_OMIT_DISKIO)
5268 SQLITE_PRIVATE   int sqlite3PagerReleaseMemory(int);
5269 #endif
5270
5271 #ifdef SQLITE_HAS_CODEC
5272 SQLITE_PRIVATE   void sqlite3PagerSetCodec(Pager*,void*(*)(void*,void*,Pgno,int),void*);
5273 #endif
5274
5275 #if !defined(NDEBUG) || defined(SQLITE_TEST)
5276 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
5277 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
5278 #endif
5279
5280 #ifdef SQLITE_TEST
5281 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
5282 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
5283   int pager3_refinfo_enable;
5284 #endif
5285
5286 #ifdef SQLITE_TEST
5287 void disable_simulated_io_errors(void);
5288 void enable_simulated_io_errors(void);
5289 #else
5290 # define disable_simulated_io_errors()
5291 # define enable_simulated_io_errors()
5292 #endif
5293
5294 #endif /* _PAGER_H_ */
5295
5296 /************** End of pager.h ***********************************************/
5297 /************** Continuing where we left off in sqliteInt.h ******************/
5298
5299
5300 /*
5301 ** Name of the master database table.  The master database table
5302 ** is a special table that holds the names and attributes of all
5303 ** user tables and indices.
5304 */
5305 #define MASTER_NAME       "sqlite_master"
5306 #define TEMP_MASTER_NAME  "sqlite_temp_master"
5307
5308 /*
5309 ** The root-page of the master database table.
5310 */
5311 #define MASTER_ROOT       1
5312
5313 /*
5314 ** The name of the schema table.
5315 */
5316 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
5317
5318 /*
5319 ** A convenience macro that returns the number of elements in
5320 ** an array.
5321 */
5322 #define ArraySize(X)    (sizeof(X)/sizeof(X[0]))
5323
5324 /*
5325 ** Forward references to structures
5326 */
5327 typedef struct AggInfo AggInfo;
5328 typedef struct AuthContext AuthContext;
5329 typedef struct CollSeq CollSeq;
5330 typedef struct Column Column;
5331 typedef struct Db Db;
5332 typedef struct Schema Schema;
5333 typedef struct Expr Expr;
5334 typedef struct ExprList ExprList;
5335 typedef struct FKey FKey;
5336 typedef struct FuncDef FuncDef;
5337 typedef struct IdList IdList;
5338 typedef struct Index Index;
5339 typedef struct KeyClass KeyClass;
5340 typedef struct KeyInfo KeyInfo;
5341 typedef struct Module Module;
5342 typedef struct NameContext NameContext;
5343 typedef struct Parse Parse;
5344 typedef struct Select Select;
5345 typedef struct SrcList SrcList;
5346 typedef struct StrAccum StrAccum;
5347 typedef struct Table Table;
5348 typedef struct TableLock TableLock;
5349 typedef struct Token Token;
5350 typedef struct TriggerStack TriggerStack;
5351 typedef struct TriggerStep TriggerStep;
5352 typedef struct Trigger Trigger;
5353 typedef struct WhereInfo WhereInfo;
5354 typedef struct WhereLevel WhereLevel;
5355
5356 /************** Include os.h in the middle of sqliteInt.h ********************/
5357 /************** Begin file os.h **********************************************/
5358 /*
5359 ** 2001 September 16
5360 **
5361 ** The author disclaims copyright to this source code.  In place of
5362 ** a legal notice, here is a blessing:
5363 **
5364 **    May you do good and not evil.
5365 **    May you find forgiveness for yourself and forgive others.
5366 **    May you share freely, never taking more than you give.
5367 **
5368 ******************************************************************************
5369 **
5370 ** This header file (together with is companion C source-code file
5371 ** "os.c") attempt to abstract the underlying operating system so that
5372 ** the SQLite library will work on both POSIX and windows systems.
5373 **
5374 ** This header file is #include-ed by sqliteInt.h and thus ends up
5375 ** being included by every source file.
5376 */
5377 #ifndef _SQLITE_OS_H_
5378 #define _SQLITE_OS_H_
5379
5380 /*
5381 ** Figure out if we are dealing with Unix, Windows, or some other
5382 ** operating system.  After the following block of preprocess macros,
5383 ** all of OS_UNIX, OS_WIN, OS_OS2, and OS_OTHER will defined to either
5384 ** 1 or 0.  One of the four will be 1.  The other three will be 0.
5385 */
5386 #if defined(OS_OTHER)
5387 # if OS_OTHER==1
5388 #   undef OS_UNIX
5389 #   define OS_UNIX 0
5390 #   undef OS_WIN
5391 #   define OS_WIN 0
5392 #   undef OS_OS2
5393 #   define OS_OS2 0
5394 # else
5395 #   undef OS_OTHER
5396 # endif
5397 #endif
5398 #if !defined(OS_UNIX) && !defined(OS_OTHER)
5399 # define OS_OTHER 0
5400 # ifndef OS_WIN
5401 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
5402 #     define OS_WIN 1
5403 #     define OS_UNIX 0
5404 #     define OS_OS2 0
5405 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
5406 #     define OS_WIN 0
5407 #     define OS_UNIX 0
5408 #     define OS_OS2 1
5409 #   else
5410 #     define OS_WIN 0
5411 #     define OS_UNIX 1
5412 #     define OS_OS2 0
5413 #  endif
5414 # else
5415 #  define OS_UNIX 0
5416 #  define OS_OS2 0
5417 # endif
5418 #else
5419 # ifndef OS_WIN
5420 #  define OS_WIN 0
5421 # endif
5422 #endif
5423
5424
5425
5426 /*
5427 ** Define the maximum size of a temporary filename
5428 */
5429 #if OS_WIN
5430 # include <windows.h>
5431 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
5432 #elif OS_OS2
5433 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
5434 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
5435 # endif
5436 # define INCL_DOSDATETIME
5437 # define INCL_DOSFILEMGR
5438 # define INCL_DOSERRORS
5439 # define INCL_DOSMISC
5440 # define INCL_DOSPROCESS
5441 # define INCL_DOSMODULEMGR
5442 # define INCL_DOSSEMAPHORES
5443 # include <os2.h>
5444 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
5445 #else
5446 # define SQLITE_TEMPNAME_SIZE 200
5447 #endif
5448
5449 /* If the SET_FULLSYNC macro is not defined above, then make it
5450 ** a no-op
5451 */
5452 #ifndef SET_FULLSYNC
5453 # define SET_FULLSYNC(x,y)
5454 #endif
5455
5456 /*
5457 ** The default size of a disk sector
5458 */
5459 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
5460 # define SQLITE_DEFAULT_SECTOR_SIZE 512
5461 #endif
5462
5463 /*
5464 ** Temporary files are named starting with this prefix followed by 16 random
5465 ** alphanumeric characters, and no file extension. They are stored in the
5466 ** OS's standard temporary file directory, and are deleted prior to exit.
5467 ** If sqlite is being embedded in another program, you may wish to change the
5468 ** prefix to reflect your program's name, so that if your program exits
5469 ** prematurely, old temporary files can be easily identified. This can be done
5470 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
5471 **
5472 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
5473 ** Mcafee started using SQLite in their anti-virus product and it
5474 ** started putting files with the "sqlite" name in the c:/temp folder.
5475 ** This annoyed many windows users.  Those users would then do a 
5476 ** Google search for "sqlite", find the telephone numbers of the
5477 ** developers and call to wake them up at night and complain.
5478 ** For this reason, the default name prefix is changed to be "sqlite" 
5479 ** spelled backwards.  So the temp files are still identified, but
5480 ** anybody smart enough to figure out the code is also likely smart
5481 ** enough to know that calling the developer will not help get rid
5482 ** of the file.
5483 */
5484 #ifndef SQLITE_TEMP_FILE_PREFIX
5485 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
5486 #endif
5487
5488 /*
5489 ** The following values may be passed as the second argument to
5490 ** sqlite3OsLock(). The various locks exhibit the following semantics:
5491 **
5492 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
5493 ** RESERVED:  A single process may hold a RESERVED lock on a file at
5494 **            any time. Other processes may hold and obtain new SHARED locks.
5495 ** PENDING:   A single process may hold a PENDING lock on a file at
5496 **            any one time. Existing SHARED locks may persist, but no new
5497 **            SHARED locks may be obtained by other processes.
5498 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
5499 **
5500 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
5501 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
5502 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
5503 ** sqlite3OsLock().
5504 */
5505 #define NO_LOCK         0
5506 #define SHARED_LOCK     1
5507 #define RESERVED_LOCK   2
5508 #define PENDING_LOCK    3
5509 #define EXCLUSIVE_LOCK  4
5510
5511 /*
5512 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
5513 **
5514 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
5515 ** those functions are not available.  So we use only LockFile() and
5516 ** UnlockFile().
5517 **
5518 ** LockFile() prevents not just writing but also reading by other processes.
5519 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
5520 ** byte out of a specific range of bytes. The lock byte is obtained at 
5521 ** random so two separate readers can probably access the file at the 
5522 ** same time, unless they are unlucky and choose the same lock byte.
5523 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
5524 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
5525 ** a single byte of the file that is designated as the reserved lock byte.
5526 ** A PENDING_LOCK is obtained by locking a designated byte different from
5527 ** the RESERVED_LOCK byte.
5528 **
5529 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
5530 ** which means we can use reader/writer locks.  When reader/writer locks
5531 ** are used, the lock is placed on the same range of bytes that is used
5532 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
5533 ** will support two or more Win95 readers or two or more WinNT readers.
5534 ** But a single Win95 reader will lock out all WinNT readers and a single
5535 ** WinNT reader will lock out all other Win95 readers.
5536 **
5537 ** The following #defines specify the range of bytes used for locking.
5538 ** SHARED_SIZE is the number of bytes available in the pool from which
5539 ** a random byte is selected for a shared lock.  The pool of bytes for
5540 ** shared locks begins at SHARED_FIRST. 
5541 **
5542 ** These #defines are available in sqlite_aux.h so that adaptors for
5543 ** connecting SQLite to other operating systems can use the same byte
5544 ** ranges for locking.  In particular, the same locking strategy and
5545 ** byte ranges are used for Unix.  This leaves open the possiblity of having
5546 ** clients on win95, winNT, and unix all talking to the same shared file
5547 ** and all locking correctly.  To do so would require that samba (or whatever
5548 ** tool is being used for file sharing) implements locks correctly between
5549 ** windows and unix.  I'm guessing that isn't likely to happen, but by
5550 ** using the same locking range we are at least open to the possibility.
5551 **
5552 ** Locking in windows is manditory.  For this reason, we cannot store
5553 ** actual data in the bytes used for locking.  The pager never allocates
5554 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
5555 ** that all locks will fit on a single page even at the minimum page size.
5556 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
5557 ** is set high so that we don't have to allocate an unused page except
5558 ** for very large databases.  But one should test the page skipping logic 
5559 ** by setting PENDING_BYTE low and running the entire regression suite.
5560 **
5561 ** Changing the value of PENDING_BYTE results in a subtly incompatible
5562 ** file format.  Depending on how it is changed, you might not notice
5563 ** the incompatibility right away, even running a full regression test.
5564 ** The default location of PENDING_BYTE is the first byte past the
5565 ** 1GB boundary.
5566 **
5567 */
5568 #ifndef SQLITE_TEST
5569 #define PENDING_BYTE      0x40000000  /* First byte past the 1GB boundary */
5570 #else
5571 SQLITE_API extern unsigned int sqlite3_pending_byte;
5572 #define PENDING_BYTE sqlite3_pending_byte
5573 #endif
5574
5575 #define RESERVED_BYTE     (PENDING_BYTE+1)
5576 #define SHARED_FIRST      (PENDING_BYTE+2)
5577 #define SHARED_SIZE       510
5578
5579 /* 
5580 ** Functions for accessing sqlite3_file methods 
5581 */
5582 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
5583 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
5584 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
5585 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
5586 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
5587 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
5588 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
5589 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
5590 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id);
5591 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
5592 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
5593 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
5594
5595 /* 
5596 ** Functions for accessing sqlite3_vfs methods 
5597 */
5598 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
5599 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
5600 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int);
5601 SQLITE_PRIVATE int sqlite3OsGetTempname(sqlite3_vfs *, int, char *);
5602 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
5603 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
5604 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
5605 SQLITE_PRIVATE void *sqlite3OsDlSym(sqlite3_vfs *, void *, const char *);
5606 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
5607 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
5608 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
5609 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*);
5610
5611 /*
5612 ** Convenience functions for opening and closing files using 
5613 ** sqlite3_malloc() to obtain space for the file-handle structure.
5614 */
5615 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
5616 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
5617
5618 /*
5619 ** Each OS-specific backend defines an instance of the following
5620 ** structure for returning a pointer to its sqlite3_vfs.  If OS_OTHER
5621 ** is defined (meaning that the application-defined OS interface layer
5622 ** is used) then there is no default VFS.   The application must
5623 ** register one or more VFS structures using sqlite3_vfs_register()
5624 ** before attempting to use SQLite.
5625 */
5626 #if OS_UNIX || OS_WIN || OS_OS2
5627 SQLITE_PRIVATE sqlite3_vfs *sqlite3OsDefaultVfs(void);
5628 #else
5629 # define sqlite3OsDefaultVfs(X) 0
5630 #endif
5631
5632 #endif /* _SQLITE_OS_H_ */
5633
5634 /************** End of os.h **************************************************/
5635 /************** Continuing where we left off in sqliteInt.h ******************/
5636 /************** Include mutex.h in the middle of sqliteInt.h *****************/
5637 /************** Begin file mutex.h *******************************************/
5638 /*
5639 ** 2007 August 28
5640 **
5641 ** The author disclaims copyright to this source code.  In place of
5642 ** a legal notice, here is a blessing:
5643 **
5644 **    May you do good and not evil.
5645 **    May you find forgiveness for yourself and forgive others.
5646 **    May you share freely, never taking more than you give.
5647 **
5648 *************************************************************************
5649 **
5650 ** This file contains the common header for all mutex implementations.
5651 ** The sqliteInt.h header #includes this file so that it is available
5652 ** to all source files.  We break it out in an effort to keep the code
5653 ** better organized.
5654 **
5655 ** NOTE:  source files should *not* #include this header file directly.
5656 ** Source files should #include the sqliteInt.h file and let that file
5657 ** include this one indirectly.
5658 **
5659 ** $Id: mutex.h,v 1.2 2007/08/30 14:10:30 drh Exp $
5660 */
5661
5662
5663 #ifdef SQLITE_MUTEX_APPDEF
5664 /*
5665 ** If SQLITE_MUTEX_APPDEF is defined, then this whole module is
5666 ** omitted and equivalent functionality must be provided by the
5667 ** application that links against the SQLite library.
5668 */
5669 #else
5670 /*
5671 ** Figure out what version of the code to use.  The choices are
5672 **
5673 **   SQLITE_MUTEX_NOOP         For single-threaded applications that
5674 **                             do not desire error checking.
5675 **
5676 **   SQLITE_MUTEX_NOOP_DEBUG   For single-threaded applications with
5677 **                             error checking to help verify that mutexes
5678 **                             are being used correctly even though they
5679 **                             are not needed.  Used when SQLITE_DEBUG is
5680 **                             defined on single-threaded builds.
5681 **
5682 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
5683 **
5684 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
5685 **
5686 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
5687 */
5688 #define SQLITE_MUTEX_NOOP 1   /* The default */
5689 #if defined(SQLITE_DEBUG) && !SQLITE_THREADSAFE
5690 # undef SQLITE_MUTEX_NOOP
5691 # define SQLITE_MUTEX_NOOP_DEBUG
5692 #endif
5693 #if defined(SQLITE_MUTEX_NOOP) && SQLITE_THREADSAFE && OS_UNIX
5694 # undef SQLITE_MUTEX_NOOP
5695 # define SQLITE_MUTEX_PTHREADS
5696 #endif
5697 #if defined(SQLITE_MUTEX_NOOP) && SQLITE_THREADSAFE && OS_WIN
5698 # undef SQLITE_MUTEX_NOOP
5699 # define SQLITE_MUTEX_W32
5700 #endif
5701 #if defined(SQLITE_MUTEX_NOOP) && SQLITE_THREADSAFE && OS_OS2
5702 # undef SQLITE_MUTEX_NOOP
5703 # define SQLITE_MUTEX_OS2
5704 #endif
5705
5706 #ifdef SQLITE_MUTEX_NOOP
5707 /*
5708 ** If this is a no-op implementation, implement everything as macros.
5709 */
5710 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
5711 #define sqlite3_mutex_free(X)
5712 #define sqlite3_mutex_enter(X)
5713 #define sqlite3_mutex_try(X)      SQLITE_OK
5714 #define sqlite3_mutex_leave(X)
5715 #define sqlite3_mutex_held(X)     1
5716 #define sqlite3_mutex_notheld(X)  1
5717 #endif
5718
5719 #endif /* SQLITE_MUTEX_APPDEF */
5720
5721 /************** End of mutex.h ***********************************************/
5722 /************** Continuing where we left off in sqliteInt.h ******************/
5723
5724 /*
5725 ** Each database file to be accessed by the system is an instance
5726 ** of the following structure.  There are normally two of these structures
5727 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
5728 ** aDb[1] is the database file used to hold temporary tables.  Additional
5729 ** databases may be attached.
5730 */
5731 struct Db {
5732   char *zName;         /* Name of this database */
5733   Btree *pBt;          /* The B*Tree structure for this database file */
5734   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
5735   u8 safety_level;     /* How aggressive at synching data to disk */
5736   void *pAux;               /* Auxiliary data.  Usually NULL */
5737   void (*xFreeAux)(void*);  /* Routine to free pAux */
5738   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
5739 };
5740
5741 /*
5742 ** An instance of the following structure stores a database schema.
5743 **
5744 ** If there are no virtual tables configured in this schema, the
5745 ** Schema.db variable is set to NULL. After the first virtual table
5746 ** has been added, it is set to point to the database connection 
5747 ** used to create the connection. Once a virtual table has been
5748 ** added to the Schema structure and the Schema.db variable populated, 
5749 ** only that database connection may use the Schema to prepare 
5750 ** statements.
5751 */
5752 struct Schema {
5753   int schema_cookie;   /* Database schema version number for this file */
5754   Hash tblHash;        /* All tables indexed by name */
5755   Hash idxHash;        /* All (named) indices indexed by name */
5756   Hash trigHash;       /* All triggers indexed by name */
5757   Hash aFKey;          /* Foreign keys indexed by to-table */
5758   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
5759   u8 file_format;      /* Schema format version for this file */
5760   u8 enc;              /* Text encoding used by this database */
5761   u16 flags;           /* Flags associated with this schema */
5762   int cache_size;      /* Number of pages to use in the cache */
5763 #ifndef SQLITE_OMIT_VIRTUALTABLE
5764   sqlite3 *db;         /* "Owner" connection. See comment above */
5765 #endif
5766 };
5767
5768 /*
5769 ** These macros can be used to test, set, or clear bits in the 
5770 ** Db.flags field.
5771 */
5772 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
5773 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
5774 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
5775 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
5776
5777 /*
5778 ** Allowed values for the DB.flags field.
5779 **
5780 ** The DB_SchemaLoaded flag is set after the database schema has been
5781 ** read into internal hash tables.
5782 **
5783 ** DB_UnresetViews means that one or more views have column names that
5784 ** have been filled out.  If the schema changes, these column names might
5785 ** changes and so the view will need to be reset.
5786 */
5787 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
5788 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
5789 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
5790
5791
5792 /*
5793 ** Each database is an instance of the following structure.
5794 **
5795 ** The sqlite.lastRowid records the last insert rowid generated by an
5796 ** insert statement.  Inserts on views do not affect its value.  Each
5797 ** trigger has its own context, so that lastRowid can be updated inside
5798 ** triggers as usual.  The previous value will be restored once the trigger
5799 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
5800 ** longer (since after version 2.8.12) reset to -1.
5801 **
5802 ** The sqlite.nChange does not count changes within triggers and keeps no
5803 ** context.  It is reset at start of sqlite3_exec.
5804 ** The sqlite.lsChange represents the number of changes made by the last
5805 ** insert, update, or delete statement.  It remains constant throughout the
5806 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
5807 ** context stack just like lastRowid so that the count of changes
5808 ** within a trigger is not seen outside the trigger.  Changes to views do not
5809 ** affect the value of lsChange.
5810 ** The sqlite.csChange keeps track of the number of current changes (since
5811 ** the last statement) and is used to update sqlite_lsChange.
5812 **
5813 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
5814 ** store the most recent error code and, if applicable, string. The
5815 ** internal function sqlite3Error() is used to set these variables
5816 ** consistently.
5817 */
5818 struct sqlite3 {
5819   sqlite3_vfs *pVfs;            /* OS Interface */
5820   int nDb;                      /* Number of backends currently in use */
5821   Db *aDb;                      /* All backends */
5822   int flags;                    /* Miscellanous flags. See below */
5823   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
5824   int errCode;                  /* Most recent error code (SQLITE_*) */
5825   int errMask;                  /* & result codes with this before returning */
5826   u8 autoCommit;                /* The auto-commit flag. */
5827   u8 temp_store;                /* 1: file 2: memory 0: default */
5828   u8 mallocFailed;              /* True if we have seen a malloc failure */
5829   char nextAutovac;             /* Autovac setting after VACUUM if >=0 */
5830   int nTable;                   /* Number of tables in the database */
5831   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
5832   i64 lastRowid;                /* ROWID of most recent insert (see above) */
5833   i64 priorNewRowid;            /* Last randomly generated ROWID */
5834   int magic;                    /* Magic number for detect library misuse */
5835   int nChange;                  /* Value returned by sqlite3_changes() */
5836   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
5837   sqlite3_mutex *mutex;         /* Connection mutex */
5838   struct sqlite3InitInfo {      /* Information used during initialization */
5839     int iDb;                    /* When back is being initialized */
5840     int newTnum;                /* Rootpage of table being initialized */
5841     u8 busy;                    /* TRUE if currently initializing */
5842   } init;
5843   int nExtension;               /* Number of loaded extensions */
5844   void **aExtension;            /* Array of shared libraray handles */
5845   struct Vdbe *pVdbe;           /* List of active virtual machines */
5846   int activeVdbeCnt;            /* Number of vdbes currently executing */
5847   void (*xTrace)(void*,const char*);        /* Trace function */
5848   void *pTraceArg;                          /* Argument to the trace function */
5849   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
5850   void *pProfileArg;                        /* Argument to profile function */
5851   void *pCommitArg;                 /* Argument to xCommitCallback() */   
5852   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
5853   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
5854   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
5855   void *pUpdateArg;
5856   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
5857   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
5858   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
5859   void *pCollNeededArg;
5860   sqlite3_value *pErr;          /* Most recent error message */
5861   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
5862   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
5863   union {
5864     int isInterrupted;          /* True if sqlite3_interrupt has been called */
5865     double notUsed1;            /* Spacer */
5866   } u1;
5867 #ifndef SQLITE_OMIT_AUTHORIZATION
5868   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
5869                                 /* Access authorization function */
5870   void *pAuthArg;               /* 1st argument to the access auth function */
5871 #endif
5872 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
5873   int (*xProgress)(void *);     /* The progress callback */
5874   void *pProgressArg;           /* Argument to the progress callback */
5875   int nProgressOps;             /* Number of opcodes for progress callback */
5876 #endif
5877 #ifndef SQLITE_OMIT_VIRTUALTABLE
5878   Hash aModule;                 /* populated by sqlite3_create_module() */
5879   Table *pVTab;                 /* vtab with active Connect/Create method */
5880   sqlite3_vtab **aVTrans;       /* Virtual tables with open transactions */
5881   int nVTrans;                  /* Allocated size of aVTrans */
5882 #endif
5883   Hash aFunc;                   /* All functions that can be in SQL exprs */
5884   Hash aCollSeq;                /* All collating sequences */
5885   BusyHandler busyHandler;      /* Busy callback */
5886   int busyTimeout;              /* Busy handler timeout, in msec */
5887   Db aDbStatic[2];              /* Static space for the 2 default backends */
5888 #ifdef SQLITE_SSE
5889   sqlite3_stmt *pFetch;         /* Used by SSE to fetch stored statements */
5890 #endif
5891   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
5892 };
5893
5894 /*
5895 ** A macro to discover the encoding of a database.
5896 */
5897 #define ENC(db) ((db)->aDb[0].pSchema->enc)
5898
5899 /*
5900 ** Possible values for the sqlite.flags and or Db.flags fields.
5901 **
5902 ** On sqlite.flags, the SQLITE_InTrans value means that we have
5903 ** executed a BEGIN.  On Db.flags, SQLITE_InTrans means a statement
5904 ** transaction is active on that particular database file.
5905 */
5906 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
5907 #define SQLITE_InTrans        0x00000008  /* True if in a transaction */
5908 #define SQLITE_InternChanges  0x00000010  /* Uncommitted Hash table changes */
5909 #define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
5910 #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
5911 #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
5912                                           /*   DELETE, or UPDATE and return */
5913                                           /*   the count using a callback. */
5914 #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
5915                                           /*   result set is empty */
5916 #define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
5917 #define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
5918 #define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
5919 #define SQLITE_NoReadlock     0x00001000  /* Readlocks are omitted when 
5920                                           ** accessing read-only databases */
5921 #define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
5922 #define SQLITE_ReadUncommitted 0x00004000 /* For shared-cache mode */
5923 #define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
5924 #define SQLITE_FullFSync      0x00010000  /* Use full fsync on the backend */
5925 #define SQLITE_LoadExtension  0x00020000  /* Enable load_extension */
5926
5927 #define SQLITE_RecoveryMode   0x00040000  /* Ignore schema errors */
5928 #define SQLITE_SharedCache    0x00080000  /* Cache sharing is enabled */
5929 #define SQLITE_Vtab           0x00100000  /* There exists a virtual table */
5930
5931 /*
5932 ** Possible values for the sqlite.magic field.
5933 ** The numbers are obtained at random and have no special meaning, other
5934 ** than being distinct from one another.
5935 */
5936 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
5937 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
5938 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
5939 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
5940
5941 /*
5942 ** Each SQL function is defined by an instance of the following
5943 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
5944 ** hash table.  When multiple functions have the same name, the hash table
5945 ** points to a linked list of these structures.
5946 */
5947 struct FuncDef {
5948   i16 nArg;            /* Number of arguments.  -1 means unlimited */
5949   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
5950   u8 needCollSeq;      /* True if sqlite3GetFuncCollSeq() might be called */
5951   u8 flags;            /* Some combination of SQLITE_FUNC_* */
5952   void *pUserData;     /* User data parameter */
5953   FuncDef *pNext;      /* Next function with same name */
5954   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
5955   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
5956   void (*xFinalize)(sqlite3_context*);                /* Aggregate finializer */
5957   char zName[1];       /* SQL name of the function.  MUST BE LAST */
5958 };
5959
5960 /*
5961 ** Each SQLite module (virtual table definition) is defined by an
5962 ** instance of the following structure, stored in the sqlite3.aModule
5963 ** hash table.
5964 */
5965 struct Module {
5966   const sqlite3_module *pModule;       /* Callback pointers */
5967   const char *zName;                   /* Name passed to create_module() */
5968   void *pAux;                          /* pAux passed to create_module() */
5969   void (*xDestroy)(void *);            /* Module destructor function */
5970 };
5971
5972 /*
5973 ** Possible values for FuncDef.flags
5974 */
5975 #define SQLITE_FUNC_LIKE   0x01  /* Candidate for the LIKE optimization */
5976 #define SQLITE_FUNC_CASE   0x02  /* Case-sensitive LIKE-type function */
5977 #define SQLITE_FUNC_EPHEM  0x04  /* Ephermeral.  Delete with VDBE */
5978
5979 /*
5980 ** information about each column of an SQL table is held in an instance
5981 ** of this structure.
5982 */
5983 struct Column {
5984   char *zName;     /* Name of this column */
5985   Expr *pDflt;     /* Default value of this column */
5986   char *zType;     /* Data type for this column */
5987   char *zColl;     /* Collating sequence.  If NULL, use the default */
5988   u8 notNull;      /* True if there is a NOT NULL constraint */
5989   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
5990   char affinity;   /* One of the SQLITE_AFF_... values */
5991 #ifndef SQLITE_OMIT_VIRTUALTABLE
5992   u8 isHidden;     /* True if this column is 'hidden' */
5993 #endif
5994 };
5995
5996 /*
5997 ** A "Collating Sequence" is defined by an instance of the following
5998 ** structure. Conceptually, a collating sequence consists of a name and
5999 ** a comparison routine that defines the order of that sequence.
6000 **
6001 ** There may two seperate implementations of the collation function, one
6002 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
6003 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
6004 ** native byte order. When a collation sequence is invoked, SQLite selects
6005 ** the version that will require the least expensive encoding
6006 ** translations, if any.
6007 **
6008 ** The CollSeq.pUser member variable is an extra parameter that passed in
6009 ** as the first argument to the UTF-8 comparison function, xCmp.
6010 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
6011 ** xCmp16.
6012 **
6013 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
6014 ** collating sequence is undefined.  Indices built on an undefined
6015 ** collating sequence may not be read or written.
6016 */
6017 struct CollSeq {
6018   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
6019   u8 enc;               /* Text encoding handled by xCmp() */
6020   u8 type;              /* One of the SQLITE_COLL_... values below */
6021   void *pUser;          /* First argument to xCmp() */
6022   int (*xCmp)(void*,int, const void*, int, const void*);
6023   void (*xDel)(void*);  /* Destructor for pUser */
6024 };
6025
6026 /*
6027 ** Allowed values of CollSeq flags:
6028 */
6029 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
6030 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
6031 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
6032 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
6033
6034 /*
6035 ** A sort order can be either ASC or DESC.
6036 */
6037 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
6038 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
6039
6040 /*
6041 ** Column affinity types.
6042 **
6043 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
6044 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
6045 ** the speed a little by number the values consecutively.  
6046 **
6047 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
6048 ** when multiple affinity types are concatenated into a string and
6049 ** used as the P3 operand, they will be more readable.
6050 **
6051 ** Note also that the numeric types are grouped together so that testing
6052 ** for a numeric type is a single comparison.
6053 */
6054 #define SQLITE_AFF_TEXT     'a'
6055 #define SQLITE_AFF_NONE     'b'
6056 #define SQLITE_AFF_NUMERIC  'c'
6057 #define SQLITE_AFF_INTEGER  'd'
6058 #define SQLITE_AFF_REAL     'e'
6059
6060 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
6061
6062 /*
6063 ** Each SQL table is represented in memory by an instance of the
6064 ** following structure.
6065 **
6066 ** Table.zName is the name of the table.  The case of the original
6067 ** CREATE TABLE statement is stored, but case is not significant for
6068 ** comparisons.
6069 **
6070 ** Table.nCol is the number of columns in this table.  Table.aCol is a
6071 ** pointer to an array of Column structures, one for each column.
6072 **
6073 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
6074 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
6075 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
6076 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
6077 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
6078 ** is generated for each row of the table.  Table.hasPrimKey is true if
6079 ** the table has any PRIMARY KEY, INTEGER or otherwise.
6080 **
6081 ** Table.tnum is the page number for the root BTree page of the table in the
6082 ** database file.  If Table.iDb is the index of the database table backend
6083 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
6084 ** holds temporary tables and indices.  If Table.isEphem
6085 ** is true, then the table is stored in a file that is automatically deleted
6086 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
6087 ** refers VDBE cursor number that holds the table open, not to the root
6088 ** page number.  Transient tables are used to hold the results of a
6089 ** sub-query that appears instead of a real table name in the FROM clause 
6090 ** of a SELECT statement.
6091 */
6092 struct Table {
6093   char *zName;     /* Name of the table */
6094   int nCol;        /* Number of columns in this table */
6095   Column *aCol;    /* Information about each column */
6096   int iPKey;       /* If not less then 0, use aCol[iPKey] as the primary key */
6097   Index *pIndex;   /* List of SQL indexes on this table. */
6098   int tnum;        /* Root BTree node for this table (see note above) */
6099   Select *pSelect; /* NULL for tables.  Points to definition if a view. */
6100   int nRef;          /* Number of pointers to this Table */
6101   Trigger *pTrigger; /* List of SQL triggers on this table */
6102   FKey *pFKey;       /* Linked list of all foreign keys in this table */
6103   char *zColAff;     /* String defining the affinity of each column */
6104 #ifndef SQLITE_OMIT_CHECK
6105   Expr *pCheck;      /* The AND of all CHECK constraints */
6106 #endif
6107 #ifndef SQLITE_OMIT_ALTERTABLE
6108   int addColOffset;  /* Offset in CREATE TABLE statement to add a new column */
6109 #endif
6110   u8 readOnly;     /* True if this table should not be written by the user */
6111   u8 isEphem;      /* True if created using OP_OpenEphermeral */
6112   u8 hasPrimKey;   /* True if there exists a primary key */
6113   u8 keyConf;      /* What to do in case of uniqueness conflict on iPKey */
6114   u8 autoInc;      /* True if the integer primary key is autoincrement */
6115 #ifndef SQLITE_OMIT_VIRTUALTABLE
6116   u8 isVirtual;             /* True if this is a virtual table */
6117   u8 isCommit;              /* True once the CREATE TABLE has been committed */
6118   Module *pMod;             /* Pointer to the implementation of the module */
6119   sqlite3_vtab *pVtab;      /* Pointer to the module instance */
6120   int nModuleArg;           /* Number of arguments to the module */
6121   char **azModuleArg;       /* Text of all module args. [0] is module name */
6122 #endif
6123   Schema *pSchema;          /* Schema that contains this table */
6124 };
6125
6126 /*
6127 ** Test to see whether or not a table is a virtual table.  This is
6128 ** done as a macro so that it will be optimized out when virtual
6129 ** table support is omitted from the build.
6130 */
6131 #ifndef SQLITE_OMIT_VIRTUALTABLE
6132 #  define IsVirtual(X)      ((X)->isVirtual)
6133 #  define IsHiddenColumn(X) ((X)->isHidden)
6134 #else
6135 #  define IsVirtual(X)      0
6136 #  define IsHiddenColumn(X) 0
6137 #endif
6138
6139 /*
6140 ** Each foreign key constraint is an instance of the following structure.
6141 **
6142 ** A foreign key is associated with two tables.  The "from" table is
6143 ** the table that contains the REFERENCES clause that creates the foreign
6144 ** key.  The "to" table is the table that is named in the REFERENCES clause.
6145 ** Consider this example:
6146 **
6147 **     CREATE TABLE ex1(
6148 **       a INTEGER PRIMARY KEY,
6149 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
6150 **     );
6151 **
6152 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
6153 **
6154 ** Each REFERENCES clause generates an instance of the following structure
6155 ** which is attached to the from-table.  The to-table need not exist when
6156 ** the from-table is created.  The existance of the to-table is not checked
6157 ** until an attempt is made to insert data into the from-table.
6158 **
6159 ** The sqlite.aFKey hash table stores pointers to this structure
6160 ** given the name of a to-table.  For each to-table, all foreign keys
6161 ** associated with that table are on a linked list using the FKey.pNextTo
6162 ** field.
6163 */
6164 struct FKey {
6165   Table *pFrom;     /* The table that constains the REFERENCES clause */
6166   FKey *pNextFrom;  /* Next foreign key in pFrom */
6167   char *zTo;        /* Name of table that the key points to */
6168   FKey *pNextTo;    /* Next foreign key that points to zTo */
6169   int nCol;         /* Number of columns in this key */
6170   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
6171     int iFrom;         /* Index of column in pFrom */
6172     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
6173   } *aCol;          /* One entry for each of nCol column s */
6174   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
6175   u8 updateConf;    /* How to resolve conflicts that occur on UPDATE */
6176   u8 deleteConf;    /* How to resolve conflicts that occur on DELETE */
6177   u8 insertConf;    /* How to resolve conflicts that occur on INSERT */
6178 };
6179
6180 /*
6181 ** SQLite supports many different ways to resolve a constraint
6182 ** error.  ROLLBACK processing means that a constraint violation
6183 ** causes the operation in process to fail and for the current transaction
6184 ** to be rolled back.  ABORT processing means the operation in process
6185 ** fails and any prior changes from that one operation are backed out,
6186 ** but the transaction is not rolled back.  FAIL processing means that
6187 ** the operation in progress stops and returns an error code.  But prior
6188 ** changes due to the same operation are not backed out and no rollback
6189 ** occurs.  IGNORE means that the particular row that caused the constraint
6190 ** error is not inserted or updated.  Processing continues and no error
6191 ** is returned.  REPLACE means that preexisting database rows that caused
6192 ** a UNIQUE constraint violation are removed so that the new insert or
6193 ** update can proceed.  Processing continues and no error is reported.
6194 **
6195 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
6196 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
6197 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
6198 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
6199 ** referenced table row is propagated into the row that holds the
6200 ** foreign key.
6201 ** 
6202 ** The following symbolic values are used to record which type
6203 ** of action to take.
6204 */
6205 #define OE_None     0   /* There is no constraint to check */
6206 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
6207 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
6208 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
6209 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
6210 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
6211
6212 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
6213 #define OE_SetNull  7   /* Set the foreign key value to NULL */
6214 #define OE_SetDflt  8   /* Set the foreign key value to its default */
6215 #define OE_Cascade  9   /* Cascade the changes */
6216
6217 #define OE_Default  99  /* Do whatever the default action is */
6218
6219
6220 /*
6221 ** An instance of the following structure is passed as the first
6222 ** argument to sqlite3VdbeKeyCompare and is used to control the 
6223 ** comparison of the two index keys.
6224 **
6225 ** If the KeyInfo.incrKey value is true and the comparison would
6226 ** otherwise be equal, then return a result as if the second key
6227 ** were larger.
6228 */
6229 struct KeyInfo {
6230   sqlite3 *db;        /* The database connection */
6231   u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
6232   u8 incrKey;         /* Increase 2nd key by epsilon before comparison */
6233   u8 prefixIsEqual;   /* Treat a prefix as equal */
6234   int nField;         /* Number of entries in aColl[] */
6235   u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
6236   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
6237 };
6238
6239 /*
6240 ** Each SQL index is represented in memory by an
6241 ** instance of the following structure.
6242 **
6243 ** The columns of the table that are to be indexed are described
6244 ** by the aiColumn[] field of this structure.  For example, suppose
6245 ** we have the following table and index:
6246 **
6247 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
6248 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
6249 **
6250 ** In the Table structure describing Ex1, nCol==3 because there are
6251 ** three columns in the table.  In the Index structure describing
6252 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
6253 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
6254 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
6255 ** The second column to be indexed (c1) has an index of 0 in
6256 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
6257 **
6258 ** The Index.onError field determines whether or not the indexed columns
6259 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
6260 ** it means this is not a unique index.  Otherwise it is a unique index
6261 ** and the value of Index.onError indicate the which conflict resolution 
6262 ** algorithm to employ whenever an attempt is made to insert a non-unique
6263 ** element.
6264 */
6265 struct Index {
6266   char *zName;     /* Name of this index */
6267   int nColumn;     /* Number of columns in the table used by this index */
6268   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
6269   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
6270   Table *pTable;   /* The SQL table being indexed */
6271   int tnum;        /* Page containing root of this index in database file */
6272   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
6273   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
6274   char *zColAff;   /* String defining the affinity of each column */
6275   Index *pNext;    /* The next index associated with the same table */
6276   Schema *pSchema; /* Schema containing this index */
6277   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
6278   char **azColl;   /* Array of collation sequence names for index */
6279 };
6280
6281 /*
6282 ** Each token coming out of the lexer is an instance of
6283 ** this structure.  Tokens are also used as part of an expression.
6284 **
6285 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
6286 ** may contain random values.  Do not make any assuptions about Token.dyn
6287 ** and Token.n when Token.z==0.
6288 */
6289 struct Token {
6290   const unsigned char *z; /* Text of the token.  Not NULL-terminated! */
6291   unsigned dyn  : 1;      /* True for malloced memory, false for static */
6292   unsigned n    : 31;     /* Number of characters in this token */
6293 };
6294
6295 /*
6296 ** An instance of this structure contains information needed to generate
6297 ** code for a SELECT that contains aggregate functions.
6298 **
6299 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
6300 ** pointer to this structure.  The Expr.iColumn field is the index in
6301 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
6302 ** code for that node.
6303 **
6304 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
6305 ** original Select structure that describes the SELECT statement.  These
6306 ** fields do not need to be freed when deallocating the AggInfo structure.
6307 */
6308 struct AggInfo {
6309   u8 directMode;          /* Direct rendering mode means take data directly
6310                           ** from source tables rather than from accumulators */
6311   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
6312                           ** than the source table */
6313   int sortingIdx;         /* Cursor number of the sorting index */
6314   ExprList *pGroupBy;     /* The group by clause */
6315   int nSortingColumn;     /* Number of columns in the sorting index */
6316   struct AggInfo_col {    /* For each column used in source tables */
6317     Table *pTab;             /* Source table */
6318     int iTable;              /* Cursor number of the source table */
6319     int iColumn;             /* Column number within the source table */
6320     int iSorterColumn;       /* Column number in the sorting index */
6321     int iMem;                /* Memory location that acts as accumulator */
6322     Expr *pExpr;             /* The original expression */
6323   } *aCol;
6324   int nColumn;            /* Number of used entries in aCol[] */
6325   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
6326   int nAccumulator;       /* Number of columns that show through to the output.
6327                           ** Additional columns are used only as parameters to
6328                           ** aggregate functions */
6329   struct AggInfo_func {   /* For each aggregate function */
6330     Expr *pExpr;             /* Expression encoding the function */
6331     FuncDef *pFunc;          /* The aggregate function implementation */
6332     int iMem;                /* Memory location that acts as accumulator */
6333     int iDistinct;           /* Ephermeral table used to enforce DISTINCT */
6334   } *aFunc;
6335   int nFunc;              /* Number of entries in aFunc[] */
6336   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
6337 };
6338
6339 /*
6340 ** Each node of an expression in the parse tree is an instance
6341 ** of this structure.
6342 **
6343 ** Expr.op is the opcode.  The integer parser token codes are reused
6344 ** as opcodes here.  For example, the parser defines TK_GE to be an integer
6345 ** code representing the ">=" operator.  This same integer code is reused
6346 ** to represent the greater-than-or-equal-to operator in the expression
6347 ** tree.
6348 **
6349 ** Expr.pRight and Expr.pLeft are subexpressions.  Expr.pList is a list
6350 ** of argument if the expression is a function.
6351 **
6352 ** Expr.token is the operator token for this node.  For some expressions
6353 ** that have subexpressions, Expr.token can be the complete text that gave
6354 ** rise to the Expr.  In the latter case, the token is marked as being
6355 ** a compound token.
6356 **
6357 ** An expression of the form ID or ID.ID refers to a column in a table.
6358 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
6359 ** the integer cursor number of a VDBE cursor pointing to that table and
6360 ** Expr.iColumn is the column number for the specific column.  If the
6361 ** expression is used as a result in an aggregate SELECT, then the
6362 ** value is also stored in the Expr.iAgg column in the aggregate so that
6363 ** it can be accessed after all aggregates are computed.
6364 **
6365 ** If the expression is a function, the Expr.iTable is an integer code
6366 ** representing which function.  If the expression is an unbound variable
6367 ** marker (a question mark character '?' in the original SQL) then the
6368 ** Expr.iTable holds the index number for that variable.
6369 **
6370 ** If the expression is a subquery then Expr.iColumn holds an integer
6371 ** register number containing the result of the subquery.  If the
6372 ** subquery gives a constant result, then iTable is -1.  If the subquery
6373 ** gives a different answer at different times during statement processing
6374 ** then iTable is the address of a subroutine that computes the subquery.
6375 **
6376 ** The Expr.pSelect field points to a SELECT statement.  The SELECT might
6377 ** be the right operand of an IN operator.  Or, if a scalar SELECT appears
6378 ** in an expression the opcode is TK_SELECT and Expr.pSelect is the only
6379 ** operand.
6380 **
6381 ** If the Expr is of type OP_Column, and the table it is selecting from
6382 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
6383 ** corresponding table definition.
6384 */
6385 struct Expr {
6386   u8 op;                 /* Operation performed by this node */
6387   char affinity;         /* The affinity of the column or 0 if not a column */
6388   u16 flags;             /* Various flags.  See below */
6389   CollSeq *pColl;        /* The collation type of the column or 0 */
6390   Expr *pLeft, *pRight;  /* Left and right subnodes */
6391   ExprList *pList;       /* A list of expressions used as function arguments
6392                          ** or in "<expr> IN (<expr-list)" */
6393   Token token;           /* An operand token */
6394   Token span;            /* Complete text of the expression */
6395   int iTable, iColumn;   /* When op==TK_COLUMN, then this expr node means the
6396                          ** iColumn-th field of the iTable-th table. */
6397   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
6398   int iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
6399   int iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
6400   Select *pSelect;       /* When the expression is a sub-select.  Also the
6401                          ** right side of "<expr> IN (<select>)" */
6402   Table *pTab;           /* Table for OP_Column expressions. */
6403 /*  Schema *pSchema; */
6404 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
6405   int nHeight;           /* Height of the tree headed by this node */
6406 #endif
6407 };
6408
6409 /*
6410 ** The following are the meanings of bits in the Expr.flags field.
6411 */
6412 #define EP_FromJoin     0x01  /* Originated in ON or USING clause of a join */
6413 #define EP_Agg          0x02  /* Contains one or more aggregate functions */
6414 #define EP_Resolved     0x04  /* IDs have been resolved to COLUMNs */
6415 #define EP_Error        0x08  /* Expression contains one or more errors */
6416 #define EP_Distinct     0x10  /* Aggregate function with DISTINCT keyword */
6417 #define EP_VarSelect    0x20  /* pSelect is correlated, not constant */
6418 #define EP_Dequoted     0x40  /* True if the string has been dequoted */
6419 #define EP_InfixFunc    0x80  /* True for an infix function: LIKE, GLOB, etc */
6420 #define EP_ExpCollate  0x100  /* Collating sequence specified explicitly */
6421
6422 /*
6423 ** These macros can be used to test, set, or clear bits in the 
6424 ** Expr.flags field.
6425 */
6426 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
6427 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
6428 #define ExprSetProperty(E,P)     (E)->flags|=(P)
6429 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
6430
6431 /*
6432 ** A list of expressions.  Each expression may optionally have a
6433 ** name.  An expr/name combination can be used in several ways, such
6434 ** as the list of "expr AS ID" fields following a "SELECT" or in the
6435 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
6436 ** also be used as the argument to a function, in which case the a.zName
6437 ** field is not used.
6438 */
6439 struct ExprList {
6440   int nExpr;             /* Number of expressions on the list */
6441   int nAlloc;            /* Number of entries allocated below */
6442   int iECursor;          /* VDBE Cursor associated with this ExprList */
6443   struct ExprList_item {
6444     Expr *pExpr;           /* The list of expressions */
6445     char *zName;           /* Token associated with this expression */
6446     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
6447     u8 isAgg;              /* True if this is an aggregate like count(*) */
6448     u8 done;               /* A flag to indicate when processing is finished */
6449   } *a;                  /* One entry for each expression */
6450 };
6451
6452 /*
6453 ** An instance of this structure can hold a simple list of identifiers,
6454 ** such as the list "a,b,c" in the following statements:
6455 **
6456 **      INSERT INTO t(a,b,c) VALUES ...;
6457 **      CREATE INDEX idx ON t(a,b,c);
6458 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
6459 **
6460 ** The IdList.a.idx field is used when the IdList represents the list of
6461 ** column names after a table name in an INSERT statement.  In the statement
6462 **
6463 **     INSERT INTO t(a,b,c) ...
6464 **
6465 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
6466 */
6467 struct IdList {
6468   struct IdList_item {
6469     char *zName;      /* Name of the identifier */
6470     int idx;          /* Index in some Table.aCol[] of a column named zName */
6471   } *a;
6472   int nId;         /* Number of identifiers on the list */
6473   int nAlloc;      /* Number of entries allocated for a[] below */
6474 };
6475
6476 /*
6477 ** The bitmask datatype defined below is used for various optimizations.
6478 **
6479 ** Changing this from a 64-bit to a 32-bit type limits the number of
6480 ** tables in a join to 32 instead of 64.  But it also reduces the size
6481 ** of the library by 738 bytes on ix86.
6482 */
6483 typedef u64 Bitmask;
6484
6485 /*
6486 ** The following structure describes the FROM clause of a SELECT statement.
6487 ** Each table or subquery in the FROM clause is a separate element of
6488 ** the SrcList.a[] array.
6489 **
6490 ** With the addition of multiple database support, the following structure
6491 ** can also be used to describe a particular table such as the table that
6492 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
6493 ** such a table must be a simple name: ID.  But in SQLite, the table can
6494 ** now be identified by a database name, a dot, then the table name: ID.ID.
6495 **
6496 ** The jointype starts out showing the join type between the current table
6497 ** and the next table on the list.  The parser builds the list this way.
6498 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
6499 ** jointype expresses the join between the table and the previous table.
6500 */
6501 struct SrcList {
6502   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
6503   i16 nAlloc;      /* Number of entries allocated in a[] below */
6504   struct SrcList_item {
6505     char *zDatabase;  /* Name of database holding this table */
6506     char *zName;      /* Name of the table */
6507     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
6508     Table *pTab;      /* An SQL table corresponding to zName */
6509     Select *pSelect;  /* A SELECT statement used in place of a table name */
6510     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
6511     u8 jointype;      /* Type of join between this able and the previous */
6512     int iCursor;      /* The VDBE cursor number used to access this table */
6513     Expr *pOn;        /* The ON clause of a join */
6514     IdList *pUsing;   /* The USING clause of a join */
6515     Bitmask colUsed;  /* Bit N (1<<N) set if column N or pTab is used */
6516   } a[1];             /* One entry for each identifier on the list */
6517 };
6518
6519 /*
6520 ** Permitted values of the SrcList.a.jointype field
6521 */
6522 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
6523 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
6524 #define JT_NATURAL   0x0004    /* True for a "natural" join */
6525 #define JT_LEFT      0x0008    /* Left outer join */
6526 #define JT_RIGHT     0x0010    /* Right outer join */
6527 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
6528 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
6529
6530 /*
6531 ** For each nested loop in a WHERE clause implementation, the WhereInfo
6532 ** structure contains a single instance of this structure.  This structure
6533 ** is intended to be private the the where.c module and should not be
6534 ** access or modified by other modules.
6535 **
6536 ** The pIdxInfo and pBestIdx fields are used to help pick the best
6537 ** index on a virtual table.  The pIdxInfo pointer contains indexing
6538 ** information for the i-th table in the FROM clause before reordering.
6539 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
6540 ** The pBestIdx pointer is a copy of pIdxInfo for the i-th table after
6541 ** FROM clause ordering.  This is a little confusing so I will repeat
6542 ** it in different words.  WhereInfo.a[i].pIdxInfo is index information 
6543 ** for WhereInfo.pTabList.a[i].  WhereInfo.a[i].pBestInfo is the
6544 ** index information for the i-th loop of the join.  pBestInfo is always
6545 ** either NULL or a copy of some pIdxInfo.  So for cleanup it is 
6546 ** sufficient to free all of the pIdxInfo pointers.
6547 ** 
6548 */
6549 struct WhereLevel {
6550   int iFrom;            /* Which entry in the FROM clause */
6551   int flags;            /* Flags associated with this level */
6552   int iMem;             /* First memory cell used by this level */
6553   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
6554   Index *pIdx;          /* Index used.  NULL if no index */
6555   int iTabCur;          /* The VDBE cursor used to access the table */
6556   int iIdxCur;          /* The VDBE cursor used to acesss pIdx */
6557   int brk;              /* Jump here to break out of the loop */
6558   int nxt;              /* Jump here to start the next IN combination */
6559   int cont;             /* Jump here to continue with the next loop cycle */
6560   int top;              /* First instruction of interior of the loop */
6561   int op, p1, p2;       /* Opcode used to terminate the loop */
6562   int nEq;              /* Number of == or IN constraints on this loop */
6563   int nIn;              /* Number of IN operators constraining this loop */
6564   struct InLoop {
6565     int iCur;              /* The VDBE cursor used by this IN operator */
6566     int topAddr;           /* Top of the IN loop */
6567   } *aInLoop;           /* Information about each nested IN operator */
6568   sqlite3_index_info *pBestIdx;  /* Index information for this level */
6569
6570   /* The following field is really not part of the current level.  But
6571   ** we need a place to cache index information for each table in the
6572   ** FROM clause and the WhereLevel structure is a convenient place.
6573   */
6574   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
6575 };
6576
6577 /*
6578 ** The WHERE clause processing routine has two halves.  The
6579 ** first part does the start of the WHERE loop and the second
6580 ** half does the tail of the WHERE loop.  An instance of
6581 ** this structure is returned by the first half and passed
6582 ** into the second half to give some continuity.
6583 */
6584 struct WhereInfo {
6585   Parse *pParse;
6586   SrcList *pTabList;   /* List of tables in the join */
6587   int iTop;            /* The very beginning of the WHERE loop */
6588   int iContinue;       /* Jump here to continue with next record */
6589   int iBreak;          /* Jump here to break out of the loop */
6590   int nLevel;          /* Number of nested loop */
6591   sqlite3_index_info **apInfo;  /* Array of pointers to index info structures */
6592   WhereLevel a[1];     /* Information about each nest loop in the WHERE */
6593 };
6594
6595 /*
6596 ** A NameContext defines a context in which to resolve table and column
6597 ** names.  The context consists of a list of tables (the pSrcList) field and
6598 ** a list of named expression (pEList).  The named expression list may
6599 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
6600 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
6601 ** pEList corresponds to the result set of a SELECT and is NULL for
6602 ** other statements.
6603 **
6604 ** NameContexts can be nested.  When resolving names, the inner-most 
6605 ** context is searched first.  If no match is found, the next outer
6606 ** context is checked.  If there is still no match, the next context
6607 ** is checked.  This process continues until either a match is found
6608 ** or all contexts are check.  When a match is found, the nRef member of
6609 ** the context containing the match is incremented. 
6610 **
6611 ** Each subquery gets a new NameContext.  The pNext field points to the
6612 ** NameContext in the parent query.  Thus the process of scanning the
6613 ** NameContext list corresponds to searching through successively outer
6614 ** subqueries looking for a match.
6615 */
6616 struct NameContext {
6617   Parse *pParse;       /* The parser */
6618   SrcList *pSrcList;   /* One or more tables used to resolve names */
6619   ExprList *pEList;    /* Optional list of named expressions */
6620   int nRef;            /* Number of names resolved by this context */
6621   int nErr;            /* Number of errors encountered while resolving names */
6622   u8 allowAgg;         /* Aggregate functions allowed here */
6623   u8 hasAgg;           /* True if aggregates are seen */
6624   u8 isCheck;          /* True if resolving names in a CHECK constraint */
6625   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
6626   AggInfo *pAggInfo;   /* Information about aggregates at this level */
6627   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
6628 };
6629
6630 /*
6631 ** An instance of the following structure contains all information
6632 ** needed to generate code for a single SELECT statement.
6633 **
6634 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
6635 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
6636 ** limit and nOffset to the value of the offset (or 0 if there is not
6637 ** offset).  But later on, nLimit and nOffset become the memory locations
6638 ** in the VDBE that record the limit and offset counters.
6639 **
6640 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
6641 ** These addresses must be stored so that we can go back and fill in
6642 ** the P3_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
6643 ** the number of columns in P2 can be computed at the same time
6644 ** as the OP_OpenEphm instruction is coded because not
6645 ** enough information about the compound query is known at that point.
6646 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
6647 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
6648 ** sequences for the ORDER BY clause.
6649 */
6650 struct Select {
6651   ExprList *pEList;      /* The fields of the result */
6652   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
6653   u8 isDistinct;         /* True if the DISTINCT keyword is present */
6654   u8 isResolved;         /* True once sqlite3SelectResolve() has run. */
6655   u8 isAgg;              /* True if this is an aggregate query */
6656   u8 usesEphm;           /* True if uses an OpenEphemeral opcode */
6657   u8 disallowOrderBy;    /* Do not allow an ORDER BY to be attached if TRUE */
6658   char affinity;         /* MakeRecord with this affinity for SRT_Set */
6659   SrcList *pSrc;         /* The FROM clause */
6660   Expr *pWhere;          /* The WHERE clause */
6661   ExprList *pGroupBy;    /* The GROUP BY clause */
6662   Expr *pHaving;         /* The HAVING clause */
6663   ExprList *pOrderBy;    /* The ORDER BY clause */
6664   Select *pPrior;        /* Prior select in a compound select statement */
6665   Select *pNext;         /* Next select to the left in a compound */
6666   Select *pRightmost;    /* Right-most select in a compound select statement */
6667   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
6668   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
6669   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
6670   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
6671 };
6672
6673 /*
6674 ** The results of a select can be distributed in several ways.
6675 */
6676 #define SRT_Union        1  /* Store result as keys in an index */
6677 #define SRT_Except       2  /* Remove result from a UNION index */
6678 #define SRT_Discard      3  /* Do not save the results anywhere */
6679
6680 /* The ORDER BY clause is ignored for all of the above */
6681 #define IgnorableOrderby(X) (X<=SRT_Discard)
6682
6683 #define SRT_Callback     4  /* Invoke a callback with each row of result */
6684 #define SRT_Mem          5  /* Store result in a memory cell */
6685 #define SRT_Set          6  /* Store non-null results as keys in an index */
6686 #define SRT_Table        7  /* Store result as data with an automatic rowid */
6687 #define SRT_EphemTab     8  /* Create transient tab and store like SRT_Table */
6688 #define SRT_Subroutine   9  /* Call a subroutine to handle results */
6689 #define SRT_Exists      10  /* Store 1 if the result is not empty */
6690
6691 /*
6692 ** An SQL parser context.  A copy of this structure is passed through
6693 ** the parser and down into all the parser action routine in order to
6694 ** carry around information that is global to the entire parse.
6695 **
6696 ** The structure is divided into two parts.  When the parser and code
6697 ** generate call themselves recursively, the first part of the structure
6698 ** is constant but the second part is reset at the beginning and end of
6699 ** each recursion.
6700 **
6701 ** The nTableLock and aTableLock variables are only used if the shared-cache 
6702 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
6703 ** used to store the set of table-locks required by the statement being
6704 ** compiled. Function sqlite3TableLock() is used to add entries to the
6705 ** list.
6706 */
6707 struct Parse {
6708   sqlite3 *db;         /* The main database structure */
6709   int rc;              /* Return code from execution */
6710   char *zErrMsg;       /* An error message */
6711   Vdbe *pVdbe;         /* An engine for executing database bytecode */
6712   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
6713   u8 nameClash;        /* A permanent table name clashes with temp table name */
6714   u8 checkSchema;      /* Causes schema cookie check after an error */
6715   u8 nested;           /* Number of nested calls to the parser/code generator */
6716   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
6717   int nErr;            /* Number of errors seen */
6718   int nTab;            /* Number of previously allocated VDBE cursors */
6719   int nMem;            /* Number of memory cells used so far */
6720   int nSet;            /* Number of sets used so far */
6721   int ckOffset;        /* Stack offset to data used by CHECK constraints */
6722   u32 writeMask;       /* Start a write transaction on these databases */
6723   u32 cookieMask;      /* Bitmask of schema verified databases */
6724   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
6725   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
6726 #ifndef SQLITE_OMIT_SHARED_CACHE
6727   int nTableLock;        /* Number of locks in aTableLock */
6728   TableLock *aTableLock; /* Required table locks for shared-cache mode */
6729 #endif
6730
6731   /* Above is constant between recursions.  Below is reset before and after
6732   ** each recursion */
6733
6734   int nVar;            /* Number of '?' variables seen in the SQL so far */
6735   int nVarExpr;        /* Number of used slots in apVarExpr[] */
6736   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
6737   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
6738   u8 explain;          /* True if the EXPLAIN flag is found on the query */
6739   Token sErrToken;     /* The token at which the error occurred */
6740   Token sNameToken;    /* Token with unqualified schema object name */
6741   Token sLastToken;    /* The last token parsed */
6742   const char *zSql;    /* All SQL text */
6743   const char *zTail;   /* All SQL text past the last semicolon parsed */
6744   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
6745   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
6746   TriggerStack *trigStack;  /* Trigger actions being coded */
6747   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
6748 #ifndef SQLITE_OMIT_VIRTUALTABLE
6749   Token sArg;                /* Complete text of a module argument */
6750   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
6751   Table *pVirtualLock;       /* Require virtual table lock on this table */
6752 #endif
6753 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
6754   int nHeight;            /* Expression tree height of current sub-select */
6755 #endif
6756 };
6757
6758 #ifdef SQLITE_OMIT_VIRTUALTABLE
6759   #define IN_DECLARE_VTAB 0
6760 #else
6761   #define IN_DECLARE_VTAB (pParse->declareVtab)
6762 #endif
6763
6764 /*
6765 ** An instance of the following structure can be declared on a stack and used
6766 ** to save the Parse.zAuthContext value so that it can be restored later.
6767 */
6768 struct AuthContext {
6769   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
6770   Parse *pParse;              /* The Parse structure */
6771 };
6772
6773 /*
6774 ** Bitfield flags for P2 value in OP_Insert and OP_Delete
6775 */
6776 #define OPFLAG_NCHANGE   1    /* Set to update db->nChange */
6777 #define OPFLAG_LASTROWID 2    /* Set to update db->lastRowid */
6778 #define OPFLAG_ISUPDATE  4    /* This OP_Insert is an sql UPDATE */
6779 #define OPFLAG_APPEND    8    /* This is likely to be an append */
6780
6781 /*
6782  * Each trigger present in the database schema is stored as an instance of
6783  * struct Trigger. 
6784  *
6785  * Pointers to instances of struct Trigger are stored in two ways.
6786  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
6787  *    database). This allows Trigger structures to be retrieved by name.
6788  * 2. All triggers associated with a single table form a linked list, using the
6789  *    pNext member of struct Trigger. A pointer to the first element of the
6790  *    linked list is stored as the "pTrigger" member of the associated
6791  *    struct Table.
6792  *
6793  * The "step_list" member points to the first element of a linked list
6794  * containing the SQL statements specified as the trigger program.
6795  */
6796 struct Trigger {
6797   char *name;             /* The name of the trigger                        */
6798   char *table;            /* The table or view to which the trigger applies */
6799   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
6800   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
6801   Expr *pWhen;            /* The WHEN clause of the expresion (may be NULL) */
6802   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
6803                              the <column-list> is stored here */
6804   Token nameToken;        /* Token containing zName. Use during parsing only */
6805   Schema *pSchema;        /* Schema containing the trigger */
6806   Schema *pTabSchema;     /* Schema containing the table */
6807   TriggerStep *step_list; /* Link list of trigger program steps             */
6808   Trigger *pNext;         /* Next trigger associated with the table */
6809 };
6810
6811 /*
6812 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
6813 ** determine which. 
6814 **
6815 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
6816 ** In that cases, the constants below can be ORed together.
6817 */
6818 #define TRIGGER_BEFORE  1
6819 #define TRIGGER_AFTER   2
6820
6821 /*
6822  * An instance of struct TriggerStep is used to store a single SQL statement
6823  * that is a part of a trigger-program. 
6824  *
6825  * Instances of struct TriggerStep are stored in a singly linked list (linked
6826  * using the "pNext" member) referenced by the "step_list" member of the 
6827  * associated struct Trigger instance. The first element of the linked list is
6828  * the first step of the trigger-program.
6829  * 
6830  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
6831  * "SELECT" statement. The meanings of the other members is determined by the 
6832  * value of "op" as follows:
6833  *
6834  * (op == TK_INSERT)
6835  * orconf    -> stores the ON CONFLICT algorithm
6836  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
6837  *              this stores a pointer to the SELECT statement. Otherwise NULL.
6838  * target    -> A token holding the name of the table to insert into.
6839  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
6840  *              this stores values to be inserted. Otherwise NULL.
6841  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
6842  *              statement, then this stores the column-names to be
6843  *              inserted into.
6844  *
6845  * (op == TK_DELETE)
6846  * target    -> A token holding the name of the table to delete from.
6847  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
6848  *              Otherwise NULL.
6849  * 
6850  * (op == TK_UPDATE)
6851  * target    -> A token holding the name of the table to update rows of.
6852  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
6853  *              Otherwise NULL.
6854  * pExprList -> A list of the columns to update and the expressions to update
6855  *              them to. See sqlite3Update() documentation of "pChanges"
6856  *              argument.
6857  * 
6858  */
6859 struct TriggerStep {
6860   int op;              /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
6861   int orconf;          /* OE_Rollback etc. */
6862   Trigger *pTrig;      /* The trigger that this step is a part of */
6863
6864   Select *pSelect;     /* Valid for SELECT and sometimes 
6865                           INSERT steps (when pExprList == 0) */
6866   Token target;        /* Valid for DELETE, UPDATE, INSERT steps */
6867   Expr *pWhere;        /* Valid for DELETE, UPDATE steps */
6868   ExprList *pExprList; /* Valid for UPDATE statements and sometimes 
6869                            INSERT steps (when pSelect == 0)         */
6870   IdList *pIdList;     /* Valid for INSERT statements only */
6871   TriggerStep *pNext;  /* Next in the link-list */
6872   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
6873 };
6874
6875 /*
6876  * An instance of struct TriggerStack stores information required during code
6877  * generation of a single trigger program. While the trigger program is being
6878  * coded, its associated TriggerStack instance is pointed to by the
6879  * "pTriggerStack" member of the Parse structure.
6880  *
6881  * The pTab member points to the table that triggers are being coded on. The 
6882  * newIdx member contains the index of the vdbe cursor that points at the temp
6883  * table that stores the new.* references. If new.* references are not valid
6884  * for the trigger being coded (for example an ON DELETE trigger), then newIdx
6885  * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
6886  *
6887  * The ON CONFLICT policy to be used for the trigger program steps is stored 
6888  * as the orconf member. If this is OE_Default, then the ON CONFLICT clause 
6889  * specified for individual triggers steps is used.
6890  *
6891  * struct TriggerStack has a "pNext" member, to allow linked lists to be
6892  * constructed. When coding nested triggers (triggers fired by other triggers)
6893  * each nested trigger stores its parent trigger's TriggerStack as the "pNext" 
6894  * pointer. Once the nested trigger has been coded, the pNext value is restored
6895  * to the pTriggerStack member of the Parse stucture and coding of the parent
6896  * trigger continues.
6897  *
6898  * Before a nested trigger is coded, the linked list pointed to by the 
6899  * pTriggerStack is scanned to ensure that the trigger is not about to be coded
6900  * recursively. If this condition is detected, the nested trigger is not coded.
6901  */
6902 struct TriggerStack {
6903   Table *pTab;         /* Table that triggers are currently being coded on */
6904   int newIdx;          /* Index of vdbe cursor to "new" temp table */
6905   int oldIdx;          /* Index of vdbe cursor to "old" temp table */
6906   int orconf;          /* Current orconf policy */
6907   int ignoreJump;      /* where to jump to for a RAISE(IGNORE) */
6908   Trigger *pTrigger;   /* The trigger currently being coded */
6909   TriggerStack *pNext; /* Next trigger down on the trigger stack */
6910 };
6911
6912 /*
6913 ** The following structure contains information used by the sqliteFix...
6914 ** routines as they walk the parse tree to make database references
6915 ** explicit.  
6916 */
6917 typedef struct DbFixer DbFixer;
6918 struct DbFixer {
6919   Parse *pParse;      /* The parsing context.  Error messages written here */
6920   const char *zDb;    /* Make sure all objects are contained in this database */
6921   const char *zType;  /* Type of the container - used for error messages */
6922   const Token *pName; /* Name of the container - used for error messages */
6923 };
6924
6925 /*
6926 ** An objected used to accumulate the text of a string where we
6927 ** do not necessarily know how big the string will be in the end.
6928 */
6929 struct StrAccum {
6930   char *zBase;     /* A base allocation.  Not from malloc. */
6931   char *zText;     /* The string collected so far */
6932   int  nChar;      /* Length of the string so far */
6933   int  nAlloc;     /* Amount of space allocated in zText */
6934   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
6935   u8   useMalloc;      /* True if zText is enlargable using realloc */
6936   u8   tooBig;         /* Becomes true if string size exceeds limits */
6937 };
6938
6939 /*
6940 ** A pointer to this structure is used to communicate information
6941 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
6942 */
6943 typedef struct {
6944   sqlite3 *db;        /* The database being initialized */
6945   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
6946   char **pzErrMsg;    /* Error message stored here */
6947   int rc;             /* Result code stored here */
6948 } InitData;
6949
6950 /*
6951 ** Assuming zIn points to the first byte of a UTF-8 character,
6952 ** advance zIn to point to the first byte of the next UTF-8 character.
6953 */
6954 #define SQLITE_SKIP_UTF8(zIn) {                        \
6955   if( (*(zIn++))>=0xc0 ){                              \
6956     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
6957   }                                                    \
6958 }
6959
6960 /*
6961 ** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production
6962 ** builds) or a function call (for debugging).  If it is a function call,
6963 ** it allows the operator to set a breakpoint at the spot where database
6964 ** corruption is first detected.
6965 */
6966 #ifdef SQLITE_DEBUG
6967 SQLITE_PRIVATE   int sqlite3Corrupt(void);
6968 # define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
6969 # define DEBUGONLY(X)        X
6970 #else
6971 # define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
6972 # define DEBUGONLY(X)
6973 #endif
6974
6975 /*
6976 ** Internal function prototypes
6977 */
6978 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
6979 SQLITE_PRIVATE int sqlite3StrNICmp(const char *, const char *, int);
6980 SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
6981
6982 SQLITE_PRIVATE void *sqlite3MallocZero(unsigned);
6983 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, unsigned);
6984 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, unsigned);
6985 SQLITE_PRIVATE char *sqlite3StrDup(const char*);
6986 SQLITE_PRIVATE char *sqlite3StrNDup(const char*, int);
6987 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
6988 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
6989 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
6990 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
6991
6992 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
6993 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
6994 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
6995 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
6996 #endif
6997 #if defined(SQLITE_TEST)
6998 SQLITE_PRIVATE   void *sqlite3TextToPtr(const char*);
6999 #endif
7000 SQLITE_PRIVATE void sqlite3SetString(char **, ...);
7001 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
7002 SQLITE_PRIVATE void sqlite3ErrorClear(Parse*);
7003 SQLITE_PRIVATE void sqlite3Dequote(char*);
7004 SQLITE_PRIVATE void sqlite3DequoteExpr(sqlite3*, Expr*);
7005 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
7006 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
7007 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
7008 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*, int, Expr*, Expr*, const Token*);
7009 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
7010 SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse*,Token*);
7011 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
7012 SQLITE_PRIVATE void sqlite3ExprSpan(Expr*,Token*,Token*);
7013 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
7014 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
7015 SQLITE_PRIVATE void sqlite3ExprDelete(Expr*);
7016 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*,Token*);
7017 SQLITE_PRIVATE void sqlite3ExprListDelete(ExprList*);
7018 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
7019 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
7020 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
7021 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
7022 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
7023 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
7024 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,char*,Select*);
7025 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
7026 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
7027 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
7028 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
7029 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
7030 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
7031 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
7032 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*);
7033 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
7034 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
7035
7036 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
7037
7038 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
7039 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
7040 #else
7041 # define sqlite3ViewGetColumnNames(A,B) 0
7042 #endif
7043
7044 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
7045 SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
7046 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
7047 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
7048 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
7049 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
7050 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
7051 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*, Token*,
7052                                       Select*, Expr*, IdList*);
7053 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
7054 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
7055 SQLITE_PRIVATE void sqlite3IdListDelete(IdList*);
7056 SQLITE_PRIVATE void sqlite3SrcListDelete(SrcList*);
7057 SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
7058                         Token*, int, int);
7059 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
7060 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, int, int, Select*, int, int*, char *aff);
7061 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
7062                          Expr*,ExprList*,int,Expr*,Expr*);
7063 SQLITE_PRIVATE void sqlite3SelectDelete(Select*);
7064 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
7065 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
7066 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
7067 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
7068 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
7069 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**);
7070 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
7071 SQLITE_PRIVATE void sqlite3ExprCodeGetColumn(Vdbe*, Table*, int, int);
7072 SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*);
7073 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*);
7074 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*);
7075 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
7076 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
7077 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
7078 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,const char*, const char*);
7079 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
7080 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
7081 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
7082 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
7083 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
7084 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
7085 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
7086 SQLITE_PRIVATE int sqlite3ExprResolveNames(NameContext *, Expr *);
7087 SQLITE_PRIVATE int sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
7088 SQLITE_PRIVATE int sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
7089 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
7090 SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(Parse *, const char*);
7091 SQLITE_PRIVATE void sqlite3Randomness(int, void*);
7092 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
7093 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
7094 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
7095 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
7096 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
7097 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
7098 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
7099 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
7100 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
7101 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
7102 SQLITE_PRIVATE void sqlite3GenerateRowDelete(sqlite3*, Vdbe*, Table*, int, int);
7103 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Vdbe*, Table*, int, char*);
7104 SQLITE_PRIVATE void sqlite3GenerateIndexKey(Vdbe*, Index*, int);
7105 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,char*,int,int,int,int);
7106 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, char*, int, int, int, int);
7107 SQLITE_PRIVATE void sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
7108 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
7109 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*);
7110 SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3*,Token*, Token*);
7111 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*);
7112 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*);
7113 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
7114 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*);
7115 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
7116 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
7117 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(sqlite3*);
7118 SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3*);
7119 SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3*);
7120 SQLITE_PRIVATE int sqlite3SafetyCheck(sqlite3*);
7121 SQLITE_PRIVATE void sqlite3ChangeCookie(sqlite3*, Vdbe*, int);
7122
7123 #ifndef SQLITE_OMIT_TRIGGER
7124 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
7125                            Expr*,int, int);
7126 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
7127 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
7128 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
7129 SQLITE_PRIVATE   int sqlite3TriggersExist(Parse*, Table*, int, ExprList*);
7130 SQLITE_PRIVATE   int sqlite3CodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int, 
7131                            int, int);
7132   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
7133 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(TriggerStep*);
7134 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
7135 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
7136                                         ExprList*,Select*,int);
7137 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, int);
7138 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
7139 SQLITE_PRIVATE   void sqlite3DeleteTrigger(Trigger*);
7140 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
7141 #else
7142 # define sqlite3TriggersExist(A,B,C,D,E,F) 0
7143 # define sqlite3DeleteTrigger(A)
7144 # define sqlite3DropTriggerPtr(A,B)
7145 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
7146 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I) 0
7147 #endif
7148
7149 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
7150 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
7151 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
7152 #ifndef SQLITE_OMIT_AUTHORIZATION
7153 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
7154 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
7155 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
7156 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
7157 #else
7158 # define sqlite3AuthRead(a,b,c,d)
7159 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
7160 # define sqlite3AuthContextPush(a,b,c)
7161 # define sqlite3AuthContextPop(a)  ((void)(a))
7162 #endif
7163 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
7164 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
7165 SQLITE_PRIVATE int sqlite3BtreeFactory(const sqlite3 *db, const char *zFilename,
7166                        int omitJournal, int nCache, int flags, Btree **ppBtree);
7167 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
7168 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
7169 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
7170 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
7171 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
7172 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
7173 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
7174 SQLITE_API char *sqlite3_snprintf(int,char*,const char*,...);
7175 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
7176 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *, int);
7177 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
7178 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
7179 SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8*, const u8**);
7180 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *, u64);
7181 SQLITE_PRIVATE int sqlite3GetVarint(const unsigned char *, u64 *);
7182 SQLITE_PRIVATE int sqlite3GetVarint32(const unsigned char *, u32 *);
7183 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
7184 SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *, Index *);
7185 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
7186 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
7187 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
7188 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
7189 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
7190 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
7191 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z);
7192 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
7193 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
7194 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
7195 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char *,int,int);
7196 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName);
7197 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
7198 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
7199 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
7200 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
7201 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
7202
7203 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
7204 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
7205 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
7206                         void(*)(void*));
7207 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
7208 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
7209 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int);
7210 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
7211 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
7212 #ifndef SQLITE_AMALGAMATION
7213 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
7214 #endif
7215 SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
7216 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
7217 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3*);
7218 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
7219 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
7220 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
7221 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
7222 SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *, Expr *);
7223 SQLITE_PRIVATE int sqlite3SelectResolve(Parse *, Select *, NameContext *);
7224 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int);
7225 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
7226 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
7227 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, CollSeq *, const char *, int);
7228 SQLITE_PRIVATE char sqlite3AffinityType(const Token*);
7229 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
7230 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
7231 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
7232 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
7233 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
7234 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
7235 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
7236 SQLITE_PRIVATE void sqlite3AttachFunctions(sqlite3 *);
7237 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
7238 SQLITE_PRIVATE void sqlite3SchemaFree(void *);
7239 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
7240 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
7241 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
7242 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
7243   void (*)(sqlite3_context*,int,sqlite3_value **),
7244   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
7245 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
7246 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
7247
7248 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
7249 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
7250 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
7251
7252
7253 /*
7254 ** The interface to the LEMON-generated parser
7255 */
7256 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
7257 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
7258 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
7259
7260 #ifndef SQLITE_OMIT_LOAD_EXTENSION
7261 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
7262 SQLITE_PRIVATE   int sqlite3AutoLoadExtensions(sqlite3*);
7263 #else
7264 # define sqlite3CloseExtensions(X)
7265 # define sqlite3AutoLoadExtensions(X)  SQLITE_OK
7266 #endif
7267
7268 #ifndef SQLITE_OMIT_SHARED_CACHE
7269 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
7270 #else
7271   #define sqlite3TableLock(v,w,x,y,z)
7272 #endif
7273
7274 #ifdef SQLITE_TEST
7275 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
7276 #endif
7277
7278 /*
7279 ** The MallocDisallow() and MallocAllow() routines are like asserts.
7280 ** Call them around a section of code that you do not expect to do
7281 ** any memory allocation.
7282 */
7283 #ifdef SQLITE_MEMDEBUG
7284 SQLITE_PRIVATE   void sqlite3MallocDisallow(void);
7285 SQLITE_PRIVATE   void sqlite3MallocAllow(void);
7286 SQLITE_PRIVATE   void sqlite3MallocBenignFailure(int);
7287 SQLITE_PRIVATE   void sqlite3MallocEnterBenignBlock(int isBenign);
7288 SQLITE_PRIVATE   void sqlite3MallocLeaveBenignBlock();
7289 #else
7290 # define sqlite3MallocDisallow()
7291 # define sqlite3MallocAllow()
7292 # define sqlite3MallocBenignFailure(x)
7293 # define sqlite3MallocEnterBenignBlock(x);
7294 # define sqlite3MallocLeaveBenignBlock();
7295 #endif
7296
7297
7298 #ifdef SQLITE_OMIT_VIRTUALTABLE
7299 #  define sqlite3VtabClear(X)
7300 #  define sqlite3VtabSync(X,Y) (Y)
7301 #  define sqlite3VtabRollback(X)
7302 #  define sqlite3VtabCommit(X)
7303 #else
7304 SQLITE_PRIVATE    void sqlite3VtabClear(Table*);
7305 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, int rc);
7306 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
7307 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
7308 #endif
7309 SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab*);
7310 SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3*, sqlite3_vtab*);
7311 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
7312 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
7313 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
7314 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
7315 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
7316 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
7317 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
7318 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, sqlite3_vtab *);
7319 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
7320 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
7321 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
7322 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, int, const char*);
7323 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
7324
7325 #define IN_INDEX_ROWID           1
7326 #define IN_INDEX_EPH             2
7327 #define IN_INDEX_INDEX           3
7328 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int);
7329
7330 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
7331 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
7332 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
7333 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
7334 #else
7335   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
7336 #endif
7337
7338 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
7339 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Expr *);
7340 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
7341 #else
7342   #define sqlite3ExprSetHeight(x)
7343 #endif
7344
7345 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
7346 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
7347
7348 #ifdef SQLITE_SSE
7349 #include "sseInt.h"
7350 #endif
7351
7352 #ifdef SQLITE_DEBUG
7353 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
7354 #endif
7355
7356 /*
7357 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
7358 ** sqlite3_io_trace is a pointer to a printf-like routine used to
7359 ** print I/O tracing messages. 
7360 */
7361 #ifdef SQLITE_ENABLE_IOTRACE
7362 # define IOTRACE(A)  if( sqlite3_io_trace ){ sqlite3_io_trace A; }
7363 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
7364 #else
7365 # define IOTRACE(A)
7366 # define sqlite3VdbeIOTraceSql(X)
7367 #endif
7368 SQLITE_EXTERN void (*sqlite3_io_trace)(const char*,...);
7369
7370 #endif
7371
7372 /************** End of sqliteInt.h *******************************************/
7373 /************** Begin file date.c ********************************************/
7374 /*
7375 ** 2003 October 31
7376 **
7377 ** The author disclaims copyright to this source code.  In place of
7378 ** a legal notice, here is a blessing:
7379 **
7380 **    May you do good and not evil.
7381 **    May you find forgiveness for yourself and forgive others.
7382 **    May you share freely, never taking more than you give.
7383 **
7384 *************************************************************************
7385 ** This file contains the C functions that implement date and time
7386 ** functions for SQLite.  
7387 **
7388 ** There is only one exported symbol in this file - the function
7389 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
7390 ** All other code has file scope.
7391 **
7392 ** $Id: date.c,v 1.73 2007/09/12 17:01:45 danielk1977 Exp $
7393 **
7394 ** SQLite processes all times and dates as Julian Day numbers.  The
7395 ** dates and times are stored as the number of days since noon
7396 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
7397 ** calendar system. 
7398 **
7399 ** 1970-01-01 00:00:00 is JD 2440587.5
7400 ** 2000-01-01 00:00:00 is JD 2451544.5
7401 **
7402 ** This implemention requires years to be expressed as a 4-digit number
7403 ** which means that only dates between 0000-01-01 and 9999-12-31 can
7404 ** be represented, even though julian day numbers allow a much wider
7405 ** range of dates.
7406 **
7407 ** The Gregorian calendar system is used for all dates and times,
7408 ** even those that predate the Gregorian calendar.  Historians usually
7409 ** use the Julian calendar for dates prior to 1582-10-15 and for some
7410 ** dates afterwards, depending on locale.  Beware of this difference.
7411 **
7412 ** The conversion algorithms are implemented based on descriptions
7413 ** in the following text:
7414 **
7415 **      Jean Meeus
7416 **      Astronomical Algorithms, 2nd Edition, 1998
7417 **      ISBM 0-943396-61-1
7418 **      Willmann-Bell, Inc
7419 **      Richmond, Virginia (USA)
7420 */
7421 #include <ctype.h>
7422 #include <time.h>
7423
7424 #ifndef SQLITE_OMIT_DATETIME_FUNCS
7425
7426 /*
7427 ** A structure for holding a single date and time.
7428 */
7429 typedef struct DateTime DateTime;
7430 struct DateTime {
7431   double rJD;      /* The julian day number */
7432   int Y, M, D;     /* Year, month, and day */
7433   int h, m;        /* Hour and minutes */
7434   int tz;          /* Timezone offset in minutes */
7435   double s;        /* Seconds */
7436   char validYMD;   /* True if Y,M,D are valid */
7437   char validHMS;   /* True if h,m,s are valid */
7438   char validJD;    /* True if rJD is valid */
7439   char validTZ;    /* True if tz is valid */
7440 };
7441
7442
7443 /*
7444 ** Convert zDate into one or more integers.  Additional arguments
7445 ** come in groups of 5 as follows:
7446 **
7447 **       N       number of digits in the integer
7448 **       min     minimum allowed value of the integer
7449 **       max     maximum allowed value of the integer
7450 **       nextC   first character after the integer
7451 **       pVal    where to write the integers value.
7452 **
7453 ** Conversions continue until one with nextC==0 is encountered.
7454 ** The function returns the number of successful conversions.
7455 */
7456 static int getDigits(const char *zDate, ...){
7457   va_list ap;
7458   int val;
7459   int N;
7460   int min;
7461   int max;
7462   int nextC;
7463   int *pVal;
7464   int cnt = 0;
7465   va_start(ap, zDate);
7466   do{
7467     N = va_arg(ap, int);
7468     min = va_arg(ap, int);
7469     max = va_arg(ap, int);
7470     nextC = va_arg(ap, int);
7471     pVal = va_arg(ap, int*);
7472     val = 0;
7473     while( N-- ){
7474       if( !isdigit(*(u8*)zDate) ){
7475         goto end_getDigits;
7476       }
7477       val = val*10 + *zDate - '0';
7478       zDate++;
7479     }
7480     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
7481       goto end_getDigits;
7482     }
7483     *pVal = val;
7484     zDate++;
7485     cnt++;
7486   }while( nextC );
7487 end_getDigits:
7488   va_end(ap);
7489   return cnt;
7490 }
7491
7492 /*
7493 ** Read text from z[] and convert into a floating point number.  Return
7494 ** the number of digits converted.
7495 */
7496 #define getValue sqlite3AtoF
7497
7498 /*
7499 ** Parse a timezone extension on the end of a date-time.
7500 ** The extension is of the form:
7501 **
7502 **        (+/-)HH:MM
7503 **
7504 ** If the parse is successful, write the number of minutes
7505 ** of change in *pnMin and return 0.  If a parser error occurs,
7506 ** return 0.
7507 **
7508 ** A missing specifier is not considered an error.
7509 */
7510 static int parseTimezone(const char *zDate, DateTime *p){
7511   int sgn = 0;
7512   int nHr, nMn;
7513   while( isspace(*(u8*)zDate) ){ zDate++; }
7514   p->tz = 0;
7515   if( *zDate=='-' ){
7516     sgn = -1;
7517   }else if( *zDate=='+' ){
7518     sgn = +1;
7519   }else{
7520     return *zDate!=0;
7521   }
7522   zDate++;
7523   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
7524     return 1;
7525   }
7526   zDate += 5;
7527   p->tz = sgn*(nMn + nHr*60);
7528   while( isspace(*(u8*)zDate) ){ zDate++; }
7529   return *zDate!=0;
7530 }
7531
7532 /*
7533 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
7534 ** The HH, MM, and SS must each be exactly 2 digits.  The
7535 ** fractional seconds FFFF can be one or more digits.
7536 **
7537 ** Return 1 if there is a parsing error and 0 on success.
7538 */
7539 static int parseHhMmSs(const char *zDate, DateTime *p){
7540   int h, m, s;
7541   double ms = 0.0;
7542   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
7543     return 1;
7544   }
7545   zDate += 5;
7546   if( *zDate==':' ){
7547     zDate++;
7548     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
7549       return 1;
7550     }
7551     zDate += 2;
7552     if( *zDate=='.' && isdigit((u8)zDate[1]) ){
7553       double rScale = 1.0;
7554       zDate++;
7555       while( isdigit(*(u8*)zDate) ){
7556         ms = ms*10.0 + *zDate - '0';
7557         rScale *= 10.0;
7558         zDate++;
7559       }
7560       ms /= rScale;
7561     }
7562   }else{
7563     s = 0;
7564   }
7565   p->validJD = 0;
7566   p->validHMS = 1;
7567   p->h = h;
7568   p->m = m;
7569   p->s = s + ms;
7570   if( parseTimezone(zDate, p) ) return 1;
7571   p->validTZ = p->tz!=0;
7572   return 0;
7573 }
7574
7575 /*
7576 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
7577 ** that the YYYY-MM-DD is according to the Gregorian calendar.
7578 **
7579 ** Reference:  Meeus page 61
7580 */
7581 static void computeJD(DateTime *p){
7582   int Y, M, D, A, B, X1, X2;
7583
7584   if( p->validJD ) return;
7585   if( p->validYMD ){
7586     Y = p->Y;
7587     M = p->M;
7588     D = p->D;
7589   }else{
7590     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
7591     M = 1;
7592     D = 1;
7593   }
7594   if( M<=2 ){
7595     Y--;
7596     M += 12;
7597   }
7598   A = Y/100;
7599   B = 2 - A + (A/4);
7600   X1 = 365.25*(Y+4716);
7601   X2 = 30.6001*(M+1);
7602   p->rJD = X1 + X2 + D + B - 1524.5;
7603   p->validJD = 1;
7604   if( p->validHMS ){
7605     p->rJD += (p->h*3600.0 + p->m*60.0 + p->s)/86400.0;
7606     if( p->validTZ ){
7607       p->rJD -= p->tz*60/86400.0;
7608       p->validYMD = 0;
7609       p->validHMS = 0;
7610       p->validTZ = 0;
7611     }
7612   }
7613 }
7614
7615 /*
7616 ** Parse dates of the form
7617 **
7618 **     YYYY-MM-DD HH:MM:SS.FFF
7619 **     YYYY-MM-DD HH:MM:SS
7620 **     YYYY-MM-DD HH:MM
7621 **     YYYY-MM-DD
7622 **
7623 ** Write the result into the DateTime structure and return 0
7624 ** on success and 1 if the input string is not a well-formed
7625 ** date.
7626 */
7627 static int parseYyyyMmDd(const char *zDate, DateTime *p){
7628   int Y, M, D, neg;
7629
7630   if( zDate[0]=='-' ){
7631     zDate++;
7632     neg = 1;
7633   }else{
7634     neg = 0;
7635   }
7636   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
7637     return 1;
7638   }
7639   zDate += 10;
7640   while( isspace(*(u8*)zDate) || 'T'==*(u8*)zDate ){ zDate++; }
7641   if( parseHhMmSs(zDate, p)==0 ){
7642     /* We got the time */
7643   }else if( *zDate==0 ){
7644     p->validHMS = 0;
7645   }else{
7646     return 1;
7647   }
7648   p->validJD = 0;
7649   p->validYMD = 1;
7650   p->Y = neg ? -Y : Y;
7651   p->M = M;
7652   p->D = D;
7653   if( p->validTZ ){
7654     computeJD(p);
7655   }
7656   return 0;
7657 }
7658
7659 /*
7660 ** Attempt to parse the given string into a Julian Day Number.  Return
7661 ** the number of errors.
7662 **
7663 ** The following are acceptable forms for the input string:
7664 **
7665 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
7666 **      DDDD.DD 
7667 **      now
7668 **
7669 ** In the first form, the +/-HH:MM is always optional.  The fractional
7670 ** seconds extension (the ".FFF") is optional.  The seconds portion
7671 ** (":SS.FFF") is option.  The year and date can be omitted as long
7672 ** as there is a time string.  The time string can be omitted as long
7673 ** as there is a year and date.
7674 */
7675 static int parseDateOrTime(
7676   sqlite3_context *context, 
7677   const char *zDate, 
7678   DateTime *p
7679 ){
7680   memset(p, 0, sizeof(*p));
7681   if( parseYyyyMmDd(zDate,p)==0 ){
7682     return 0;
7683   }else if( parseHhMmSs(zDate, p)==0 ){
7684     return 0;
7685   }else if( sqlite3StrICmp(zDate,"now")==0){
7686     double r;
7687     sqlite3OsCurrentTime((sqlite3_vfs *)sqlite3_user_data(context), &r);
7688     p->rJD = r;
7689     p->validJD = 1;
7690     return 0;
7691   }else if( sqlite3IsNumber(zDate, 0, SQLITE_UTF8) ){
7692     getValue(zDate, &p->rJD);
7693     p->validJD = 1;
7694     return 0;
7695   }
7696   return 1;
7697 }
7698
7699 /*
7700 ** Compute the Year, Month, and Day from the julian day number.
7701 */
7702 static void computeYMD(DateTime *p){
7703   int Z, A, B, C, D, E, X1;
7704   if( p->validYMD ) return;
7705   if( !p->validJD ){
7706     p->Y = 2000;
7707     p->M = 1;
7708     p->D = 1;
7709   }else{
7710     Z = p->rJD + 0.5;
7711     A = (Z - 1867216.25)/36524.25;
7712     A = Z + 1 + A - (A/4);
7713     B = A + 1524;
7714     C = (B - 122.1)/365.25;
7715     D = 365.25*C;
7716     E = (B-D)/30.6001;
7717     X1 = 30.6001*E;
7718     p->D = B - D - X1;
7719     p->M = E<14 ? E-1 : E-13;
7720     p->Y = p->M>2 ? C - 4716 : C - 4715;
7721   }
7722   p->validYMD = 1;
7723 }
7724
7725 /*
7726 ** Compute the Hour, Minute, and Seconds from the julian day number.
7727 */
7728 static void computeHMS(DateTime *p){
7729   int Z, s;
7730   if( p->validHMS ) return;
7731   computeJD(p);
7732   Z = p->rJD + 0.5;
7733   s = (p->rJD + 0.5 - Z)*86400000.0 + 0.5;
7734   p->s = 0.001*s;
7735   s = p->s;
7736   p->s -= s;
7737   p->h = s/3600;
7738   s -= p->h*3600;
7739   p->m = s/60;
7740   p->s += s - p->m*60;
7741   p->validHMS = 1;
7742 }
7743
7744 /*
7745 ** Compute both YMD and HMS
7746 */
7747 static void computeYMD_HMS(DateTime *p){
7748   computeYMD(p);
7749   computeHMS(p);
7750 }
7751
7752 /*
7753 ** Clear the YMD and HMS and the TZ
7754 */
7755 static void clearYMD_HMS_TZ(DateTime *p){
7756   p->validYMD = 0;
7757   p->validHMS = 0;
7758   p->validTZ = 0;
7759 }
7760
7761 /*
7762 ** Compute the difference (in days) between localtime and UTC (a.k.a. GMT)
7763 ** for the time value p where p is in UTC.
7764 */
7765 static double localtimeOffset(DateTime *p){
7766   DateTime x, y;
7767   time_t t;
7768   x = *p;
7769   computeYMD_HMS(&x);
7770   if( x.Y<1971 || x.Y>=2038 ){
7771     x.Y = 2000;
7772     x.M = 1;
7773     x.D = 1;
7774     x.h = 0;
7775     x.m = 0;
7776     x.s = 0.0;
7777   } else {
7778     int s = x.s + 0.5;
7779     x.s = s;
7780   }
7781   x.tz = 0;
7782   x.validJD = 0;
7783   computeJD(&x);
7784   t = (x.rJD-2440587.5)*86400.0 + 0.5;
7785 #ifdef HAVE_LOCALTIME_R
7786   {
7787     struct tm sLocal;
7788     localtime_r(&t, &sLocal);
7789     y.Y = sLocal.tm_year + 1900;
7790     y.M = sLocal.tm_mon + 1;
7791     y.D = sLocal.tm_mday;
7792     y.h = sLocal.tm_hour;
7793     y.m = sLocal.tm_min;
7794     y.s = sLocal.tm_sec;
7795   }
7796 #else
7797   {
7798     struct tm *pTm;
7799     sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
7800     pTm = localtime(&t);
7801     y.Y = pTm->tm_year + 1900;
7802     y.M = pTm->tm_mon + 1;
7803     y.D = pTm->tm_mday;
7804     y.h = pTm->tm_hour;
7805     y.m = pTm->tm_min;
7806     y.s = pTm->tm_sec;
7807     sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
7808   }
7809 #endif
7810   y.validYMD = 1;
7811   y.validHMS = 1;
7812   y.validJD = 0;
7813   y.validTZ = 0;
7814   computeJD(&y);
7815   return y.rJD - x.rJD;
7816 }
7817
7818 /*
7819 ** Process a modifier to a date-time stamp.  The modifiers are
7820 ** as follows:
7821 **
7822 **     NNN days
7823 **     NNN hours
7824 **     NNN minutes
7825 **     NNN.NNNN seconds
7826 **     NNN months
7827 **     NNN years
7828 **     start of month
7829 **     start of year
7830 **     start of week
7831 **     start of day
7832 **     weekday N
7833 **     unixepoch
7834 **     localtime
7835 **     utc
7836 **
7837 ** Return 0 on success and 1 if there is any kind of error.
7838 */
7839 static int parseModifier(const char *zMod, DateTime *p){
7840   int rc = 1;
7841   int n;
7842   double r;
7843   char *z, zBuf[30];
7844   z = zBuf;
7845   for(n=0; n<sizeof(zBuf)-1 && zMod[n]; n++){
7846     z[n] = tolower(zMod[n]);
7847   }
7848   z[n] = 0;
7849   switch( z[0] ){
7850     case 'l': {
7851       /*    localtime
7852       **
7853       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
7854       ** show local time.
7855       */
7856       if( strcmp(z, "localtime")==0 ){
7857         computeJD(p);
7858         p->rJD += localtimeOffset(p);
7859         clearYMD_HMS_TZ(p);
7860         rc = 0;
7861       }
7862       break;
7863     }
7864     case 'u': {
7865       /*
7866       **    unixepoch
7867       **
7868       ** Treat the current value of p->rJD as the number of
7869       ** seconds since 1970.  Convert to a real julian day number.
7870       */
7871       if( strcmp(z, "unixepoch")==0 && p->validJD ){
7872         p->rJD = p->rJD/86400.0 + 2440587.5;
7873         clearYMD_HMS_TZ(p);
7874         rc = 0;
7875       }else if( strcmp(z, "utc")==0 ){
7876         double c1;
7877         computeJD(p);
7878         c1 = localtimeOffset(p);
7879         p->rJD -= c1;
7880         clearYMD_HMS_TZ(p);
7881         p->rJD += c1 - localtimeOffset(p);
7882         rc = 0;
7883       }
7884       break;
7885     }
7886     case 'w': {
7887       /*
7888       **    weekday N
7889       **
7890       ** Move the date to the same time on the next occurrence of
7891       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
7892       ** date is already on the appropriate weekday, this is a no-op.
7893       */
7894       if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
7895                  && (n=r)==r && n>=0 && r<7 ){
7896         int Z;
7897         computeYMD_HMS(p);
7898         p->validTZ = 0;
7899         p->validJD = 0;
7900         computeJD(p);
7901         Z = p->rJD + 1.5;
7902         Z %= 7;
7903         if( Z>n ) Z -= 7;
7904         p->rJD += n - Z;
7905         clearYMD_HMS_TZ(p);
7906         rc = 0;
7907       }
7908       break;
7909     }
7910     case 's': {
7911       /*
7912       **    start of TTTTT
7913       **
7914       ** Move the date backwards to the beginning of the current day,
7915       ** or month or year.
7916       */
7917       if( strncmp(z, "start of ", 9)!=0 ) break;
7918       z += 9;
7919       computeYMD(p);
7920       p->validHMS = 1;
7921       p->h = p->m = 0;
7922       p->s = 0.0;
7923       p->validTZ = 0;
7924       p->validJD = 0;
7925       if( strcmp(z,"month")==0 ){
7926         p->D = 1;
7927         rc = 0;
7928       }else if( strcmp(z,"year")==0 ){
7929         computeYMD(p);
7930         p->M = 1;
7931         p->D = 1;
7932         rc = 0;
7933       }else if( strcmp(z,"day")==0 ){
7934         rc = 0;
7935       }
7936       break;
7937     }
7938     case '+':
7939     case '-':
7940     case '0':
7941     case '1':
7942     case '2':
7943     case '3':
7944     case '4':
7945     case '5':
7946     case '6':
7947     case '7':
7948     case '8':
7949     case '9': {
7950       n = getValue(z, &r);
7951       assert( n>=1 );
7952       if( z[n]==':' ){
7953         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
7954         ** specified number of hours, minutes, seconds, and fractional seconds
7955         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
7956         ** omitted.
7957         */
7958         const char *z2 = z;
7959         DateTime tx;
7960         int day;
7961         if( !isdigit(*(u8*)z2) ) z2++;
7962         memset(&tx, 0, sizeof(tx));
7963         if( parseHhMmSs(z2, &tx) ) break;
7964         computeJD(&tx);
7965         tx.rJD -= 0.5;
7966         day = (int)tx.rJD;
7967         tx.rJD -= day;
7968         if( z[0]=='-' ) tx.rJD = -tx.rJD;
7969         computeJD(p);
7970         clearYMD_HMS_TZ(p);
7971         p->rJD += tx.rJD;
7972         rc = 0;
7973         break;
7974       }
7975       z += n;
7976       while( isspace(*(u8*)z) ) z++;
7977       n = strlen(z);
7978       if( n>10 || n<3 ) break;
7979       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
7980       computeJD(p);
7981       rc = 0;
7982       if( n==3 && strcmp(z,"day")==0 ){
7983         p->rJD += r;
7984       }else if( n==4 && strcmp(z,"hour")==0 ){
7985         p->rJD += r/24.0;
7986       }else if( n==6 && strcmp(z,"minute")==0 ){
7987         p->rJD += r/(24.0*60.0);
7988       }else if( n==6 && strcmp(z,"second")==0 ){
7989         p->rJD += r/(24.0*60.0*60.0);
7990       }else if( n==5 && strcmp(z,"month")==0 ){
7991         int x, y;
7992         computeYMD_HMS(p);
7993         p->M += r;
7994         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
7995         p->Y += x;
7996         p->M -= x*12;
7997         p->validJD = 0;
7998         computeJD(p);
7999         y = r;
8000         if( y!=r ){
8001           p->rJD += (r - y)*30.0;
8002         }
8003       }else if( n==4 && strcmp(z,"year")==0 ){
8004         computeYMD_HMS(p);
8005         p->Y += r;
8006         p->validJD = 0;
8007         computeJD(p);
8008       }else{
8009         rc = 1;
8010       }
8011       clearYMD_HMS_TZ(p);
8012       break;
8013     }
8014     default: {
8015       break;
8016     }
8017   }
8018   return rc;
8019 }
8020
8021 /*
8022 ** Process time function arguments.  argv[0] is a date-time stamp.
8023 ** argv[1] and following are modifiers.  Parse them all and write
8024 ** the resulting time into the DateTime structure p.  Return 0
8025 ** on success and 1 if there are any errors.
8026 */
8027 static int isDate(
8028   sqlite3_context *context, 
8029   int argc, 
8030   sqlite3_value **argv, 
8031   DateTime *p
8032 ){
8033   int i;
8034   const unsigned char *z;
8035   if( argc==0 ) return 1;
8036   z = sqlite3_value_text(argv[0]);
8037   if( !z || parseDateOrTime(context, (char*)z, p) ){
8038     return 1;
8039   }
8040   for(i=1; i<argc; i++){
8041     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
8042       return 1;
8043     }
8044   }
8045   return 0;
8046 }
8047
8048
8049 /*
8050 ** The following routines implement the various date and time functions
8051 ** of SQLite.
8052 */
8053
8054 /*
8055 **    julianday( TIMESTRING, MOD, MOD, ...)
8056 **
8057 ** Return the julian day number of the date specified in the arguments
8058 */
8059 static void juliandayFunc(
8060   sqlite3_context *context,
8061   int argc,
8062   sqlite3_value **argv
8063 ){
8064   DateTime x;
8065   if( isDate(context, argc, argv, &x)==0 ){
8066     computeJD(&x);
8067     sqlite3_result_double(context, x.rJD);
8068   }
8069 }
8070
8071 /*
8072 **    datetime( TIMESTRING, MOD, MOD, ...)
8073 **
8074 ** Return YYYY-MM-DD HH:MM:SS
8075 */
8076 static void datetimeFunc(
8077   sqlite3_context *context,
8078   int argc,
8079   sqlite3_value **argv
8080 ){
8081   DateTime x;
8082   if( isDate(context, argc, argv, &x)==0 ){
8083     char zBuf[100];
8084     computeYMD_HMS(&x);
8085     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
8086                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
8087     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
8088   }
8089 }
8090
8091 /*
8092 **    time( TIMESTRING, MOD, MOD, ...)
8093 **
8094 ** Return HH:MM:SS
8095 */
8096 static void timeFunc(
8097   sqlite3_context *context,
8098   int argc,
8099   sqlite3_value **argv
8100 ){
8101   DateTime x;
8102   if( isDate(context, argc, argv, &x)==0 ){
8103     char zBuf[100];
8104     computeHMS(&x);
8105     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
8106     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
8107   }
8108 }
8109
8110 /*
8111 **    date( TIMESTRING, MOD, MOD, ...)
8112 **
8113 ** Return YYYY-MM-DD
8114 */
8115 static void dateFunc(
8116   sqlite3_context *context,
8117   int argc,
8118   sqlite3_value **argv
8119 ){
8120   DateTime x;
8121   if( isDate(context, argc, argv, &x)==0 ){
8122     char zBuf[100];
8123     computeYMD(&x);
8124     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
8125     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
8126   }
8127 }
8128
8129 /*
8130 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
8131 **
8132 ** Return a string described by FORMAT.  Conversions as follows:
8133 **
8134 **   %d  day of month
8135 **   %f  ** fractional seconds  SS.SSS
8136 **   %H  hour 00-24
8137 **   %j  day of year 000-366
8138 **   %J  ** Julian day number
8139 **   %m  month 01-12
8140 **   %M  minute 00-59
8141 **   %s  seconds since 1970-01-01
8142 **   %S  seconds 00-59
8143 **   %w  day of week 0-6  sunday==0
8144 **   %W  week of year 00-53
8145 **   %Y  year 0000-9999
8146 **   %%  %
8147 */
8148 static void strftimeFunc(
8149   sqlite3_context *context,
8150   int argc,
8151   sqlite3_value **argv
8152 ){
8153   DateTime x;
8154   u64 n;
8155   int i, j;
8156   char *z;
8157   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
8158   char zBuf[100];
8159   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
8160   for(i=0, n=1; zFmt[i]; i++, n++){
8161     if( zFmt[i]=='%' ){
8162       switch( zFmt[i+1] ){
8163         case 'd':
8164         case 'H':
8165         case 'm':
8166         case 'M':
8167         case 'S':
8168         case 'W':
8169           n++;
8170           /* fall thru */
8171         case 'w':
8172         case '%':
8173           break;
8174         case 'f':
8175           n += 8;
8176           break;
8177         case 'j':
8178           n += 3;
8179           break;
8180         case 'Y':
8181           n += 8;
8182           break;
8183         case 's':
8184         case 'J':
8185           n += 50;
8186           break;
8187         default:
8188           return;  /* ERROR.  return a NULL */
8189       }
8190       i++;
8191     }
8192   }
8193   if( n<sizeof(zBuf) ){
8194     z = zBuf;
8195   }else if( n>SQLITE_MAX_LENGTH ){
8196     sqlite3_result_error_toobig(context);
8197     return;
8198   }else{
8199     z = sqlite3_malloc( n );
8200     if( z==0 ) return;
8201   }
8202   computeJD(&x);
8203   computeYMD_HMS(&x);
8204   for(i=j=0; zFmt[i]; i++){
8205     if( zFmt[i]!='%' ){
8206       z[j++] = zFmt[i];
8207     }else{
8208       i++;
8209       switch( zFmt[i] ){
8210         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
8211         case 'f': {
8212           double s = x.s;
8213           if( s>59.999 ) s = 59.999;
8214           sqlite3_snprintf(7, &z[j],"%06.3f", s);
8215           j += strlen(&z[j]);
8216           break;
8217         }
8218         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
8219         case 'W': /* Fall thru */
8220         case 'j': {
8221           int nDay;             /* Number of days since 1st day of year */
8222           DateTime y = x;
8223           y.validJD = 0;
8224           y.M = 1;
8225           y.D = 1;
8226           computeJD(&y);
8227           nDay = x.rJD - y.rJD + 0.5;
8228           if( zFmt[i]=='W' ){
8229             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
8230             wd = ((int)(x.rJD+0.5)) % 7;
8231             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
8232             j += 2;
8233           }else{
8234             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
8235             j += 3;
8236           }
8237           break;
8238         }
8239         case 'J': {
8240           sqlite3_snprintf(20, &z[j],"%.16g",x.rJD);
8241           j+=strlen(&z[j]);
8242           break;
8243         }
8244         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
8245         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
8246         case 's': {
8247           sqlite3_snprintf(30,&z[j],"%d",
8248                            (int)((x.rJD-2440587.5)*86400.0 + 0.5));
8249           j += strlen(&z[j]);
8250           break;
8251         }
8252         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
8253         case 'w':  z[j++] = (((int)(x.rJD+1.5)) % 7) + '0'; break;
8254         case 'Y':  sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=strlen(&z[j]);break;
8255         case '%':  z[j++] = '%'; break;
8256       }
8257     }
8258   }
8259   z[j] = 0;
8260   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
8261   if( z!=zBuf ){
8262     sqlite3_free(z);
8263   }
8264 }
8265
8266 /*
8267 ** current_time()
8268 **
8269 ** This function returns the same value as time('now').
8270 */
8271 static void ctimeFunc(
8272   sqlite3_context *context,
8273   int argc,
8274   sqlite3_value **argv
8275 ){
8276   sqlite3_value *pVal = sqlite3ValueNew(0);
8277   if( pVal ){
8278     sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
8279     timeFunc(context, 1, &pVal);
8280     sqlite3ValueFree(pVal);
8281   }
8282 }
8283
8284 /*
8285 ** current_date()
8286 **
8287 ** This function returns the same value as date('now').
8288 */
8289 static void cdateFunc(
8290   sqlite3_context *context,
8291   int argc,
8292   sqlite3_value **argv
8293 ){
8294   sqlite3_value *pVal = sqlite3ValueNew(0);
8295   if( pVal ){
8296     sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
8297     dateFunc(context, 1, &pVal);
8298     sqlite3ValueFree(pVal);
8299   }
8300 }
8301
8302 /*
8303 ** current_timestamp()
8304 **
8305 ** This function returns the same value as datetime('now').
8306 */
8307 static void ctimestampFunc(
8308   sqlite3_context *context,
8309   int argc,
8310   sqlite3_value **argv
8311 ){
8312   sqlite3_value *pVal = sqlite3ValueNew(0);
8313   if( pVal ){
8314     sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
8315     datetimeFunc(context, 1, &pVal);
8316     sqlite3ValueFree(pVal);
8317   }
8318 }
8319 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
8320
8321 #ifdef SQLITE_OMIT_DATETIME_FUNCS
8322 /*
8323 ** If the library is compiled to omit the full-scale date and time
8324 ** handling (to get a smaller binary), the following minimal version
8325 ** of the functions current_time(), current_date() and current_timestamp()
8326 ** are included instead. This is to support column declarations that
8327 ** include "DEFAULT CURRENT_TIME" etc.
8328 **
8329 ** This function uses the C-library functions time(), gmtime()
8330 ** and strftime(). The format string to pass to strftime() is supplied
8331 ** as the user-data for the function.
8332 */
8333 static void currentTimeFunc(
8334   sqlite3_context *context,
8335   int argc,
8336   sqlite3_value **argv
8337 ){
8338   time_t t;
8339   char *zFormat = (char *)sqlite3_user_data(context);
8340   char zBuf[20];
8341
8342   time(&t);
8343 #ifdef SQLITE_TEST
8344   {
8345     extern int sqlite3_current_time;  /* See os_XXX.c */
8346     if( sqlite3_current_time ){
8347       t = sqlite3_current_time;
8348     }
8349   }
8350 #endif
8351
8352 #ifdef HAVE_GMTIME_R
8353   {
8354     struct tm sNow;
8355     gmtime_r(&t, &sNow);
8356     strftime(zBuf, 20, zFormat, &sNow);
8357   }
8358 #else
8359   {
8360     struct tm *pTm;
8361     sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
8362     pTm = gmtime(&t);
8363     strftime(zBuf, 20, zFormat, pTm);
8364     sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
8365   }
8366 #endif
8367
8368   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
8369 }
8370 #endif
8371
8372 /*
8373 ** This function registered all of the above C functions as SQL
8374 ** functions.  This should be the only routine in this file with
8375 ** external linkage.
8376 */
8377 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(sqlite3 *db){
8378 #ifndef SQLITE_OMIT_DATETIME_FUNCS
8379   static const struct {
8380      char *zName;
8381      int nArg;
8382      void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
8383   } aFuncs[] = {
8384     { "julianday", -1, juliandayFunc   },
8385     { "date",      -1, dateFunc        },
8386     { "time",      -1, timeFunc        },
8387     { "datetime",  -1, datetimeFunc    },
8388     { "strftime",  -1, strftimeFunc    },
8389     { "current_time",       0, ctimeFunc      },
8390     { "current_timestamp",  0, ctimestampFunc },
8391     { "current_date",       0, cdateFunc      },
8392   };
8393   int i;
8394
8395   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
8396     sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
8397         SQLITE_UTF8, (void *)(db->pVfs), aFuncs[i].xFunc, 0, 0);
8398   }
8399 #else
8400   static const struct {
8401      char *zName;
8402      char *zFormat;
8403   } aFuncs[] = {
8404     { "current_time", "%H:%M:%S" },
8405     { "current_date", "%Y-%m-%d" },
8406     { "current_timestamp", "%Y-%m-%d %H:%M:%S" }
8407   };
8408   int i;
8409
8410   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
8411     sqlite3CreateFunc(db, aFuncs[i].zName, 0, SQLITE_UTF8, 
8412         aFuncs[i].zFormat, currentTimeFunc, 0, 0);
8413   }
8414 #endif
8415 }
8416
8417 /************** End of date.c ************************************************/
8418 /************** Begin file os.c **********************************************/
8419  /*
8420 ** 2005 November 29
8421 **
8422 ** The author disclaims copyright to this source code.  In place of
8423 ** a legal notice, here is a blessing:
8424 **
8425 **    May you do good and not evil.
8426 **    May you find forgiveness for yourself and forgive others.
8427 **    May you share freely, never taking more than you give.
8428 **
8429 ******************************************************************************
8430 **
8431 ** This file contains OS interface code that is common to all
8432 ** architectures.
8433 */
8434 #define _SQLITE_OS_C_ 1
8435 #undef _SQLITE_OS_C_
8436
8437 /*
8438 ** The default SQLite sqlite3_vfs implementations do not allocate
8439 ** memory (actually, os_unix.c allocates a small amount of memory
8440 ** from within OsOpen()), but some third-party implementations may.
8441 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
8442 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
8443 **
8444 ** The following functions are instrumented for malloc() failure 
8445 ** testing:
8446 **
8447 **     sqlite3OsOpen()
8448 **     sqlite3OsRead()
8449 **     sqlite3OsWrite()
8450 **     sqlite3OsSync()
8451 **     sqlite3OsLock()
8452 **
8453 */
8454 #ifdef SQLITE_TEST
8455   #define DO_OS_MALLOC_TEST if (1) {            \
8456     void *pTstAlloc = sqlite3_malloc(10);       \
8457     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;  \
8458     sqlite3_free(pTstAlloc);                    \
8459   }
8460 #else
8461   #define DO_OS_MALLOC_TEST
8462 #endif
8463
8464 /*
8465 ** The following routines are convenience wrappers around methods
8466 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
8467 ** of this would be completely automatic if SQLite were coded using
8468 ** C++ instead of plain old C.
8469 */
8470 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
8471   int rc = SQLITE_OK;
8472   if( pId->pMethods ){
8473     rc = pId->pMethods->xClose(pId);
8474     pId->pMethods = 0;
8475   }
8476   return rc;
8477 }
8478 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
8479   DO_OS_MALLOC_TEST;
8480   return id->pMethods->xRead(id, pBuf, amt, offset);
8481 }
8482 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
8483   DO_OS_MALLOC_TEST;
8484   return id->pMethods->xWrite(id, pBuf, amt, offset);
8485 }
8486 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
8487   return id->pMethods->xTruncate(id, size);
8488 }
8489 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
8490   DO_OS_MALLOC_TEST;
8491   return id->pMethods->xSync(id, flags);
8492 }
8493 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
8494   return id->pMethods->xFileSize(id, pSize);
8495 }
8496 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
8497   DO_OS_MALLOC_TEST;
8498   return id->pMethods->xLock(id, lockType);
8499 }
8500 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
8501   return id->pMethods->xUnlock(id, lockType);
8502 }
8503 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id){
8504   return id->pMethods->xCheckReservedLock(id);
8505 }
8506 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
8507   return id->pMethods->xFileControl(id,op,pArg);
8508 }
8509
8510 #ifdef SQLITE_TEST
8511   /* The following two variables are used to override the values returned
8512   ** by the xSectorSize() and xDeviceCharacteristics() vfs methods for
8513   ** testing purposes. They are usually set by a test command implemented
8514   ** in test6.c.
8515   */
8516   int sqlite3_test_sector_size = 0;
8517   int sqlite3_test_device_characteristics = 0;
8518   int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
8519     int dc = id->pMethods->xDeviceCharacteristics(id);
8520     return dc | sqlite3_test_device_characteristics;
8521   }
8522   int sqlite3OsSectorSize(sqlite3_file *id){
8523     if( sqlite3_test_sector_size==0 ){
8524       int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
8525       return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
8526     }
8527     return sqlite3_test_sector_size;
8528   }
8529 #else
8530   int sqlite3OsSectorSize(sqlite3_file *id){
8531     int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
8532     return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
8533   }
8534   int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
8535     return id->pMethods->xDeviceCharacteristics(id);
8536   }
8537 #endif
8538
8539 /*
8540 ** The next group of routines are convenience wrappers around the
8541 ** VFS methods.
8542 */
8543 SQLITE_PRIVATE int sqlite3OsOpen(
8544   sqlite3_vfs *pVfs, 
8545   const char *zPath, 
8546   sqlite3_file *pFile, 
8547   int flags, 
8548   int *pFlagsOut
8549 ){
8550   DO_OS_MALLOC_TEST;
8551   return pVfs->xOpen(pVfs, zPath, pFile, flags, pFlagsOut);
8552 }
8553 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
8554   return pVfs->xDelete(pVfs, zPath, dirSync);
8555 }
8556 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *pVfs, const char *zPath, int flags){
8557   return pVfs->xAccess(pVfs, zPath, flags);
8558 }
8559 SQLITE_PRIVATE int sqlite3OsGetTempname(sqlite3_vfs *pVfs, int nBufOut, char *zBufOut){
8560   return pVfs->xGetTempname(pVfs, nBufOut, zBufOut);
8561 }
8562 SQLITE_PRIVATE int sqlite3OsFullPathname(
8563   sqlite3_vfs *pVfs, 
8564   const char *zPath, 
8565   int nPathOut, 
8566   char *zPathOut
8567 ){
8568   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
8569 }
8570 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
8571   return pVfs->xDlOpen(pVfs, zPath);
8572 }
8573 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
8574   pVfs->xDlError(pVfs, nByte, zBufOut);
8575 }
8576 SQLITE_PRIVATE void *sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
8577   return pVfs->xDlSym(pVfs, pHandle, zSymbol);
8578 }
8579 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
8580   pVfs->xDlClose(pVfs, pHandle);
8581 }
8582 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
8583   return pVfs->xRandomness(pVfs, nByte, zBufOut);
8584 }
8585 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
8586   return pVfs->xSleep(pVfs, nMicro);
8587 }
8588 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
8589   return pVfs->xCurrentTime(pVfs, pTimeOut);
8590 }
8591
8592 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
8593   sqlite3_vfs *pVfs, 
8594   const char *zFile, 
8595   sqlite3_file **ppFile, 
8596   int flags,
8597   int *pOutFlags
8598 ){
8599   int rc = SQLITE_NOMEM;
8600   sqlite3_file *pFile;
8601   pFile = (sqlite3_file *)sqlite3_malloc(pVfs->szOsFile);
8602   if( pFile ){
8603     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
8604     if( rc!=SQLITE_OK ){
8605       sqlite3_free(pFile);
8606     }else{
8607       *ppFile = pFile;
8608     }
8609   }
8610   return rc;
8611 }
8612 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
8613   int rc = SQLITE_OK;
8614   if( pFile ){
8615     rc = sqlite3OsClose(pFile);
8616     sqlite3_free(pFile);
8617   }
8618   return rc;
8619 }
8620
8621 /*
8622 ** The list of all registered VFS implementations.  This list is
8623 ** initialized to the single VFS returned by sqlite3OsDefaultVfs()
8624 ** upon the first call to sqlite3_vfs_find().
8625 */
8626 static sqlite3_vfs *vfsList = 0;
8627
8628 /*
8629 ** Locate a VFS by name.  If no name is given, simply return the
8630 ** first VFS on the list.
8631 */
8632 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
8633   sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
8634   sqlite3_vfs *pVfs = 0;
8635   static int isInit = 0;
8636   sqlite3_mutex_enter(mutex);
8637   if( !isInit ){
8638     vfsList = sqlite3OsDefaultVfs();
8639     isInit = 1;
8640   }
8641   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
8642     if( zVfs==0 ) break;
8643     if( strcmp(zVfs, pVfs->zName)==0 ) break;
8644   }
8645   sqlite3_mutex_leave(mutex);
8646   return pVfs;
8647 }
8648
8649 /*
8650 ** Unlink a VFS from the linked list
8651 */
8652 static void vfsUnlink(sqlite3_vfs *pVfs){
8653   assert( sqlite3_mutex_held(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER)) );
8654   if( pVfs==0 ){
8655     /* No-op */
8656   }else if( vfsList==pVfs ){
8657     vfsList = pVfs->pNext;
8658   }else if( vfsList ){
8659     sqlite3_vfs *p = vfsList;
8660     while( p->pNext && p->pNext!=pVfs ){
8661       p = p->pNext;
8662     }
8663     if( p->pNext==pVfs ){
8664       p->pNext = pVfs->pNext;
8665     }
8666   }
8667 }
8668
8669 /*
8670 ** Register a VFS with the system.  It is harmless to register the same
8671 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
8672 ** true.
8673 */
8674 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
8675   sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
8676   sqlite3_vfs_find(0);  /* Make sure we are initialized */
8677   sqlite3_mutex_enter(mutex);
8678   vfsUnlink(pVfs);
8679   if( makeDflt || vfsList==0 ){
8680     pVfs->pNext = vfsList;
8681     vfsList = pVfs;
8682   }else{
8683     pVfs->pNext = vfsList->pNext;
8684     vfsList->pNext = pVfs;
8685   }
8686   assert(vfsList);
8687   sqlite3_mutex_leave(mutex);
8688   return SQLITE_OK;
8689 }
8690
8691 /*
8692 ** Unregister a VFS so that it is no longer accessible.
8693 */
8694 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
8695   sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
8696   sqlite3_mutex_enter(mutex);
8697   vfsUnlink(pVfs);
8698   sqlite3_mutex_leave(mutex);
8699   return SQLITE_OK;
8700 }
8701
8702 /************** End of os.c **************************************************/
8703 /************** Begin file mem1.c ********************************************/
8704 /*
8705 ** 2007 August 14
8706 **
8707 ** The author disclaims copyright to this source code.  In place of
8708 ** a legal notice, here is a blessing:
8709 **
8710 **    May you do good and not evil.
8711 **    May you find forgiveness for yourself and forgive others.
8712 **    May you share freely, never taking more than you give.
8713 **
8714 *************************************************************************
8715 ** This file contains the C functions that implement a memory
8716 ** allocation subsystem for use by SQLite.  
8717 **
8718 ** $Id: mem1.c,v 1.14 2007/11/29 18:36:49 drh Exp $
8719 */
8720
8721 /*
8722 ** This version of the memory allocator is the default.  It is
8723 ** used when no other memory allocator is specified using compile-time
8724 ** macros.
8725 */
8726 #if !defined(SQLITE_MEMDEBUG) && !defined(SQLITE_MEMORY_SIZE) \
8727      && !defined(SQLITE_MMAP_HEAP_SIZE)
8728
8729 /*
8730 ** We will eventually construct multiple memory allocation subsystems
8731 ** suitable for use in various contexts:
8732 **
8733 **    *  Normal multi-threaded builds
8734 **    *  Normal single-threaded builds
8735 **    *  Debugging builds
8736 **
8737 ** This initial version is suitable for use in normal multi-threaded
8738 ** builds.  We envision that alternative versions will be stored in
8739 ** separate source files.  #ifdefs will be used to select the code from
8740 ** one of the various memN.c source files for use in any given build.
8741 */
8742
8743 /*
8744 ** All of the static variables used by this module are collected
8745 ** into a single structure named "mem".  This is to keep the
8746 ** static variables organized and to reduce namespace pollution
8747 ** when this module is combined with other in the amalgamation.
8748 */
8749 static struct {
8750   /*
8751   ** The alarm callback and its arguments.  The mem.mutex lock will
8752   ** be held while the callback is running.  Recursive calls into
8753   ** the memory subsystem are allowed, but no new callbacks will be
8754   ** issued.  The alarmBusy variable is set to prevent recursive
8755   ** callbacks.
8756   */
8757   sqlite3_int64 alarmThreshold;
8758   void (*alarmCallback)(void*, sqlite3_int64,int);
8759   void *alarmArg;
8760   int alarmBusy;
8761   
8762   /*
8763   ** Mutex to control access to the memory allocation subsystem.
8764   */
8765   sqlite3_mutex *mutex;
8766   
8767   /*
8768   ** Current allocation and high-water mark.
8769   */
8770   sqlite3_int64 nowUsed;
8771   sqlite3_int64 mxUsed;
8772   
8773  
8774 } mem;
8775
8776 /*
8777 ** Enter the mutex mem.mutex. Allocate it if it is not already allocated.
8778 */
8779 static void enterMem(void){
8780   if( mem.mutex==0 ){
8781     mem.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM);
8782   }
8783   sqlite3_mutex_enter(mem.mutex);
8784 }
8785
8786 /*
8787 ** Return the amount of memory currently checked out.
8788 */
8789 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
8790   sqlite3_int64 n;
8791   enterMem();
8792   n = mem.nowUsed;
8793   sqlite3_mutex_leave(mem.mutex);  
8794   return n;
8795 }
8796
8797 /*
8798 ** Return the maximum amount of memory that has ever been
8799 ** checked out since either the beginning of this process
8800 ** or since the most recent reset.
8801 */
8802 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
8803   sqlite3_int64 n;
8804   enterMem();
8805   n = mem.mxUsed;
8806   if( resetFlag ){
8807     mem.mxUsed = mem.nowUsed;
8808   }
8809   sqlite3_mutex_leave(mem.mutex);  
8810   return n;
8811 }
8812
8813 /*
8814 ** Change the alarm callback
8815 */
8816 SQLITE_API int sqlite3_memory_alarm(
8817   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
8818   void *pArg,
8819   sqlite3_int64 iThreshold
8820 ){
8821   enterMem();
8822   mem.alarmCallback = xCallback;
8823   mem.alarmArg = pArg;
8824   mem.alarmThreshold = iThreshold;
8825   sqlite3_mutex_leave(mem.mutex);
8826   return SQLITE_OK;
8827 }
8828
8829 /*
8830 ** Trigger the alarm 
8831 */
8832 static void sqlite3MemsysAlarm(int nByte){
8833   void (*xCallback)(void*,sqlite3_int64,int);
8834   sqlite3_int64 nowUsed;
8835   void *pArg;
8836   if( mem.alarmCallback==0 || mem.alarmBusy  ) return;
8837   mem.alarmBusy = 1;
8838   xCallback = mem.alarmCallback;
8839   nowUsed = mem.nowUsed;
8840   pArg = mem.alarmArg;
8841   sqlite3_mutex_leave(mem.mutex);
8842   xCallback(pArg, nowUsed, nByte);
8843   sqlite3_mutex_enter(mem.mutex);
8844   mem.alarmBusy = 0;
8845 }
8846
8847 /*
8848 ** Allocate nBytes of memory
8849 */
8850 SQLITE_API void *sqlite3_malloc(int nBytes){
8851   sqlite3_int64 *p = 0;
8852   if( nBytes>0 ){
8853     enterMem();
8854     if( mem.alarmCallback!=0 && mem.nowUsed+nBytes>=mem.alarmThreshold ){
8855       sqlite3MemsysAlarm(nBytes);
8856     }
8857     p = malloc(nBytes+8);
8858     if( p==0 ){
8859       sqlite3MemsysAlarm(nBytes);
8860       p = malloc(nBytes+8);
8861     }
8862     if( p ){
8863       p[0] = nBytes;
8864       p++;
8865       mem.nowUsed += nBytes;
8866       if( mem.nowUsed>mem.mxUsed ){
8867         mem.mxUsed = mem.nowUsed;
8868       }
8869     }
8870     sqlite3_mutex_leave(mem.mutex);
8871   }
8872   return (void*)p; 
8873 }
8874
8875 /*
8876 ** Free memory.
8877 */
8878 SQLITE_API void sqlite3_free(void *pPrior){
8879   sqlite3_int64 *p;
8880   int nByte;
8881   if( pPrior==0 ){
8882     return;
8883   }
8884   assert( mem.mutex!=0 );
8885   p = pPrior;
8886   p--;
8887   nByte = (int)*p;
8888   sqlite3_mutex_enter(mem.mutex);
8889   mem.nowUsed -= nByte;
8890   free(p);
8891   sqlite3_mutex_leave(mem.mutex);  
8892 }
8893
8894 /*
8895 ** Change the size of an existing memory allocation
8896 */
8897 SQLITE_API void *sqlite3_realloc(void *pPrior, int nBytes){
8898   int nOld;
8899   sqlite3_int64 *p;
8900   if( pPrior==0 ){
8901     return sqlite3_malloc(nBytes);
8902   }
8903   if( nBytes<=0 ){
8904     sqlite3_free(pPrior);
8905     return 0;
8906   }
8907   p = pPrior;
8908   p--;
8909   nOld = (int)p[0];
8910   assert( mem.mutex!=0 );
8911   sqlite3_mutex_enter(mem.mutex);
8912   if( mem.nowUsed+nBytes-nOld>=mem.alarmThreshold ){
8913     sqlite3MemsysAlarm(nBytes-nOld);
8914   }
8915   p = realloc(p, nBytes+8);
8916   if( p==0 ){
8917     sqlite3MemsysAlarm(nBytes);
8918     p = pPrior;
8919     p--;
8920     p = realloc(p, nBytes+8);
8921   }
8922   if( p ){
8923     p[0] = nBytes;
8924     p++;
8925     mem.nowUsed += nBytes-nOld;
8926     if( mem.nowUsed>mem.mxUsed ){
8927       mem.mxUsed = mem.nowUsed;
8928     }
8929   }
8930   sqlite3_mutex_leave(mem.mutex);
8931   return (void*)p;
8932 }
8933
8934 #endif /* !SQLITE_MEMDEBUG && !SQLITE_OMIT_MEMORY_ALLOCATION */
8935
8936 /************** End of mem1.c ************************************************/
8937 /************** Begin file mem2.c ********************************************/
8938 /*
8939 ** 2007 August 15
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 ** This file contains the C functions that implement a memory
8950 ** allocation subsystem for use by SQLite.  
8951 **
8952 ** $Id: mem2.c,v 1.18 2007/11/29 18:36:49 drh Exp $
8953 */
8954
8955 /*
8956 ** This version of the memory allocator is used only if the
8957 ** SQLITE_MEMDEBUG macro is defined and SQLITE_OMIT_MEMORY_ALLOCATION
8958 ** is not defined.
8959 */
8960 #if defined(SQLITE_MEMDEBUG)
8961
8962 /*
8963 ** We will eventually construct multiple memory allocation subsystems
8964 ** suitable for use in various contexts:
8965 **
8966 **    *  Normal multi-threaded builds
8967 **    *  Normal single-threaded builds
8968 **    *  Debugging builds
8969 **
8970 ** This version is suitable for use in debugging builds.
8971 **
8972 ** Features:
8973 **
8974 **    * Every allocate has guards at both ends.
8975 **    * New allocations are initialized with randomness
8976 **    * Allocations are overwritten with randomness when freed
8977 **    * Optional logs of malloc activity generated
8978 **    * Summary of outstanding allocations with backtraces to the
8979 **      point of allocation.
8980 **    * The ability to simulate memory allocation failure
8981 */
8982
8983 /*
8984 ** The backtrace functionality is only available with GLIBC
8985 */
8986 #ifdef __GLIBC__
8987   extern int backtrace(void**,int);
8988   extern void backtrace_symbols_fd(void*const*,int,int);
8989 #else
8990 # define backtrace(A,B) 0
8991 # define backtrace_symbols_fd(A,B,C)
8992 #endif
8993
8994 /*
8995 ** Each memory allocation looks like this:
8996 **
8997 **  ------------------------------------------------------------------------
8998 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
8999 **  ------------------------------------------------------------------------
9000 **
9001 ** The application code sees only a pointer to the allocation.  We have
9002 ** to back up from the allocation pointer to find the MemBlockHdr.  The
9003 ** MemBlockHdr tells us the size of the allocation and the number of
9004 ** backtrace pointers.  There is also a guard word at the end of the
9005 ** MemBlockHdr.
9006 */
9007 struct MemBlockHdr {
9008   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
9009   int iSize;                          /* Size of this allocation */
9010   char nBacktrace;                    /* Number of backtraces on this alloc */
9011   char nBacktraceSlots;               /* Available backtrace slots */
9012   short nTitle;                       /* Bytes of title; includes '\0' */
9013   int iForeGuard;                     /* Guard word for sanity */
9014 };
9015
9016 /*
9017 ** Guard words
9018 */
9019 #define FOREGUARD 0x80F5E153
9020 #define REARGUARD 0xE4676B53
9021
9022 /*
9023 ** Number of malloc size increments to track.
9024 */
9025 #define NCSIZE  1000
9026
9027 /*
9028 ** All of the static variables used by this module are collected
9029 ** into a single structure named "mem".  This is to keep the
9030 ** static variables organized and to reduce namespace pollution
9031 ** when this module is combined with other in the amalgamation.
9032 */
9033 static struct {
9034   /*
9035   ** The alarm callback and its arguments.  The mem.mutex lock will
9036   ** be held while the callback is running.  Recursive calls into
9037   ** the memory subsystem are allowed, but no new callbacks will be
9038   ** issued.  The alarmBusy variable is set to prevent recursive
9039   ** callbacks.
9040   */
9041   sqlite3_int64 alarmThreshold;
9042   void (*alarmCallback)(void*, sqlite3_int64, int);
9043   void *alarmArg;
9044   int alarmBusy;
9045   
9046   /*
9047   ** Mutex to control access to the memory allocation subsystem.
9048   */
9049   sqlite3_mutex *mutex;
9050   
9051   /*
9052   ** Current allocation and high-water mark.
9053   */
9054   sqlite3_int64 nowUsed;
9055   sqlite3_int64 mxUsed;
9056   
9057   /*
9058   ** Head and tail of a linked list of all outstanding allocations
9059   */
9060   struct MemBlockHdr *pFirst;
9061   struct MemBlockHdr *pLast;
9062   
9063   /*
9064   ** The number of levels of backtrace to save in new allocations.
9065   */
9066   int nBacktrace;
9067
9068   /*
9069   ** Title text to insert in front of each block
9070   */
9071   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
9072   char zTitle[100];  /* The title text */
9073
9074   /*
9075   ** These values are used to simulate malloc failures.  When
9076   ** iFail is 1, simulate a malloc failures and reset the value
9077   ** to iReset.
9078   */
9079   int iFail;    /* Decrement and fail malloc when this is 1 */
9080   int iReset;   /* When malloc fails set iiFail to this value */
9081   int iFailCnt;         /* Number of failures */
9082   int iBenignFailCnt;   /* Number of benign failures */
9083   int iNextIsBenign;    /* True if the next call to malloc may fail benignly */
9084   int iIsBenign;        /* All malloc calls may fail benignly */
9085
9086   /* 
9087   ** sqlite3MallocDisallow() increments the following counter.
9088   ** sqlite3MallocAllow() decrements it.
9089   */
9090   int disallow; /* Do not allow memory allocation */
9091
9092   /*
9093   ** Gather statistics on the sizes of memory allocations.
9094   ** sizeCnt[i] is the number of allocation attempts of i*8
9095   ** bytes.  i==NCSIZE is the number of allocation attempts for
9096   ** sizes more than NCSIZE*8 bytes.
9097   */
9098   int sizeCnt[NCSIZE];
9099
9100 } mem;
9101
9102
9103 /*
9104 ** Enter the mutex mem.mutex. Allocate it if it is not already allocated.
9105 */
9106 static void enterMem(void){
9107   if( mem.mutex==0 ){
9108     mem.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM);
9109   }
9110   sqlite3_mutex_enter(mem.mutex);
9111 }
9112
9113 /*
9114 ** Return the amount of memory currently checked out.
9115 */
9116 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
9117   sqlite3_int64 n;
9118   enterMem();
9119   n = mem.nowUsed;
9120   sqlite3_mutex_leave(mem.mutex);  
9121   return n;
9122 }
9123
9124 /*
9125 ** Return the maximum amount of memory that has ever been
9126 ** checked out since either the beginning of this process
9127 ** or since the most recent reset.
9128 */
9129 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
9130   sqlite3_int64 n;
9131   enterMem();
9132   n = mem.mxUsed;
9133   if( resetFlag ){
9134     mem.mxUsed = mem.nowUsed;
9135   }
9136   sqlite3_mutex_leave(mem.mutex);  
9137   return n;
9138 }
9139
9140 /*
9141 ** Change the alarm callback
9142 */
9143 SQLITE_API int sqlite3_memory_alarm(
9144   void(*xCallback)(void *pArg, sqlite3_int64 used, int N),
9145   void *pArg,
9146   sqlite3_int64 iThreshold
9147 ){
9148   enterMem();
9149   mem.alarmCallback = xCallback;
9150   mem.alarmArg = pArg;
9151   mem.alarmThreshold = iThreshold;
9152   sqlite3_mutex_leave(mem.mutex);
9153   return SQLITE_OK;
9154 }
9155
9156 /*
9157 ** Trigger the alarm 
9158 */
9159 static void sqlite3MemsysAlarm(int nByte){
9160   void (*xCallback)(void*,sqlite3_int64,int);
9161   sqlite3_int64 nowUsed;
9162   void *pArg;
9163   if( mem.alarmCallback==0 || mem.alarmBusy  ) return;
9164   mem.alarmBusy = 1;
9165   xCallback = mem.alarmCallback;
9166   nowUsed = mem.nowUsed;
9167   pArg = mem.alarmArg;
9168   sqlite3_mutex_leave(mem.mutex);
9169   xCallback(pArg, nowUsed, nByte);
9170   sqlite3_mutex_enter(mem.mutex);
9171   mem.alarmBusy = 0;
9172 }
9173
9174 /*
9175 ** Given an allocation, find the MemBlockHdr for that allocation.
9176 **
9177 ** This routine checks the guards at either end of the allocation and
9178 ** if they are incorrect it asserts.
9179 */
9180 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
9181   struct MemBlockHdr *p;
9182   int *pInt;
9183
9184   p = (struct MemBlockHdr*)pAllocation;
9185   p--;
9186   assert( p->iForeGuard==FOREGUARD );
9187   assert( (p->iSize & 3)==0 );
9188   pInt = (int*)pAllocation;
9189   assert( pInt[p->iSize/sizeof(int)]==REARGUARD );
9190   return p;
9191 }
9192
9193 /*
9194 ** This routine is called once the first time a simulated memory
9195 ** failure occurs.  The sole purpose of this routine is to provide
9196 ** a convenient place to set a debugger breakpoint when debugging
9197 ** errors related to malloc() failures.
9198 */
9199 static void sqlite3MemsysFailed(void){
9200   mem.iFailCnt = 0;
9201   mem.iBenignFailCnt = 0;
9202 }
9203
9204 /*
9205 ** Allocate nByte bytes of memory.
9206 */
9207 SQLITE_API void *sqlite3_malloc(int nByte){
9208   struct MemBlockHdr *pHdr;
9209   void **pBt;
9210   char *z;
9211   int *pInt;
9212   void *p = 0;
9213   int totalSize;
9214
9215   if( nByte>0 ){
9216     enterMem();
9217     assert( mem.disallow==0 );
9218     if( mem.alarmCallback!=0 && mem.nowUsed+nByte>=mem.alarmThreshold ){
9219       sqlite3MemsysAlarm(nByte);
9220     }
9221     nByte = (nByte+3)&~3;
9222     if( nByte/8>NCSIZE-1 ){
9223       mem.sizeCnt[NCSIZE-1]++;
9224     }else{
9225       mem.sizeCnt[nByte/8]++;
9226     }
9227     totalSize = nByte + sizeof(*pHdr) + sizeof(int) +
9228                  mem.nBacktrace*sizeof(void*) + mem.nTitle;
9229     if( mem.iFail>0 ){
9230       if( mem.iFail==1 ){
9231         p = 0;
9232         mem.iFail = mem.iReset;
9233         if( mem.iFailCnt==0 ){
9234           sqlite3MemsysFailed();  /* A place to set a breakpoint */
9235         }
9236         mem.iFailCnt++;
9237         if( mem.iNextIsBenign || mem.iIsBenign ){
9238           mem.iBenignFailCnt++;
9239         }
9240       }else{
9241         p = malloc(totalSize);
9242         mem.iFail--;
9243       }
9244     }else{
9245       p = malloc(totalSize);
9246       if( p==0 ){
9247         sqlite3MemsysAlarm(nByte);
9248         p = malloc(totalSize);
9249       }
9250     }
9251     if( p ){
9252       z = p;
9253       pBt = (void**)&z[mem.nTitle];
9254       pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
9255       pHdr->pNext = 0;
9256       pHdr->pPrev = mem.pLast;
9257       if( mem.pLast ){
9258         mem.pLast->pNext = pHdr;
9259       }else{
9260         mem.pFirst = pHdr;
9261       }
9262       mem.pLast = pHdr;
9263       pHdr->iForeGuard = FOREGUARD;
9264       pHdr->nBacktraceSlots = mem.nBacktrace;
9265       pHdr->nTitle = mem.nTitle;
9266       if( mem.nBacktrace ){
9267         void *aAddr[40];
9268         pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
9269         memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
9270       }else{
9271         pHdr->nBacktrace = 0;
9272       }
9273       if( mem.nTitle ){
9274         memcpy(z, mem.zTitle, mem.nTitle);
9275       }
9276       pHdr->iSize = nByte;
9277       pInt = (int*)&pHdr[1];
9278       pInt[nByte/sizeof(int)] = REARGUARD;
9279       memset(pInt, 0x65, nByte);
9280       mem.nowUsed += nByte;
9281       if( mem.nowUsed>mem.mxUsed ){
9282         mem.mxUsed = mem.nowUsed;
9283       }
9284       p = (void*)pInt;
9285     }
9286     sqlite3_mutex_leave(mem.mutex);
9287   }
9288   mem.iNextIsBenign = 0;
9289   return p; 
9290 }
9291
9292 /*
9293 ** Free memory.
9294 */
9295 SQLITE_API void sqlite3_free(void *pPrior){
9296   struct MemBlockHdr *pHdr;
9297   void **pBt;
9298   char *z;
9299   if( pPrior==0 ){
9300     return;
9301   }
9302   assert( mem.mutex!=0 );
9303   pHdr = sqlite3MemsysGetHeader(pPrior);
9304   pBt = (void**)pHdr;
9305   pBt -= pHdr->nBacktraceSlots;
9306   sqlite3_mutex_enter(mem.mutex);
9307   mem.nowUsed -= pHdr->iSize;
9308   if( pHdr->pPrev ){
9309     assert( pHdr->pPrev->pNext==pHdr );
9310     pHdr->pPrev->pNext = pHdr->pNext;
9311   }else{
9312     assert( mem.pFirst==pHdr );
9313     mem.pFirst = pHdr->pNext;
9314   }
9315   if( pHdr->pNext ){
9316     assert( pHdr->pNext->pPrev==pHdr );
9317     pHdr->pNext->pPrev = pHdr->pPrev;
9318   }else{
9319     assert( mem.pLast==pHdr );
9320     mem.pLast = pHdr->pPrev;
9321   }
9322   z = (char*)pBt;
9323   z -= pHdr->nTitle;
9324   memset(z, 0x2b, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
9325                   pHdr->iSize + sizeof(int) + pHdr->nTitle);
9326   free(z);
9327   sqlite3_mutex_leave(mem.mutex);  
9328 }
9329
9330 /*
9331 ** Change the size of an existing memory allocation.
9332 **
9333 ** For this debugging implementation, we *always* make a copy of the
9334 ** allocation into a new place in memory.  In this way, if the 
9335 ** higher level code is using pointer to the old allocation, it is 
9336 ** much more likely to break and we are much more liking to find
9337 ** the error.
9338 */
9339 SQLITE_API void *sqlite3_realloc(void *pPrior, int nByte){
9340   struct MemBlockHdr *pOldHdr;
9341   void *pNew;
9342   if( pPrior==0 ){
9343     return sqlite3_malloc(nByte);
9344   }
9345   if( nByte<=0 ){
9346     sqlite3_free(pPrior);
9347     return 0;
9348   }
9349   assert( mem.disallow==0 );
9350   pOldHdr = sqlite3MemsysGetHeader(pPrior);
9351   pNew = sqlite3_malloc(nByte);
9352   if( pNew ){
9353     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
9354     if( nByte>pOldHdr->iSize ){
9355       memset(&((char*)pNew)[pOldHdr->iSize], 0x2b, nByte - pOldHdr->iSize);
9356     }
9357     sqlite3_free(pPrior);
9358   }
9359   return pNew;
9360 }
9361
9362 /*
9363 ** Set the number of backtrace levels kept for each allocation.
9364 ** A value of zero turns of backtracing.  The number is always rounded
9365 ** up to a multiple of 2.
9366 */
9367 SQLITE_API void sqlite3_memdebug_backtrace(int depth){
9368   if( depth<0 ){ depth = 0; }
9369   if( depth>20 ){ depth = 20; }
9370   depth = (depth+1)&0xfe;
9371   mem.nBacktrace = depth;
9372 }
9373
9374 /*
9375 ** Set the title string for subsequent allocations.
9376 */
9377 SQLITE_API void sqlite3_memdebug_settitle(const char *zTitle){
9378   int n = strlen(zTitle) + 1;
9379   enterMem();
9380   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
9381   memcpy(mem.zTitle, zTitle, n);
9382   mem.zTitle[n] = 0;
9383   mem.nTitle = (n+3)&~3;
9384   sqlite3_mutex_leave(mem.mutex);
9385 }
9386
9387 /*
9388 ** Open the file indicated and write a log of all unfreed memory 
9389 ** allocations into that log.
9390 */
9391 SQLITE_API void sqlite3_memdebug_dump(const char *zFilename){
9392   FILE *out;
9393   struct MemBlockHdr *pHdr;
9394   void **pBt;
9395   int i;
9396   out = fopen(zFilename, "w");
9397   if( out==0 ){
9398     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
9399                     zFilename);
9400     return;
9401   }
9402   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
9403     char *z = (char*)pHdr;
9404     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
9405     fprintf(out, "**** %d bytes at %p from %s ****\n", 
9406             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
9407     if( pHdr->nBacktrace ){
9408       fflush(out);
9409       pBt = (void**)pHdr;
9410       pBt -= pHdr->nBacktraceSlots;
9411       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
9412       fprintf(out, "\n");
9413     }
9414   }
9415   fprintf(out, "COUNTS:\n");
9416   for(i=0; i<NCSIZE-1; i++){
9417     if( mem.sizeCnt[i] ){
9418       fprintf(out, "   %3d: %d\n", i*8+8, mem.sizeCnt[i]);
9419     }
9420   }
9421   if( mem.sizeCnt[NCSIZE-1] ){
9422     fprintf(out, "  >%3d: %d\n", NCSIZE*8, mem.sizeCnt[NCSIZE-1]);
9423   }
9424   fclose(out);
9425 }
9426
9427 /*
9428 ** This routine is used to simulate malloc failures.
9429 **
9430 ** After calling this routine, there will be iFail successful
9431 ** memory allocations and then a failure.  If iRepeat is 1
9432 ** all subsequent memory allocations will fail.  If iRepeat is
9433 ** 0, only a single allocation will fail.  If iRepeat is negative
9434 ** then the previous setting for iRepeat is unchanged.
9435 **
9436 ** Each call to this routine overrides the previous.  To disable
9437 ** the simulated allocation failure mechanism, set iFail to -1.
9438 **
9439 ** This routine returns the number of simulated failures that have
9440 ** occurred since the previous call.
9441 */
9442 SQLITE_API int sqlite3_memdebug_fail(int iFail, int iRepeat, int *piBenign){
9443   int n = mem.iFailCnt;
9444   if( piBenign ){
9445     *piBenign = mem.iBenignFailCnt;
9446   }
9447   mem.iFail = iFail+1;
9448   if( iRepeat>=0 ){
9449     mem.iReset = iRepeat;
9450   }
9451   mem.iFailCnt = 0;
9452   mem.iBenignFailCnt = 0;
9453   return n;
9454 }
9455
9456 SQLITE_API int sqlite3_memdebug_pending(){
9457   return (mem.iFail-1);
9458 }
9459
9460 /*
9461 ** The following three functions are used to indicate to the test 
9462 ** infrastructure which malloc() calls may fail benignly without
9463 ** affecting functionality. This can happen when resizing hash tables 
9464 ** (failing to resize a hash-table is a performance hit, but not an 
9465 ** error) or sometimes during a rollback operation.
9466 **
9467 ** If the argument is true, sqlite3MallocBenignFailure() indicates that the
9468 ** next call to allocate memory may fail benignly.
9469 **
9470 ** If sqlite3MallocEnterBenignBlock() is called with a non-zero argument,
9471 ** then all memory allocations requested before the next call to
9472 ** sqlite3MallocLeaveBenignBlock() may fail benignly.
9473 */
9474 SQLITE_PRIVATE void sqlite3MallocBenignFailure(int isBenign){
9475   if( isBenign ){
9476     mem.iNextIsBenign = 1;
9477   }
9478 }
9479 SQLITE_PRIVATE void sqlite3MallocEnterBenignBlock(int isBenign){
9480   if( isBenign ){
9481     mem.iIsBenign = 1;
9482   }
9483 }
9484 SQLITE_PRIVATE void sqlite3MallocLeaveBenignBlock(){
9485   mem.iIsBenign = 0;
9486 }
9487
9488 /*
9489 ** The following two routines are used to assert that no memory
9490 ** allocations occur between one call and the next.  The use of
9491 ** these routines does not change the computed results in any way.
9492 ** These routines are like asserts.
9493 */
9494 SQLITE_PRIVATE void sqlite3MallocDisallow(void){
9495   assert( mem.mutex!=0 );
9496   sqlite3_mutex_enter(mem.mutex);
9497   mem.disallow++;
9498   sqlite3_mutex_leave(mem.mutex);
9499 }
9500 SQLITE_PRIVATE void sqlite3MallocAllow(void){
9501   assert( mem.mutex );
9502   sqlite3_mutex_enter(mem.mutex);
9503   assert( mem.disallow>0 );
9504   mem.disallow--;
9505   sqlite3_mutex_leave(mem.mutex);
9506 }
9507
9508 #endif /* SQLITE_MEMDEBUG && !SQLITE_OMIT_MEMORY_ALLOCATION */
9509
9510 /************** End of mem2.c ************************************************/
9511 /************** Begin file mem3.c ********************************************/
9512 /*
9513 ** 2007 October 14
9514 **
9515 ** The author disclaims copyright to this source code.  In place of
9516 ** a legal notice, here is a blessing:
9517 **
9518 **    May you do good and not evil.
9519 **    May you find forgiveness for yourself and forgive others.
9520 **    May you share freely, never taking more than you give.
9521 **
9522 *************************************************************************
9523 ** This file contains the C functions that implement a memory
9524 ** allocation subsystem for use by SQLite. 
9525 **
9526 ** This version of the memory allocation subsystem omits all
9527 ** use of malloc().  All dynamically allocatable memory is
9528 ** contained in a static array, mem.aPool[].  The size of this
9529 ** fixed memory pool is SQLITE_MEMORY_SIZE bytes.
9530 **
9531 ** This version of the memory allocation subsystem is used if
9532 ** and only if SQLITE_MEMORY_SIZE is defined.
9533 **
9534 ** $Id: mem3.c,v 1.7 2007/11/29 18:36:49 drh Exp $
9535 */
9536
9537 /*
9538 ** This version of the memory allocator is used only when 
9539 ** SQLITE_MEMORY_SIZE is defined.
9540 */
9541 #if defined(SQLITE_MEMORY_SIZE)
9542
9543 #ifdef SQLITE_MEMDEBUG
9544 # error  cannot define both SQLITE_MEMDEBUG and SQLITE_MEMORY_SIZE
9545 #endif
9546
9547 /*
9548 ** Maximum size (in Mem3Blocks) of a "small" chunk.
9549 */
9550 #define MX_SMALL 10
9551
9552
9553 /*
9554 ** Number of freelist hash slots
9555 */
9556 #define N_HASH  61
9557
9558 /*
9559 ** A memory allocation (also called a "chunk") consists of two or 
9560 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
9561 ** a header that is not returned to the user.
9562 **
9563 ** A chunk is two or more blocks that is either checked out or
9564 ** free.  The first block has format u.hdr.  u.hdr.size is the
9565 ** size of the allocation in blocks if the allocation is free.
9566 ** If the allocation is checked out, u.hdr.size is the negative
9567 ** of the size.  Similarly, u.hdr.prevSize is the size of the
9568 ** immediately previous allocation.
9569 **
9570 ** We often identify a chunk by its index in mem.aPool[].  When
9571 ** this is done, the chunk index refers to the second block of
9572 ** the chunk.  In this way, the first chunk has an index of 1.
9573 ** A chunk index of 0 means "no such chunk" and is the equivalent
9574 ** of a NULL pointer.
9575 **
9576 ** The second block of free chunks is of the form u.list.  The
9577 ** two fields form a double-linked list of chunks of related sizes.
9578 ** Pointers to the head of the list are stored in mem.aiSmall[] 
9579 ** for smaller chunks and mem.aiHash[] for larger chunks.
9580 **
9581 ** The second block of a chunk is user data if the chunk is checked 
9582 ** out.
9583 */
9584 typedef struct Mem3Block Mem3Block;
9585 struct Mem3Block {
9586   union {
9587     struct {
9588       int prevSize;   /* Size of previous chunk in Mem3Block elements */
9589       int size;       /* Size of current chunk in Mem3Block elements */
9590     } hdr;
9591     struct {
9592       int next;       /* Index in mem.aPool[] of next free chunk */
9593       int prev;       /* Index in mem.aPool[] of previous free chunk */
9594     } list;
9595   } u;
9596 };
9597
9598 /*
9599 ** All of the static variables used by this module are collected
9600 ** into a single structure named "mem".  This is to keep the
9601 ** static variables organized and to reduce namespace pollution
9602 ** when this module is combined with other in the amalgamation.
9603 */
9604 static struct {
9605   /*
9606   ** True if we are evaluating an out-of-memory callback.
9607   */
9608   int alarmBusy;
9609   
9610   /*
9611   ** Mutex to control access to the memory allocation subsystem.
9612   */
9613   sqlite3_mutex *mutex;
9614   
9615   /*
9616   ** The minimum amount of free space that we have seen.
9617   */
9618   int mnMaster;
9619
9620   /*
9621   ** iMaster is the index of the master chunk.  Most new allocations
9622   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
9623   ** of the current master.  iMaster is 0 if there is not master chunk.
9624   ** The master chunk is not in either the aiHash[] or aiSmall[].
9625   */
9626   int iMaster;
9627   int szMaster;
9628
9629   /*
9630   ** Array of lists of free blocks according to the block size 
9631   ** for smaller chunks, or a hash on the block size for larger
9632   ** chunks.
9633   */
9634   int aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
9635   int aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
9636
9637   /*
9638   ** Memory available for allocation
9639   */
9640   Mem3Block aPool[SQLITE_MEMORY_SIZE/sizeof(Mem3Block)+2];
9641 } mem;
9642
9643 /*
9644 ** Unlink the chunk at mem.aPool[i] from list it is currently
9645 ** on.  *pRoot is the list that i is a member of.
9646 */
9647 static void memsys3UnlinkFromList(int i, int *pRoot){
9648   int next = mem.aPool[i].u.list.next;
9649   int prev = mem.aPool[i].u.list.prev;
9650   assert( sqlite3_mutex_held(mem.mutex) );
9651   if( prev==0 ){
9652     *pRoot = next;
9653   }else{
9654     mem.aPool[prev].u.list.next = next;
9655   }
9656   if( next ){
9657     mem.aPool[next].u.list.prev = prev;
9658   }
9659   mem.aPool[i].u.list.next = 0;
9660   mem.aPool[i].u.list.prev = 0;
9661 }
9662
9663 /*
9664 ** Unlink the chunk at index i from 
9665 ** whatever list is currently a member of.
9666 */
9667 static void memsys3Unlink(int i){
9668   int size, hash;
9669   assert( sqlite3_mutex_held(mem.mutex) );
9670   size = mem.aPool[i-1].u.hdr.size;
9671   assert( size==mem.aPool[i+size-1].u.hdr.prevSize );
9672   assert( size>=2 );
9673   if( size <= MX_SMALL ){
9674     memsys3UnlinkFromList(i, &mem.aiSmall[size-2]);
9675   }else{
9676     hash = size % N_HASH;
9677     memsys3UnlinkFromList(i, &mem.aiHash[hash]);
9678   }
9679 }
9680
9681 /*
9682 ** Link the chunk at mem.aPool[i] so that is on the list rooted
9683 ** at *pRoot.
9684 */
9685 static void memsys3LinkIntoList(int i, int *pRoot){
9686   assert( sqlite3_mutex_held(mem.mutex) );
9687   mem.aPool[i].u.list.next = *pRoot;
9688   mem.aPool[i].u.list.prev = 0;
9689   if( *pRoot ){
9690     mem.aPool[*pRoot].u.list.prev = i;
9691   }
9692   *pRoot = i;
9693 }
9694
9695 /*
9696 ** Link the chunk at index i into either the appropriate
9697 ** small chunk list, or into the large chunk hash table.
9698 */
9699 static void memsys3Link(int i){
9700   int size, hash;
9701   assert( sqlite3_mutex_held(mem.mutex) );
9702   size = mem.aPool[i-1].u.hdr.size;
9703   assert( size==mem.aPool[i+size-1].u.hdr.prevSize );
9704   assert( size>=2 );
9705   if( size <= MX_SMALL ){
9706     memsys3LinkIntoList(i, &mem.aiSmall[size-2]);
9707   }else{
9708     hash = size % N_HASH;
9709     memsys3LinkIntoList(i, &mem.aiHash[hash]);
9710   }
9711 }
9712
9713 /*
9714 ** Enter the mutex mem.mutex. Allocate it if it is not already allocated.
9715 **
9716 ** Also:  Initialize the memory allocation subsystem the first time
9717 ** this routine is called.
9718 */
9719 static void memsys3Enter(void){
9720   if( mem.mutex==0 ){
9721     mem.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM);
9722     mem.aPool[0].u.hdr.size = SQLITE_MEMORY_SIZE/8;
9723     mem.aPool[SQLITE_MEMORY_SIZE/8].u.hdr.prevSize = SQLITE_MEMORY_SIZE/8;
9724     mem.iMaster = 1;
9725     mem.szMaster = SQLITE_MEMORY_SIZE/8;
9726     mem.mnMaster = mem.szMaster;
9727   }
9728   sqlite3_mutex_enter(mem.mutex);
9729 }
9730
9731 /*
9732 ** Return the amount of memory currently checked out.
9733 */
9734 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
9735   sqlite3_int64 n;
9736   memsys3Enter();
9737   n = SQLITE_MEMORY_SIZE - mem.szMaster*8;
9738   sqlite3_mutex_leave(mem.mutex);  
9739   return n;
9740 }
9741
9742 /*
9743 ** Return the maximum amount of memory that has ever been
9744 ** checked out since either the beginning of this process
9745 ** or since the most recent reset.
9746 */
9747 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
9748   sqlite3_int64 n;
9749   memsys3Enter();
9750   n = SQLITE_MEMORY_SIZE - mem.mnMaster*8;
9751   if( resetFlag ){
9752     mem.mnMaster = mem.szMaster;
9753   }
9754   sqlite3_mutex_leave(mem.mutex);  
9755   return n;
9756 }
9757
9758 /*
9759 ** Change the alarm callback.
9760 **
9761 ** This is a no-op for the static memory allocator.  The purpose
9762 ** of the memory alarm is to support sqlite3_soft_heap_limit().
9763 ** But with this memory allocator, the soft_heap_limit is really
9764 ** a hard limit that is fixed at SQLITE_MEMORY_SIZE.
9765 */
9766 SQLITE_API int sqlite3_memory_alarm(
9767   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
9768   void *pArg,
9769   sqlite3_int64 iThreshold
9770 ){
9771   return SQLITE_OK;
9772 }
9773
9774 /*
9775 ** Called when we are unable to satisfy an allocation of nBytes.
9776 */
9777 static void memsys3OutOfMemory(int nByte){
9778   if( !mem.alarmBusy ){
9779     mem.alarmBusy = 1;
9780     assert( sqlite3_mutex_held(mem.mutex) );
9781     sqlite3_mutex_leave(mem.mutex);
9782     sqlite3_release_memory(nByte);
9783     sqlite3_mutex_enter(mem.mutex);
9784     mem.alarmBusy = 0;
9785   }
9786 }
9787
9788 /*
9789 ** Return the size of an outstanding allocation, in bytes.  The
9790 ** size returned omits the 8-byte header overhead.  This only
9791 ** works for chunks that are currently checked out.
9792 */
9793 static int memsys3Size(void *p){
9794   Mem3Block *pBlock = (Mem3Block*)p;
9795   assert( pBlock[-1].u.hdr.size<0 );
9796   return (-1-pBlock[-1].u.hdr.size)*8;
9797 }
9798
9799 /*
9800 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
9801 ** size parameters for check-out and return a pointer to the 
9802 ** user portion of the chunk.
9803 */
9804 static void *memsys3Checkout(int i, int nBlock){
9805   assert( sqlite3_mutex_held(mem.mutex) );
9806   assert( mem.aPool[i-1].u.hdr.size==nBlock );
9807   assert( mem.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
9808   mem.aPool[i-1].u.hdr.size = -nBlock;
9809   mem.aPool[i+nBlock-1].u.hdr.prevSize = -nBlock;
9810   return &mem.aPool[i];
9811 }
9812
9813 /*
9814 ** Carve a piece off of the end of the mem.iMaster free chunk.
9815 ** Return a pointer to the new allocation.  Or, if the master chunk
9816 ** is not large enough, return 0.
9817 */
9818 static void *memsys3FromMaster(int nBlock){
9819   assert( sqlite3_mutex_held(mem.mutex) );
9820   assert( mem.szMaster>=nBlock );
9821   if( nBlock>=mem.szMaster-1 ){
9822     /* Use the entire master */
9823     void *p = memsys3Checkout(mem.iMaster, mem.szMaster);
9824     mem.iMaster = 0;
9825     mem.szMaster = 0;
9826     mem.mnMaster = 0;
9827     return p;
9828   }else{
9829     /* Split the master block.  Return the tail. */
9830     int newi;
9831     newi = mem.iMaster + mem.szMaster - nBlock;
9832     assert( newi > mem.iMaster+1 );
9833     mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.prevSize = -nBlock;
9834     mem.aPool[newi-1].u.hdr.size = -nBlock;
9835     mem.szMaster -= nBlock;
9836     mem.aPool[newi-1].u.hdr.prevSize = mem.szMaster;
9837     mem.aPool[mem.iMaster-1].u.hdr.size = mem.szMaster;
9838     if( mem.szMaster < mem.mnMaster ){
9839       mem.mnMaster = mem.szMaster;
9840     }
9841     return (void*)&mem.aPool[newi];
9842   }
9843 }
9844
9845 /*
9846 ** *pRoot is the head of a list of free chunks of the same size
9847 ** or same size hash.  In other words, *pRoot is an entry in either
9848 ** mem.aiSmall[] or mem.aiHash[].  
9849 **
9850 ** This routine examines all entries on the given list and tries
9851 ** to coalesce each entries with adjacent free chunks.  
9852 **
9853 ** If it sees a chunk that is larger than mem.iMaster, it replaces 
9854 ** the current mem.iMaster with the new larger chunk.  In order for
9855 ** this mem.iMaster replacement to work, the master chunk must be
9856 ** linked into the hash tables.  That is not the normal state of
9857 ** affairs, of course.  The calling routine must link the master
9858 ** chunk before invoking this routine, then must unlink the (possibly
9859 ** changed) master chunk once this routine has finished.
9860 */
9861 static void memsys3Merge(int *pRoot){
9862   int iNext, prev, size, i;
9863
9864   assert( sqlite3_mutex_held(mem.mutex) );
9865   for(i=*pRoot; i>0; i=iNext){
9866     iNext = mem.aPool[i].u.list.next;
9867     size = mem.aPool[i-1].u.hdr.size;
9868     assert( size>0 );
9869     if( mem.aPool[i-1].u.hdr.prevSize>0 ){
9870       memsys3UnlinkFromList(i, pRoot);
9871       prev = i - mem.aPool[i-1].u.hdr.prevSize;
9872       assert( prev>=0 );
9873       if( prev==iNext ){
9874         iNext = mem.aPool[prev].u.list.next;
9875       }
9876       memsys3Unlink(prev);
9877       size = i + size - prev;
9878       mem.aPool[prev-1].u.hdr.size = size;
9879       mem.aPool[prev+size-1].u.hdr.prevSize = size;
9880       memsys3Link(prev);
9881       i = prev;
9882     }
9883     if( size>mem.szMaster ){
9884       mem.iMaster = i;
9885       mem.szMaster = size;
9886     }
9887   }
9888 }
9889
9890 /*
9891 ** Return a block of memory of at least nBytes in size.
9892 ** Return NULL if unable.
9893 */
9894 static void *memsys3Malloc(int nByte){
9895   int i;
9896   int nBlock;
9897   int toFree;
9898
9899   assert( sqlite3_mutex_held(mem.mutex) );
9900   assert( sizeof(Mem3Block)==8 );
9901   if( nByte<=0 ){
9902     nBlock = 2;
9903   }else{
9904     nBlock = (nByte + 15)/8;
9905   }
9906   assert( nBlock >= 2 );
9907
9908   /* STEP 1:
9909   ** Look for an entry of the correct size in either the small
9910   ** chunk table or in the large chunk hash table.  This is
9911   ** successful most of the time (about 9 times out of 10).
9912   */
9913   if( nBlock <= MX_SMALL ){
9914     i = mem.aiSmall[nBlock-2];
9915     if( i>0 ){
9916       memsys3UnlinkFromList(i, &mem.aiSmall[nBlock-2]);
9917       return memsys3Checkout(i, nBlock);
9918     }
9919   }else{
9920     int hash = nBlock % N_HASH;
9921     for(i=mem.aiHash[hash]; i>0; i=mem.aPool[i].u.list.next){
9922       if( mem.aPool[i-1].u.hdr.size==nBlock ){
9923         memsys3UnlinkFromList(i, &mem.aiHash[hash]);
9924         return memsys3Checkout(i, nBlock);
9925       }
9926     }
9927   }
9928
9929   /* STEP 2:
9930   ** Try to satisfy the allocation by carving a piece off of the end
9931   ** of the master chunk.  This step usually works if step 1 fails.
9932   */
9933   if( mem.szMaster>=nBlock ){
9934     return memsys3FromMaster(nBlock);
9935   }
9936
9937
9938   /* STEP 3:  
9939   ** Loop through the entire memory pool.  Coalesce adjacent free
9940   ** chunks.  Recompute the master chunk as the largest free chunk.
9941   ** Then try again to satisfy the allocation by carving a piece off
9942   ** of the end of the master chunk.  This step happens very
9943   ** rarely (we hope!)
9944   */
9945   for(toFree=nBlock*16; toFree<SQLITE_MEMORY_SIZE*2; toFree *= 2){
9946     memsys3OutOfMemory(toFree);
9947     if( mem.iMaster ){
9948       memsys3Link(mem.iMaster);
9949       mem.iMaster = 0;
9950       mem.szMaster = 0;
9951     }
9952     for(i=0; i<N_HASH; i++){
9953       memsys3Merge(&mem.aiHash[i]);
9954     }
9955     for(i=0; i<MX_SMALL-1; i++){
9956       memsys3Merge(&mem.aiSmall[i]);
9957     }
9958     if( mem.szMaster ){
9959       memsys3Unlink(mem.iMaster);
9960       if( mem.szMaster>=nBlock ){
9961         return memsys3FromMaster(nBlock);
9962       }
9963     }
9964   }
9965
9966   /* If none of the above worked, then we fail. */
9967   return 0;
9968 }
9969
9970 /*
9971 ** Free an outstanding memory allocation.
9972 */
9973 void memsys3Free(void *pOld){
9974   Mem3Block *p = (Mem3Block*)pOld;
9975   int i;
9976   int size;
9977   assert( sqlite3_mutex_held(mem.mutex) );
9978   assert( p>mem.aPool && p<&mem.aPool[SQLITE_MEMORY_SIZE/8] );
9979   i = p - mem.aPool;
9980   size = -mem.aPool[i-1].u.hdr.size;
9981   assert( size>=2 );
9982   assert( mem.aPool[i+size-1].u.hdr.prevSize==-size );
9983   mem.aPool[i-1].u.hdr.size = size;
9984   mem.aPool[i+size-1].u.hdr.prevSize = size;
9985   memsys3Link(i);
9986
9987   /* Try to expand the master using the newly freed chunk */
9988   if( mem.iMaster ){
9989     while( mem.aPool[mem.iMaster-1].u.hdr.prevSize>0 ){
9990       size = mem.aPool[mem.iMaster-1].u.hdr.prevSize;
9991       mem.iMaster -= size;
9992       mem.szMaster += size;
9993       memsys3Unlink(mem.iMaster);
9994       mem.aPool[mem.iMaster-1].u.hdr.size = mem.szMaster;
9995       mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.prevSize = mem.szMaster;
9996     }
9997     while( mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.size>0 ){
9998       memsys3Unlink(mem.iMaster+mem.szMaster);
9999       mem.szMaster += mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.size;
10000       mem.aPool[mem.iMaster-1].u.hdr.size = mem.szMaster;
10001       mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.prevSize = mem.szMaster;
10002     }
10003   }
10004 }
10005
10006 /*
10007 ** Allocate nBytes of memory
10008 */
10009 SQLITE_API void *sqlite3_malloc(int nBytes){
10010   sqlite3_int64 *p = 0;
10011   if( nBytes>0 ){
10012     memsys3Enter();
10013     p = memsys3Malloc(nBytes);
10014     sqlite3_mutex_leave(mem.mutex);
10015   }
10016   return (void*)p; 
10017 }
10018
10019 /*
10020 ** Free memory.
10021 */
10022 SQLITE_API void sqlite3_free(void *pPrior){
10023   if( pPrior==0 ){
10024     return;
10025   }
10026   assert( mem.mutex!=0 );
10027   sqlite3_mutex_enter(mem.mutex);
10028   memsys3Free(pPrior);
10029   sqlite3_mutex_leave(mem.mutex);  
10030 }
10031
10032 /*
10033 ** Change the size of an existing memory allocation
10034 */
10035 SQLITE_API void *sqlite3_realloc(void *pPrior, int nBytes){
10036   int nOld;
10037   void *p;
10038   if( pPrior==0 ){
10039     return sqlite3_malloc(nBytes);
10040   }
10041   if( nBytes<=0 ){
10042     sqlite3_free(pPrior);
10043     return 0;
10044   }
10045   assert( mem.mutex!=0 );
10046   nOld = memsys3Size(pPrior);
10047   if( nBytes<=nOld && nBytes>=nOld-128 ){
10048     return pPrior;
10049   }
10050   sqlite3_mutex_enter(mem.mutex);
10051   p = memsys3Malloc(nBytes);
10052   if( p ){
10053     if( nOld<nBytes ){
10054       memcpy(p, pPrior, nOld);
10055     }else{
10056       memcpy(p, pPrior, nBytes);
10057     }
10058     memsys3Free(pPrior);
10059   }
10060   sqlite3_mutex_leave(mem.mutex);
10061   return p;
10062 }
10063
10064 /*
10065 ** Open the file indicated and write a log of all unfreed memory 
10066 ** allocations into that log.
10067 */
10068 SQLITE_API void sqlite3_memdebug_dump(const char *zFilename){
10069 #ifdef SQLITE_DEBUG
10070   FILE *out;
10071   int i, j, size;
10072   if( zFilename==0 || zFilename[0]==0 ){
10073     out = stdout;
10074   }else{
10075     out = fopen(zFilename, "w");
10076     if( out==0 ){
10077       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
10078                       zFilename);
10079       return;
10080     }
10081   }
10082   memsys3Enter();
10083   fprintf(out, "CHUNKS:\n");
10084   for(i=1; i<=SQLITE_MEMORY_SIZE/8; i+=size){
10085     size = mem.aPool[i-1].u.hdr.size;
10086     if( size>=-1 && size<=1 ){
10087       fprintf(out, "%p size error\n", &mem.aPool[i]);
10088       assert( 0 );
10089       break;
10090     }
10091     if( mem.aPool[i+(size<0?-size:size)-1].u.hdr.prevSize!=size ){
10092       fprintf(out, "%p tail size does not match\n", &mem.aPool[i]);
10093       assert( 0 );
10094       break;
10095     }
10096     if( size<0 ){
10097       size = -size;
10098       fprintf(out, "%p %6d bytes checked out\n", &mem.aPool[i], size*8-8);
10099     }else{
10100       fprintf(out, "%p %6d bytes free%s\n", &mem.aPool[i], size*8-8,
10101                   i==mem.iMaster ? " **master**" : "");
10102     }
10103   }
10104   for(i=0; i<MX_SMALL-1; i++){
10105     if( mem.aiSmall[i]==0 ) continue;
10106     fprintf(out, "small(%2d):", i);
10107     for(j = mem.aiSmall[i]; j>0; j=mem.aPool[j].u.list.next){
10108       fprintf(out, " %p(%d)", &mem.aPool[j], mem.aPool[j-1].u.hdr.size*8-8);
10109     }
10110     fprintf(out, "\n"); 
10111   }
10112   for(i=0; i<N_HASH; i++){
10113     if( mem.aiHash[i]==0 ) continue;
10114     fprintf(out, "hash(%2d):", i);
10115     for(j = mem.aiHash[i]; j>0; j=mem.aPool[j].u.list.next){
10116       fprintf(out, " %p(%d)", &mem.aPool[j], mem.aPool[j-1].u.hdr.size*8-8);
10117     }
10118     fprintf(out, "\n"); 
10119   }
10120   fprintf(out, "master=%d\n", mem.iMaster);
10121   fprintf(out, "nowUsed=%d\n", SQLITE_MEMORY_SIZE - mem.szMaster*8);
10122   fprintf(out, "mxUsed=%d\n", SQLITE_MEMORY_SIZE - mem.mnMaster*8);
10123   sqlite3_mutex_leave(mem.mutex);
10124   if( out==stdout ){
10125     fflush(stdout);
10126   }else{
10127     fclose(out);
10128   }
10129 #endif
10130 }
10131
10132
10133 #endif /* !SQLITE_MEMORY_SIZE */
10134
10135 /************** End of mem3.c ************************************************/
10136 /************** Begin file mutex.c *******************************************/
10137 /*
10138 ** 2007 August 14
10139 **
10140 ** The author disclaims copyright to this source code.  In place of
10141 ** a legal notice, here is a blessing:
10142 **
10143 **    May you do good and not evil.
10144 **    May you find forgiveness for yourself and forgive others.
10145 **    May you share freely, never taking more than you give.
10146 **
10147 *************************************************************************
10148 ** This file contains the C functions that implement mutexes.
10149 **
10150 ** The implementation in this file does not provide any mutual
10151 ** exclusion and is thus suitable for use only in applications
10152 ** that use SQLite in a single thread.  But this implementation
10153 ** does do a lot of error checking on mutexes to make sure they
10154 ** are called correctly and at appropriate times.  Hence, this
10155 ** implementation is suitable for testing.
10156 ** debugging purposes
10157 **
10158 ** $Id: mutex.c,v 1.16 2007/09/10 16:13:00 danielk1977 Exp $
10159 */
10160
10161 #ifdef SQLITE_MUTEX_NOOP_DEBUG
10162 /*
10163 ** In this implementation, mutexes do not provide any mutual exclusion.
10164 ** But the error checking is provided.  This implementation is useful
10165 ** for test purposes.
10166 */
10167
10168 /*
10169 ** The mutex object
10170 */
10171 struct sqlite3_mutex {
10172   int id;     /* The mutex type */
10173   int cnt;    /* Number of entries without a matching leave */
10174 };
10175
10176 /*
10177 ** The sqlite3_mutex_alloc() routine allocates a new
10178 ** mutex and returns a pointer to it.  If it returns NULL
10179 ** that means that a mutex could not be allocated. 
10180 */
10181 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
10182   static sqlite3_mutex aStatic[5];
10183   sqlite3_mutex *pNew = 0;
10184   switch( id ){
10185     case SQLITE_MUTEX_FAST:
10186     case SQLITE_MUTEX_RECURSIVE: {
10187       pNew = sqlite3_malloc(sizeof(*pNew));
10188       if( pNew ){
10189         pNew->id = id;
10190         pNew->cnt = 0;
10191       }
10192       break;
10193     }
10194     default: {
10195       assert( id-2 >= 0 );
10196       assert( id-2 < sizeof(aStatic)/sizeof(aStatic[0]) );
10197       pNew = &aStatic[id-2];
10198       pNew->id = id;
10199       break;
10200     }
10201   }
10202   return pNew;
10203 }
10204
10205 /*
10206 ** This routine deallocates a previously allocated mutex.
10207 */
10208 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
10209   assert( p );
10210   assert( p->cnt==0 );
10211   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
10212   sqlite3_free(p);
10213 }
10214
10215 /*
10216 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
10217 ** to enter a mutex.  If another thread is already within the mutex,
10218 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
10219 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
10220 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
10221 ** be entered multiple times by the same thread.  In such cases the,
10222 ** mutex must be exited an equal number of times before another thread
10223 ** can enter.  If the same thread tries to enter any other kind of mutex
10224 ** more than once, the behavior is undefined.
10225 */
10226 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
10227   assert( p );
10228   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
10229   p->cnt++;
10230 }
10231 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
10232   assert( p );
10233   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
10234   p->cnt++;
10235   return SQLITE_OK;
10236 }
10237
10238 /*
10239 ** The sqlite3_mutex_leave() routine exits a mutex that was
10240 ** previously entered by the same thread.  The behavior
10241 ** is undefined if the mutex is not currently entered or
10242 ** is not currently allocated.  SQLite will never do either.
10243 */
10244 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
10245   assert( p );
10246   assert( sqlite3_mutex_held(p) );
10247   p->cnt--;
10248   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
10249 }
10250
10251 /*
10252 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
10253 ** intended for use inside assert() statements.
10254 */
10255 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
10256   return p==0 || p->cnt>0;
10257 }
10258 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
10259   return p==0 || p->cnt==0;
10260 }
10261 #endif /* SQLITE_MUTEX_NOOP_DEBUG */
10262
10263 /************** End of mutex.c ***********************************************/
10264 /************** Begin file mutex_os2.c ***************************************/
10265 /*
10266 ** 2007 August 28
10267 **
10268 ** The author disclaims copyright to this source code.  In place of
10269 ** a legal notice, here is a blessing:
10270 **
10271 **    May you do good and not evil.
10272 **    May you find forgiveness for yourself and forgive others.
10273 **    May you share freely, never taking more than you give.
10274 **
10275 *************************************************************************
10276 ** This file contains the C functions that implement mutexes for OS/2
10277 **
10278 ** $Id: mutex_os2.c,v 1.3 2007/10/02 19:56:04 pweilbacher Exp $
10279 */
10280
10281 /*
10282 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
10283 ** See the mutex.h file for details.
10284 */
10285 #ifdef SQLITE_MUTEX_OS2
10286
10287 /********************** OS/2 Mutex Implementation **********************
10288 **
10289 ** This implementation of mutexes is built using the OS/2 API.
10290 */
10291
10292 /*
10293 ** The mutex object
10294 ** Each recursive mutex is an instance of the following structure.
10295 */
10296 struct sqlite3_mutex {
10297   PSZ  mutexName;   /* Mutex name controlling the lock */
10298   HMTX mutex;       /* Mutex controlling the lock */
10299   int  id;          /* Mutex type */
10300   int  nRef;        /* Number of references */
10301   TID  owner;       /* Thread holding this mutex */
10302 };
10303
10304 /*
10305 ** The sqlite3_mutex_alloc() routine allocates a new
10306 ** mutex and returns a pointer to it.  If it returns NULL
10307 ** that means that a mutex could not be allocated. 
10308 ** SQLite will unwind its stack and return an error.  The argument
10309 ** to sqlite3_mutex_alloc() is one of these integer constants:
10310 **
10311 ** <ul>
10312 ** <li>  SQLITE_MUTEX_FAST               0
10313 ** <li>  SQLITE_MUTEX_RECURSIVE          1
10314 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
10315 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
10316 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
10317 ** </ul>
10318 **
10319 ** The first two constants cause sqlite3_mutex_alloc() to create
10320 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
10321 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
10322 ** The mutex implementation does not need to make a distinction
10323 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
10324 ** not want to.  But SQLite will only request a recursive mutex in
10325 ** cases where it really needs one.  If a faster non-recursive mutex
10326 ** implementation is available on the host platform, the mutex subsystem
10327 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
10328 **
10329 ** The other allowed parameters to sqlite3_mutex_alloc() each return
10330 ** a pointer to a static preexisting mutex.  Three static mutexes are
10331 ** used by the current version of SQLite.  Future versions of SQLite
10332 ** may add additional static mutexes.  Static mutexes are for internal
10333 ** use by SQLite only.  Applications that use SQLite mutexes should
10334 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
10335 ** SQLITE_MUTEX_RECURSIVE.
10336 **
10337 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
10338 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
10339 ** returns a different mutex on every call.  But for the static
10340 ** mutex types, the same mutex is returned on every call that has
10341 ** the same type number.
10342 */
10343 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int iType){
10344   PSZ mutex_name = "\\SEM32\\SQLITE\\MUTEX";
10345   int mutex_name_len = strlen(mutex_name) + 1; /* name length + null byte */
10346   sqlite3_mutex *p;
10347
10348   switch( iType ){
10349     case SQLITE_MUTEX_FAST:
10350     case SQLITE_MUTEX_RECURSIVE: {
10351       p = sqlite3MallocZero( sizeof(*p) );
10352       if( p ){
10353         p->mutexName = (PSZ)malloc(mutex_name_len);
10354         sqlite3_snprintf(mutex_name_len, p->mutexName, "%s", mutex_name);
10355         p->id = iType;
10356         DosCreateMutexSem(p->mutexName, &p->mutex, 0, FALSE);
10357         DosOpenMutexSem(p->mutexName, &p->mutex);
10358       }
10359       break;
10360     }
10361     default: {
10362       static sqlite3_mutex staticMutexes[5];
10363       static int isInit = 0;
10364       while( !isInit ) {
10365         static long lock = 0;
10366         DosEnterCritSec();
10367         lock++;
10368         if( lock == 1 ) {
10369           DosExitCritSec();
10370           int i;
10371           for(i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++) {
10372             staticMutexes[i].mutexName = (PSZ)malloc(mutex_name_len + 1);
10373             sqlite3_snprintf(mutex_name_len + 1, /* one more for the number */
10374                              staticMutexes[i].mutexName, "%s%1d", mutex_name, i);
10375             DosCreateMutexSem(staticMutexes[i].mutexName,
10376                               &staticMutexes[i].mutex, 0, FALSE);
10377             DosOpenMutexSem(staticMutexes[i].mutexName,
10378                             &staticMutexes[i].mutex);
10379           }
10380           isInit = 1;
10381         } else {
10382           DosExitCritSec();
10383           DosSleep(1);
10384         }
10385       }
10386       assert( iType-2 >= 0 );
10387       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
10388       p = &staticMutexes[iType-2];
10389       p->id = iType;
10390       break;
10391     }
10392   }
10393   return p;
10394 }
10395
10396
10397 /*
10398 ** This routine deallocates a previously allocated mutex.
10399 ** SQLite is careful to deallocate every mutex that it allocates.
10400 */
10401 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
10402   assert( p );
10403   assert( p->nRef==0 );
10404   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
10405   DosCloseMutexSem(p->mutex);
10406   free(p->mutexName);
10407   sqlite3_free(p);
10408 }
10409
10410 /*
10411 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
10412 ** to enter a mutex.  If another thread is already within the mutex,
10413 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
10414 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
10415 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
10416 ** be entered multiple times by the same thread.  In such cases the,
10417 ** mutex must be exited an equal number of times before another thread
10418 ** can enter.  If the same thread tries to enter any other kind of mutex
10419 ** more than once, the behavior is undefined.
10420 */
10421 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
10422   TID tid;
10423   PID holder1;
10424   ULONG holder2;
10425   assert( p );
10426   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
10427   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
10428   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
10429   p->owner = tid;
10430   p->nRef++;
10431 }
10432 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
10433   int rc;
10434   TID tid;
10435   PID holder1;
10436   ULONG holder2;
10437   assert( p );
10438   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
10439   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
10440     DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
10441     p->owner = tid;
10442     p->nRef++;
10443     rc = SQLITE_OK;
10444   } else {
10445     rc = SQLITE_BUSY;
10446   }
10447
10448   return rc;
10449 }
10450
10451 /*
10452 ** The sqlite3_mutex_leave() routine exits a mutex that was
10453 ** previously entered by the same thread.  The behavior
10454 ** is undefined if the mutex is not currently entered or
10455 ** is not currently allocated.  SQLite will never do either.
10456 */
10457 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
10458   TID tid;
10459   PID holder1;
10460   ULONG holder2;
10461   assert( p->nRef>0 );
10462   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
10463   assert( p->owner==tid );
10464   p->nRef--;
10465   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
10466   DosReleaseMutexSem(p->mutex);
10467 }
10468
10469 /*
10470 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
10471 ** intended for use inside assert() statements.
10472 */
10473 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
10474   TID tid;
10475   PID pid;
10476   ULONG ulCount;
10477   PTIB ptib;
10478   if( p!=0 ) {
10479     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
10480   } else {
10481     DosGetInfoBlocks(&ptib, NULL);
10482     tid = ptib->tib_ptib2->tib2_ultid;
10483   }
10484   return p==0 || (p->nRef!=0 && p->owner==tid);
10485 }
10486 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
10487   TID tid;
10488   PID pid;
10489   ULONG ulCount;
10490   PTIB ptib;
10491   if( p!= 0 ) {
10492     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
10493   } else {
10494     DosGetInfoBlocks(&ptib, NULL);
10495     tid = ptib->tib_ptib2->tib2_ultid;
10496   }
10497   return p==0 || p->nRef==0 || p->owner!=tid;
10498 }
10499 #endif /* SQLITE_MUTEX_OS2 */
10500
10501 /************** End of mutex_os2.c *******************************************/
10502 /************** Begin file mutex_unix.c **************************************/
10503 /*
10504 ** 2007 August 28
10505 **
10506 ** The author disclaims copyright to this source code.  In place of
10507 ** a legal notice, here is a blessing:
10508 **
10509 **    May you do good and not evil.
10510 **    May you find forgiveness for yourself and forgive others.
10511 **    May you share freely, never taking more than you give.
10512 **
10513 *************************************************************************
10514 ** This file contains the C functions that implement mutexes for pthreads
10515 **
10516 ** $Id: mutex_unix.c,v 1.5 2007/11/28 14:04:57 drh Exp $
10517 */
10518
10519 /*
10520 ** The code in this file is only used if we are compiling threadsafe
10521 ** under unix with pthreads.
10522 **
10523 ** Note that this implementation requires a version of pthreads that
10524 ** supports recursive mutexes.
10525 */
10526 #ifdef SQLITE_MUTEX_PTHREADS
10527
10528 #include <pthread.h>
10529
10530
10531 /*
10532 ** Each recursive mutex is an instance of the following structure.
10533 */
10534 struct sqlite3_mutex {
10535   pthread_mutex_t mutex;     /* Mutex controlling the lock */
10536   int id;                    /* Mutex type */
10537   int nRef;                  /* Number of entrances */
10538   pthread_t owner;           /* Thread that is within this mutex */
10539 #ifdef SQLITE_DEBUG
10540   int trace;                 /* True to trace changes */
10541 #endif
10542 };
10543
10544 /*
10545 ** The sqlite3_mutex_alloc() routine allocates a new
10546 ** mutex and returns a pointer to it.  If it returns NULL
10547 ** that means that a mutex could not be allocated.  SQLite
10548 ** will unwind its stack and return an error.  The argument
10549 ** to sqlite3_mutex_alloc() is one of these integer constants:
10550 **
10551 ** <ul>
10552 ** <li>  SQLITE_MUTEX_FAST
10553 ** <li>  SQLITE_MUTEX_RECURSIVE
10554 ** <li>  SQLITE_MUTEX_STATIC_MASTER
10555 ** <li>  SQLITE_MUTEX_STATIC_MEM
10556 ** <li>  SQLITE_MUTEX_STATIC_MEM2
10557 ** <li>  SQLITE_MUTEX_STATIC_PRNG
10558 ** <li>  SQLITE_MUTEX_STATIC_LRU
10559 ** </ul>
10560 **
10561 ** The first two constants cause sqlite3_mutex_alloc() to create
10562 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
10563 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
10564 ** The mutex implementation does not need to make a distinction
10565 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
10566 ** not want to.  But SQLite will only request a recursive mutex in
10567 ** cases where it really needs one.  If a faster non-recursive mutex
10568 ** implementation is available on the host platform, the mutex subsystem
10569 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
10570 **
10571 ** The other allowed parameters to sqlite3_mutex_alloc() each return
10572 ** a pointer to a static preexisting mutex.  Three static mutexes are
10573 ** used by the current version of SQLite.  Future versions of SQLite
10574 ** may add additional static mutexes.  Static mutexes are for internal
10575 ** use by SQLite only.  Applications that use SQLite mutexes should
10576 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
10577 ** SQLITE_MUTEX_RECURSIVE.
10578 **
10579 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
10580 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
10581 ** returns a different mutex on every call.  But for the static 
10582 ** mutex types, the same mutex is returned on every call that has
10583 ** the same type number.
10584 */
10585 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int iType){
10586   static sqlite3_mutex staticMutexes[] = {
10587     { PTHREAD_MUTEX_INITIALIZER, },
10588     { PTHREAD_MUTEX_INITIALIZER, },
10589     { PTHREAD_MUTEX_INITIALIZER, },
10590     { PTHREAD_MUTEX_INITIALIZER, },
10591     { PTHREAD_MUTEX_INITIALIZER, },
10592   };
10593   sqlite3_mutex *p;
10594   switch( iType ){
10595     case SQLITE_MUTEX_RECURSIVE: {
10596       p = sqlite3MallocZero( sizeof(*p) );
10597       if( p ){
10598 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
10599         /* If recursive mutexes are not available, we will have to
10600         ** build our own.  See below. */
10601         pthread_mutex_init(&p->mutex, 0);
10602 #else
10603         /* Use a recursive mutex if it is available */
10604         pthread_mutexattr_t recursiveAttr;
10605         pthread_mutexattr_init(&recursiveAttr);
10606         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
10607         pthread_mutex_init(&p->mutex, &recursiveAttr);
10608         pthread_mutexattr_destroy(&recursiveAttr);
10609 #endif
10610         p->id = iType;
10611       }
10612       break;
10613     }
10614     case SQLITE_MUTEX_FAST: {
10615       p = sqlite3MallocZero( sizeof(*p) );
10616       if( p ){
10617         p->id = iType;
10618         pthread_mutex_init(&p->mutex, 0);
10619       }
10620       break;
10621     }
10622     default: {
10623       assert( iType-2 >= 0 );
10624       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
10625       p = &staticMutexes[iType-2];
10626       p->id = iType;
10627       break;
10628     }
10629   }
10630   return p;
10631 }
10632
10633
10634 /*
10635 ** This routine deallocates a previously
10636 ** allocated mutex.  SQLite is careful to deallocate every
10637 ** mutex that it allocates.
10638 */
10639 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
10640   assert( p );
10641   assert( p->nRef==0 );
10642   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
10643   pthread_mutex_destroy(&p->mutex);
10644   sqlite3_free(p);
10645 }
10646
10647 /*
10648 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
10649 ** to enter a mutex.  If another thread is already within the mutex,
10650 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
10651 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
10652 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
10653 ** be entered multiple times by the same thread.  In such cases the,
10654 ** mutex must be exited an equal number of times before another thread
10655 ** can enter.  If the same thread tries to enter any other kind of mutex
10656 ** more than once, the behavior is undefined.
10657 */
10658 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
10659   assert( p );
10660   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
10661
10662 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
10663   /* If recursive mutexes are not available, then we have to grow
10664   ** our own.  This implementation assumes that pthread_equal()
10665   ** is atomic - that it cannot be deceived into thinking self
10666   ** and p->owner are equal if p->owner changes between two values
10667   ** that are not equal to self while the comparison is taking place.
10668   ** This implementation also assumes a coherent cache - that 
10669   ** separate processes cannot read different values from the same
10670   ** address at the same time.  If either of these two conditions
10671   ** are not met, then the mutexes will fail and problems will result.
10672   */
10673   {
10674     pthread_t self = pthread_self();
10675     if( p->nRef>0 && pthread_equal(p->owner, self) ){
10676       p->nRef++;
10677     }else{
10678       pthread_mutex_lock(&p->mutex);
10679       assert( p->nRef==0 );
10680       p->owner = self;
10681       p->nRef = 1;
10682     }
10683   }
10684 #else
10685   /* Use the built-in recursive mutexes if they are available.
10686   */
10687   pthread_mutex_lock(&p->mutex);
10688   p->owner = pthread_self();
10689   p->nRef++;
10690 #endif
10691
10692 #ifdef SQLITE_DEBUG
10693   if( p->trace ){
10694     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
10695   }
10696 #endif
10697 }
10698 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
10699   int rc;
10700   assert( p );
10701   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
10702
10703 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
10704   /* If recursive mutexes are not available, then we have to grow
10705   ** our own.  This implementation assumes that pthread_equal()
10706   ** is atomic - that it cannot be deceived into thinking self
10707   ** and p->owner are equal if p->owner changes between two values
10708   ** that are not equal to self while the comparison is taking place.
10709   ** This implementation also assumes a coherent cache - that 
10710   ** separate processes cannot read different values from the same
10711   ** address at the same time.  If either of these two conditions
10712   ** are not met, then the mutexes will fail and problems will result.
10713   */
10714   {
10715     pthread_t self = pthread_self();
10716     if( p->nRef>0 && pthread_equal(p->owner, self) ){
10717       p->nRef++;
10718       rc = SQLITE_OK;
10719     }else if( pthread_mutex_lock(&p->mutex)==0 ){
10720       assert( p->nRef==0 );
10721       p->owner = self;
10722       p->nRef = 1;
10723       rc = SQLITE_OK;
10724     }else{
10725       rc = SQLITE_BUSY;
10726     }
10727   }
10728 #else
10729   /* Use the built-in recursive mutexes if they are available.
10730   */
10731   if( pthread_mutex_trylock(&p->mutex)==0 ){
10732     p->owner = pthread_self();
10733     p->nRef++;
10734     rc = SQLITE_OK;
10735   }else{
10736     rc = SQLITE_BUSY;
10737   }
10738 #endif
10739
10740 #ifdef SQLITE_DEBUG
10741   if( rc==SQLITE_OK && p->trace ){
10742     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
10743   }
10744 #endif
10745   return rc;
10746 }
10747
10748 /*
10749 ** The sqlite3_mutex_leave() routine exits a mutex that was
10750 ** previously entered by the same thread.  The behavior
10751 ** is undefined if the mutex is not currently entered or
10752 ** is not currently allocated.  SQLite will never do either.
10753 */
10754 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
10755   assert( p );
10756   assert( sqlite3_mutex_held(p) );
10757   p->nRef--;
10758   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
10759
10760 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
10761   if( p->nRef==0 ){
10762     pthread_mutex_unlock(&p->mutex);
10763   }
10764 #else
10765   pthread_mutex_unlock(&p->mutex);
10766 #endif
10767
10768 #ifdef SQLITE_DEBUG
10769   if( p->trace ){
10770     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
10771   }
10772 #endif
10773 }
10774
10775 /*
10776 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
10777 ** intended for use only inside assert() statements.  On some platforms,
10778 ** there might be race conditions that can cause these routines to
10779 ** deliver incorrect results.  In particular, if pthread_equal() is
10780 ** not an atomic operation, then these routines might delivery
10781 ** incorrect results.  On most platforms, pthread_equal() is a 
10782 ** comparison of two integers and is therefore atomic.  But we are
10783 ** told that HPUX is not such a platform.  If so, then these routines
10784 ** will not always work correctly on HPUX.
10785 **
10786 ** On those platforms where pthread_equal() is not atomic, SQLite
10787 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
10788 ** make sure no assert() statements are evaluated and hence these
10789 ** routines are never called.
10790 */
10791 #ifndef NDEBUG
10792 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
10793   return p==0 || (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
10794 }
10795 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
10796   return p==0 || p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
10797 }
10798 #endif
10799 #endif /* SQLITE_MUTEX_PTHREAD */
10800
10801 /************** End of mutex_unix.c ******************************************/
10802 /************** Begin file mutex_w32.c ***************************************/
10803 /*
10804 ** 2007 August 14
10805 **
10806 ** The author disclaims copyright to this source code.  In place of
10807 ** a legal notice, here is a blessing:
10808 **
10809 **    May you do good and not evil.
10810 **    May you find forgiveness for yourself and forgive others.
10811 **    May you share freely, never taking more than you give.
10812 **
10813 *************************************************************************
10814 ** This file contains the C functions that implement mutexes for win32
10815 **
10816 ** $Id: mutex_w32.c,v 1.5 2007/10/05 15:08:01 drh Exp $
10817 */
10818
10819 /*
10820 ** The code in this file is only used if we are compiling multithreaded
10821 ** on a win32 system.
10822 */
10823 #ifdef SQLITE_MUTEX_W32
10824
10825 /*
10826 ** Each recursive mutex is an instance of the following structure.
10827 */
10828 struct sqlite3_mutex {
10829   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
10830   int id;                    /* Mutex type */
10831   int nRef;                  /* Number of enterances */
10832   DWORD owner;               /* Thread holding this mutex */
10833 };
10834
10835 /*
10836 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
10837 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
10838 **
10839 ** Here is an interesting observation:  Win95, Win98, and WinME lack
10840 ** the LockFileEx() API.  But we can still statically link against that
10841 ** API as long as we don't call it win running Win95/98/ME.  A call to
10842 ** this routine is used to determine if the host is Win95/98/ME or
10843 ** WinNT/2K/XP so that we will know whether or not we can safely call
10844 ** the LockFileEx() API.
10845 */
10846 #if OS_WINCE
10847 # define mutexIsNT()  (1)
10848 #else
10849   static int mutexIsNT(void){
10850     static int osType = 0;
10851     if( osType==0 ){
10852       OSVERSIONINFO sInfo;
10853       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
10854       GetVersionEx(&sInfo);
10855       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
10856     }
10857     return osType==2;
10858   }
10859 #endif /* OS_WINCE */
10860
10861
10862 /*
10863 ** The sqlite3_mutex_alloc() routine allocates a new
10864 ** mutex and returns a pointer to it.  If it returns NULL
10865 ** that means that a mutex could not be allocated.  SQLite
10866 ** will unwind its stack and return an error.  The argument
10867 ** to sqlite3_mutex_alloc() is one of these integer constants:
10868 **
10869 ** <ul>
10870 ** <li>  SQLITE_MUTEX_FAST               0
10871 ** <li>  SQLITE_MUTEX_RECURSIVE          1
10872 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
10873 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
10874 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
10875 ** </ul>
10876 **
10877 ** The first two constants cause sqlite3_mutex_alloc() to create
10878 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
10879 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
10880 ** The mutex implementation does not need to make a distinction
10881 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
10882 ** not want to.  But SQLite will only request a recursive mutex in
10883 ** cases where it really needs one.  If a faster non-recursive mutex
10884 ** implementation is available on the host platform, the mutex subsystem
10885 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
10886 **
10887 ** The other allowed parameters to sqlite3_mutex_alloc() each return
10888 ** a pointer to a static preexisting mutex.  Three static mutexes are
10889 ** used by the current version of SQLite.  Future versions of SQLite
10890 ** may add additional static mutexes.  Static mutexes are for internal
10891 ** use by SQLite only.  Applications that use SQLite mutexes should
10892 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
10893 ** SQLITE_MUTEX_RECURSIVE.
10894 **
10895 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
10896 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
10897 ** returns a different mutex on every call.  But for the static 
10898 ** mutex types, the same mutex is returned on every call that has
10899 ** the same type number.
10900 */
10901 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int iType){
10902   sqlite3_mutex *p;
10903
10904   switch( iType ){
10905     case SQLITE_MUTEX_FAST:
10906     case SQLITE_MUTEX_RECURSIVE: {
10907       p = sqlite3MallocZero( sizeof(*p) );
10908       if( p ){
10909         p->id = iType;
10910         InitializeCriticalSection(&p->mutex);
10911       }
10912       break;
10913     }
10914     default: {
10915       static sqlite3_mutex staticMutexes[5];
10916       static int isInit = 0;
10917       while( !isInit ){
10918         static long lock = 0;
10919         if( InterlockedIncrement(&lock)==1 ){
10920           int i;
10921           for(i=0; i<sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++){
10922             InitializeCriticalSection(&staticMutexes[i].mutex);
10923           }
10924           isInit = 1;
10925         }else{
10926           Sleep(1);
10927         }
10928       }
10929       assert( iType-2 >= 0 );
10930       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
10931       p = &staticMutexes[iType-2];
10932       p->id = iType;
10933       break;
10934     }
10935   }
10936   return p;
10937 }
10938
10939
10940 /*
10941 ** This routine deallocates a previously
10942 ** allocated mutex.  SQLite is careful to deallocate every
10943 ** mutex that it allocates.
10944 */
10945 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
10946   assert( p );
10947   assert( p->nRef==0 );
10948   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
10949   DeleteCriticalSection(&p->mutex);
10950   sqlite3_free(p);
10951 }
10952
10953 /*
10954 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
10955 ** to enter a mutex.  If another thread is already within the mutex,
10956 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
10957 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
10958 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
10959 ** be entered multiple times by the same thread.  In such cases the,
10960 ** mutex must be exited an equal number of times before another thread
10961 ** can enter.  If the same thread tries to enter any other kind of mutex
10962 ** more than once, the behavior is undefined.
10963 */
10964 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
10965   assert( p );
10966   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
10967   EnterCriticalSection(&p->mutex);
10968   p->owner = GetCurrentThreadId(); 
10969   p->nRef++;
10970 }
10971 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
10972   int rc = SQLITE_BUSY;
10973   assert( p );
10974   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
10975   /*
10976   ** The sqlite3_mutex_try() routine is very rarely used, and when it
10977   ** is used it is merely an optimization.  So it is OK for it to always
10978   ** fail.  
10979   **
10980   ** The TryEnterCriticalSection() interface is only available on WinNT.
10981   ** And some windows compilers complain if you try to use it without
10982   ** first doing some #defines that prevent SQLite from building on Win98.
10983   ** For that reason, we will omit this optimization for now.  See
10984   ** ticket #2685.
10985   */
10986 #if 0
10987   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
10988     p->owner = GetCurrentThreadId();
10989     p->nRef++;
10990     rc = SQLITE_OK;
10991   }
10992 #endif
10993   return rc;
10994 }
10995
10996 /*
10997 ** The sqlite3_mutex_leave() routine exits a mutex that was
10998 ** previously entered by the same thread.  The behavior
10999 ** is undefined if the mutex is not currently entered or
11000 ** is not currently allocated.  SQLite will never do either.
11001 */
11002 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
11003   assert( p->nRef>0 );
11004   assert( p->owner==GetCurrentThreadId() );
11005   p->nRef--;
11006   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
11007   LeaveCriticalSection(&p->mutex);
11008 }
11009
11010 /*
11011 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
11012 ** intended for use only inside assert() statements.
11013 */
11014 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
11015   return p==0 || (p->nRef!=0 && p->owner==GetCurrentThreadId());
11016 }
11017 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
11018   return p==0 || p->nRef==0 || p->owner!=GetCurrentThreadId();
11019 }
11020 #endif /* SQLITE_MUTEX_W32 */
11021
11022 /************** End of mutex_w32.c *******************************************/
11023 /************** Begin file malloc.c ******************************************/
11024 /*
11025 ** 2001 September 15
11026 **
11027 ** The author disclaims copyright to this source code.  In place of
11028 ** a legal notice, here is a blessing:
11029 **
11030 **    May you do good and not evil.
11031 **    May you find forgiveness for yourself and forgive others.
11032 **    May you share freely, never taking more than you give.
11033 **
11034 *************************************************************************
11035 ** Memory allocation functions used throughout sqlite.
11036 **
11037 **
11038 ** $Id: malloc.c,v 1.14 2007/10/20 16:36:31 drh Exp $
11039 */
11040
11041 /*
11042 ** This routine runs when the memory allocator sees that the
11043 ** total memory allocation is about to exceed the soft heap
11044 ** limit.
11045 */
11046 static void softHeapLimitEnforcer(
11047   void *NotUsed, 
11048   sqlite3_int64 inUse,
11049   int allocSize
11050 ){
11051   sqlite3_release_memory(allocSize);
11052 }
11053
11054 /*
11055 ** Set the soft heap-size limit for the current thread. Passing a
11056 ** zero or negative value indicates no limit.
11057 */
11058 SQLITE_API void sqlite3_soft_heap_limit(int n){
11059   sqlite3_uint64 iLimit;
11060   int overage;
11061   if( n<0 ){
11062     iLimit = 0;
11063   }else{
11064     iLimit = n;
11065   }
11066   if( iLimit>0 ){
11067     sqlite3_memory_alarm(softHeapLimitEnforcer, 0, iLimit);
11068   }else{
11069     sqlite3_memory_alarm(0, 0, 0);
11070   }
11071   overage = sqlite3_memory_used() - n;
11072   if( overage>0 ){
11073     sqlite3_release_memory(overage);
11074   }
11075 }
11076
11077 /*
11078 ** Release memory held by SQLite instances created by the current thread.
11079 */
11080 SQLITE_API int sqlite3_release_memory(int n){
11081 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
11082   return sqlite3PagerReleaseMemory(n);
11083 #else
11084   return SQLITE_OK;
11085 #endif
11086 }
11087
11088
11089 /*
11090 ** Allocate and zero memory.
11091 */ 
11092 SQLITE_PRIVATE void *sqlite3MallocZero(unsigned n){
11093   void *p = sqlite3_malloc(n);
11094   if( p ){
11095     memset(p, 0, n);
11096   }
11097   return p;
11098 }
11099
11100 /*
11101 ** Allocate and zero memory.  If the allocation fails, make
11102 ** the mallocFailed flag in the connection pointer.
11103 */
11104 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, unsigned n){
11105   void *p = sqlite3DbMallocRaw(db, n);
11106   if( p ){
11107     memset(p, 0, n);
11108   }
11109   return p;
11110 }
11111
11112 /*
11113 ** Allocate and zero memory.  If the allocation fails, make
11114 ** the mallocFailed flag in the connection pointer.
11115 */
11116 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, unsigned n){
11117   void *p = 0;
11118   if( !db || db->mallocFailed==0 ){
11119     p = sqlite3_malloc(n);
11120     if( !p && db ){
11121       db->mallocFailed = 1;
11122     }
11123   }
11124   return p;
11125 }
11126
11127 /*
11128 ** Resize the block of memory pointed to by p to n bytes. If the
11129 ** resize fails, set the mallocFailed flag inthe connection object.
11130 */
11131 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
11132   void *pNew = 0;
11133   if( db->mallocFailed==0 ){
11134     pNew = sqlite3_realloc(p, n);
11135     if( !pNew ){
11136       db->mallocFailed = 1;
11137     }
11138   }
11139   return pNew;
11140 }
11141
11142 /*
11143 ** Attempt to reallocate p.  If the reallocation fails, then free p
11144 ** and set the mallocFailed flag in the database connection.
11145 */
11146 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
11147   void *pNew;
11148   pNew = sqlite3DbRealloc(db, p, n);
11149   if( !pNew ){
11150     sqlite3_free(p);
11151   }
11152   return pNew;
11153 }
11154
11155 /*
11156 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
11157 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
11158 ** is because when memory debugging is turned on, these two functions are 
11159 ** called via macros that record the current file and line number in the
11160 ** ThreadData structure.
11161 */
11162 SQLITE_PRIVATE char *sqlite3StrDup(const char *z){
11163   char *zNew;
11164   int n;
11165   if( z==0 ) return 0;
11166   n = strlen(z)+1;
11167   zNew = sqlite3_malloc(n);
11168   if( zNew ) memcpy(zNew, z, n);
11169   return zNew;
11170 }
11171 SQLITE_PRIVATE char *sqlite3StrNDup(const char *z, int n){
11172   char *zNew;
11173   if( z==0 ) return 0;
11174   zNew = sqlite3_malloc(n+1);
11175   if( zNew ){
11176     memcpy(zNew, z, n);
11177     zNew[n] = 0;
11178   }
11179   return zNew;
11180 }
11181
11182 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
11183   char *zNew = sqlite3StrDup(z);
11184   if( z && !zNew ){
11185     db->mallocFailed = 1;
11186   }
11187   return zNew;
11188 }
11189 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
11190   char *zNew = sqlite3StrNDup(z, n);
11191   if( z && !zNew ){
11192     db->mallocFailed = 1;
11193   }
11194   return zNew;
11195 }
11196
11197 /*
11198 ** Create a string from the 2nd and subsequent arguments (up to the
11199 ** first NULL argument), store the string in memory obtained from
11200 ** sqliteMalloc() and make the pointer indicated by the 1st argument
11201 ** point to that string.  The 1st argument must either be NULL or 
11202 ** point to memory obtained from sqliteMalloc().
11203 */
11204 SQLITE_PRIVATE void sqlite3SetString(char **pz, ...){
11205   va_list ap;
11206   int nByte;
11207   const char *z;
11208   char *zResult;
11209
11210   assert( pz!=0 );
11211   nByte = 1;
11212   va_start(ap, pz);
11213   while( (z = va_arg(ap, const char*))!=0 ){
11214     nByte += strlen(z);
11215   }
11216   va_end(ap);
11217   sqlite3_free(*pz);
11218   *pz = zResult = sqlite3_malloc(nByte);
11219   if( zResult==0 ){
11220     return;
11221   }
11222   *zResult = 0;
11223   va_start(ap, pz);
11224   while( (z = va_arg(ap, const char*))!=0 ){
11225     int n = strlen(z);
11226     memcpy(zResult, z, n);
11227     zResult += n;
11228   }
11229   zResult[0] = 0;
11230   va_end(ap);
11231 }
11232
11233
11234 /*
11235 ** This function must be called before exiting any API function (i.e. 
11236 ** returning control to the user) that has called sqlite3_malloc or
11237 ** sqlite3_realloc.
11238 **
11239 ** The returned value is normally a copy of the second argument to this
11240 ** function. However, if a malloc() failure has occured since the previous
11241 ** invocation SQLITE_NOMEM is returned instead. 
11242 **
11243 ** If the first argument, db, is not NULL and a malloc() error has occured,
11244 ** then the connection error-code (the value returned by sqlite3_errcode())
11245 ** is set to SQLITE_NOMEM.
11246 */
11247 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
11248   /* If the db handle is not NULL, then we must hold the connection handle
11249   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
11250   ** is unsafe, as is the call to sqlite3Error().
11251   */
11252   assert( !db || sqlite3_mutex_held(db->mutex) );
11253   if( db && db->mallocFailed ){
11254     sqlite3Error(db, SQLITE_NOMEM, 0);
11255     db->mallocFailed = 0;
11256     rc = SQLITE_NOMEM;
11257   }
11258   return rc & (db ? db->errMask : 0xff);
11259 }
11260
11261 /************** End of malloc.c **********************************************/
11262 /************** Begin file printf.c ******************************************/
11263 /*
11264 ** The "printf" code that follows dates from the 1980's.  It is in
11265 ** the public domain.  The original comments are included here for
11266 ** completeness.  They are very out-of-date but might be useful as
11267 ** an historical reference.  Most of the "enhancements" have been backed
11268 ** out so that the functionality is now the same as standard printf().
11269 **
11270 **************************************************************************
11271 **
11272 ** The following modules is an enhanced replacement for the "printf" subroutines
11273 ** found in the standard C library.  The following enhancements are
11274 ** supported:
11275 **
11276 **      +  Additional functions.  The standard set of "printf" functions
11277 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
11278 **         vsprintf.  This module adds the following:
11279 **
11280 **           *  snprintf -- Works like sprintf, but has an extra argument
11281 **                          which is the size of the buffer written to.
11282 **
11283 **           *  mprintf --  Similar to sprintf.  Writes output to memory
11284 **                          obtained from malloc.
11285 **
11286 **           *  xprintf --  Calls a function to dispose of output.
11287 **
11288 **           *  nprintf --  No output, but returns the number of characters
11289 **                          that would have been output by printf.
11290 **
11291 **           *  A v- version (ex: vsnprintf) of every function is also
11292 **              supplied.
11293 **
11294 **      +  A few extensions to the formatting notation are supported:
11295 **
11296 **           *  The "=" flag (similar to "-") causes the output to be
11297 **              be centered in the appropriately sized field.
11298 **
11299 **           *  The %b field outputs an integer in binary notation.
11300 **
11301 **           *  The %c field now accepts a precision.  The character output
11302 **              is repeated by the number of times the precision specifies.
11303 **
11304 **           *  The %' field works like %c, but takes as its character the
11305 **              next character of the format string, instead of the next
11306 **              argument.  For example,  printf("%.78'-")  prints 78 minus
11307 **              signs, the same as  printf("%.78c",'-').
11308 **
11309 **      +  When compiled using GCC on a SPARC, this version of printf is
11310 **         faster than the library printf for SUN OS 4.1.
11311 **
11312 **      +  All functions are fully reentrant.
11313 **
11314 */
11315
11316 /*
11317 ** Conversion types fall into various categories as defined by the
11318 ** following enumeration.
11319 */
11320 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
11321 #define etFLOAT       2 /* Floating point.  %f */
11322 #define etEXP         3 /* Exponentional notation. %e and %E */
11323 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
11324 #define etSIZE        5 /* Return number of characters processed so far. %n */
11325 #define etSTRING      6 /* Strings. %s */
11326 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
11327 #define etPERCENT     8 /* Percent symbol. %% */
11328 #define etCHARX       9 /* Characters. %c */
11329 /* The rest are extensions, not normally found in printf() */
11330 #define etCHARLIT    10 /* Literal characters.  %' */
11331 #define etSQLESCAPE  11 /* Strings with '\'' doubled.  %q */
11332 #define etSQLESCAPE2 12 /* Strings with '\'' doubled and enclosed in '',
11333                           NULL pointers replaced by SQL NULL.  %Q */
11334 #define etTOKEN      13 /* a pointer to a Token structure */
11335 #define etSRCLIST    14 /* a pointer to a SrcList */
11336 #define etPOINTER    15 /* The %p conversion */
11337 #define etSQLESCAPE3 16 /* %w -> Strings with '\"' doubled */
11338 #define etORDINAL    17 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
11339
11340
11341 /*
11342 ** An "etByte" is an 8-bit unsigned value.
11343 */
11344 typedef unsigned char etByte;
11345
11346 /*
11347 ** Each builtin conversion character (ex: the 'd' in "%d") is described
11348 ** by an instance of the following structure
11349 */
11350 typedef struct et_info {   /* Information about each format field */
11351   char fmttype;            /* The format field code letter */
11352   etByte base;             /* The base for radix conversion */
11353   etByte flags;            /* One or more of FLAG_ constants below */
11354   etByte type;             /* Conversion paradigm */
11355   etByte charset;          /* Offset into aDigits[] of the digits string */
11356   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
11357 } et_info;
11358
11359 /*
11360 ** Allowed values for et_info.flags
11361 */
11362 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
11363 #define FLAG_INTERN  2     /* True if for internal use only */
11364 #define FLAG_STRING  4     /* Allow infinity precision */
11365
11366
11367 /*
11368 ** The following table is searched linearly, so it is good to put the
11369 ** most frequently used conversion types first.
11370 */
11371 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
11372 static const char aPrefix[] = "-x0\000X0";
11373 static const et_info fmtinfo[] = {
11374   {  'd', 10, 1, etRADIX,      0,  0 },
11375   {  's',  0, 4, etSTRING,     0,  0 },
11376   {  'g',  0, 1, etGENERIC,    30, 0 },
11377   {  'z',  0, 4, etDYNSTRING,  0,  0 },
11378   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
11379   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
11380   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
11381   {  'c',  0, 0, etCHARX,      0,  0 },
11382   {  'o',  8, 0, etRADIX,      0,  2 },
11383   {  'u', 10, 0, etRADIX,      0,  0 },
11384   {  'x', 16, 0, etRADIX,      16, 1 },
11385   {  'X', 16, 0, etRADIX,      0,  4 },
11386 #ifndef SQLITE_OMIT_FLOATING_POINT
11387   {  'f',  0, 1, etFLOAT,      0,  0 },
11388   {  'e',  0, 1, etEXP,        30, 0 },
11389   {  'E',  0, 1, etEXP,        14, 0 },
11390   {  'G',  0, 1, etGENERIC,    14, 0 },
11391 #endif
11392   {  'i', 10, 1, etRADIX,      0,  0 },
11393   {  'n',  0, 0, etSIZE,       0,  0 },
11394   {  '%',  0, 0, etPERCENT,    0,  0 },
11395   {  'p', 16, 0, etPOINTER,    0,  1 },
11396   {  'T',  0, 2, etTOKEN,      0,  0 },
11397   {  'S',  0, 2, etSRCLIST,    0,  0 },
11398   {  'r', 10, 3, etORDINAL,    0,  0 },
11399 };
11400 #define etNINFO  (sizeof(fmtinfo)/sizeof(fmtinfo[0]))
11401
11402 /*
11403 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
11404 ** conversions will work.
11405 */
11406 #ifndef SQLITE_OMIT_FLOATING_POINT
11407 /*
11408 ** "*val" is a double such that 0.1 <= *val < 10.0
11409 ** Return the ascii code for the leading digit of *val, then
11410 ** multiply "*val" by 10.0 to renormalize.
11411 **
11412 ** Example:
11413 **     input:     *val = 3.14159
11414 **     output:    *val = 1.4159    function return = '3'
11415 **
11416 ** The counter *cnt is incremented each time.  After counter exceeds
11417 ** 16 (the number of significant digits in a 64-bit float) '0' is
11418 ** always returned.
11419 */
11420 static int et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
11421   int digit;
11422   LONGDOUBLE_TYPE d;
11423   if( (*cnt)++ >= 16 ) return '0';
11424   digit = (int)*val;
11425   d = digit;
11426   digit += '0';
11427   *val = (*val - d)*10.0;
11428   return digit;
11429 }
11430 #endif /* SQLITE_OMIT_FLOATING_POINT */
11431
11432 /*
11433 ** Append N space characters to the given string buffer.
11434 */
11435 static void appendSpace(StrAccum *pAccum, int N){
11436   static const char zSpaces[] = "                             ";
11437   while( N>=sizeof(zSpaces)-1 ){
11438     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
11439     N -= sizeof(zSpaces)-1;
11440   }
11441   if( N>0 ){
11442     sqlite3StrAccumAppend(pAccum, zSpaces, N);
11443   }
11444 }
11445
11446 /*
11447 ** On machines with a small stack size, you can redefine the
11448 ** SQLITE_PRINT_BUF_SIZE to be less than 350.  But beware - for
11449 ** smaller values some %f conversions may go into an infinite loop.
11450 */
11451 #ifndef SQLITE_PRINT_BUF_SIZE
11452 # define SQLITE_PRINT_BUF_SIZE 350
11453 #endif
11454 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
11455
11456 /*
11457 ** The root program.  All variations call this core.
11458 **
11459 ** INPUTS:
11460 **   func   This is a pointer to a function taking three arguments
11461 **            1. A pointer to anything.  Same as the "arg" parameter.
11462 **            2. A pointer to the list of characters to be output
11463 **               (Note, this list is NOT null terminated.)
11464 **            3. An integer number of characters to be output.
11465 **               (Note: This number might be zero.)
11466 **
11467 **   arg    This is the pointer to anything which will be passed as the
11468 **          first argument to "func".  Use it for whatever you like.
11469 **
11470 **   fmt    This is the format string, as in the usual print.
11471 **
11472 **   ap     This is a pointer to a list of arguments.  Same as in
11473 **          vfprint.
11474 **
11475 ** OUTPUTS:
11476 **          The return value is the total number of characters sent to
11477 **          the function "func".  Returns -1 on a error.
11478 **
11479 ** Note that the order in which automatic variables are declared below
11480 ** seems to make a big difference in determining how fast this beast
11481 ** will run.
11482 */
11483 static void vxprintf(
11484   StrAccum *pAccum,                  /* Accumulate results here */
11485   int useExtended,                   /* Allow extended %-conversions */
11486   const char *fmt,                   /* Format string */
11487   va_list ap                         /* arguments */
11488 ){
11489   int c;                     /* Next character in the format string */
11490   char *bufpt;               /* Pointer to the conversion buffer */
11491   int precision;             /* Precision of the current field */
11492   int length;                /* Length of the field */
11493   int idx;                   /* A general purpose loop counter */
11494   int width;                 /* Width of the current field */
11495   etByte flag_leftjustify;   /* True if "-" flag is present */
11496   etByte flag_plussign;      /* True if "+" flag is present */
11497   etByte flag_blanksign;     /* True if " " flag is present */
11498   etByte flag_alternateform; /* True if "#" flag is present */
11499   etByte flag_altform2;      /* True if "!" flag is present */
11500   etByte flag_zeropad;       /* True if field width constant starts with zero */
11501   etByte flag_long;          /* True if "l" flag is present */
11502   etByte flag_longlong;      /* True if the "ll" flag is present */
11503   etByte done;               /* Loop termination flag */
11504   sqlite_uint64 longvalue;   /* Value for integer types */
11505   LONGDOUBLE_TYPE realvalue; /* Value for real types */
11506   const et_info *infop;      /* Pointer to the appropriate info structure */
11507   char buf[etBUFSIZE];       /* Conversion buffer */
11508   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
11509   etByte errorflag = 0;      /* True if an error is encountered */
11510   etByte xtype;              /* Conversion paradigm */
11511   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
11512 #ifndef SQLITE_OMIT_FLOATING_POINT
11513   int  exp, e2;              /* exponent of real numbers */
11514   double rounder;            /* Used for rounding floating point values */
11515   etByte flag_dp;            /* True if decimal point should be shown */
11516   etByte flag_rtz;           /* True if trailing zeros should be removed */
11517   etByte flag_exp;           /* True to force display of the exponent */
11518   int nsd;                   /* Number of significant digits returned */
11519 #endif
11520
11521   length = 0;
11522   bufpt = 0;
11523   for(; (c=(*fmt))!=0; ++fmt){
11524     if( c!='%' ){
11525       int amt;
11526       bufpt = (char *)fmt;
11527       amt = 1;
11528       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
11529       sqlite3StrAccumAppend(pAccum, bufpt, amt);
11530       if( c==0 ) break;
11531     }
11532     if( (c=(*++fmt))==0 ){
11533       errorflag = 1;
11534       sqlite3StrAccumAppend(pAccum, "%", 1);
11535       break;
11536     }
11537     /* Find out what flags are present */
11538     flag_leftjustify = flag_plussign = flag_blanksign = 
11539      flag_alternateform = flag_altform2 = flag_zeropad = 0;
11540     done = 0;
11541     do{
11542       switch( c ){
11543         case '-':   flag_leftjustify = 1;     break;
11544         case '+':   flag_plussign = 1;        break;
11545         case ' ':   flag_blanksign = 1;       break;
11546         case '#':   flag_alternateform = 1;   break;
11547         case '!':   flag_altform2 = 1;        break;
11548         case '0':   flag_zeropad = 1;         break;
11549         default:    done = 1;                 break;
11550       }
11551     }while( !done && (c=(*++fmt))!=0 );
11552     /* Get the field width */
11553     width = 0;
11554     if( c=='*' ){
11555       width = va_arg(ap,int);
11556       if( width<0 ){
11557         flag_leftjustify = 1;
11558         width = -width;
11559       }
11560       c = *++fmt;
11561     }else{
11562       while( c>='0' && c<='9' ){
11563         width = width*10 + c - '0';
11564         c = *++fmt;
11565       }
11566     }
11567     if( width > etBUFSIZE-10 ){
11568       width = etBUFSIZE-10;
11569     }
11570     /* Get the precision */
11571     if( c=='.' ){
11572       precision = 0;
11573       c = *++fmt;
11574       if( c=='*' ){
11575         precision = va_arg(ap,int);
11576         if( precision<0 ) precision = -precision;
11577         c = *++fmt;
11578       }else{
11579         while( c>='0' && c<='9' ){
11580           precision = precision*10 + c - '0';
11581           c = *++fmt;
11582         }
11583       }
11584     }else{
11585       precision = -1;
11586     }
11587     /* Get the conversion type modifier */
11588     if( c=='l' ){
11589       flag_long = 1;
11590       c = *++fmt;
11591       if( c=='l' ){
11592         flag_longlong = 1;
11593         c = *++fmt;
11594       }else{
11595         flag_longlong = 0;
11596       }
11597     }else{
11598       flag_long = flag_longlong = 0;
11599     }
11600     /* Fetch the info entry for the field */
11601     infop = 0;
11602     for(idx=0; idx<etNINFO; idx++){
11603       if( c==fmtinfo[idx].fmttype ){
11604         infop = &fmtinfo[idx];
11605         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
11606           xtype = infop->type;
11607         }else{
11608           return;
11609         }
11610         break;
11611       }
11612     }
11613     zExtra = 0;
11614     if( infop==0 ){
11615       return;
11616     }
11617
11618
11619     /* Limit the precision to prevent overflowing buf[] during conversion */
11620     if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
11621       precision = etBUFSIZE-40;
11622     }
11623
11624     /*
11625     ** At this point, variables are initialized as follows:
11626     **
11627     **   flag_alternateform          TRUE if a '#' is present.
11628     **   flag_altform2               TRUE if a '!' is present.
11629     **   flag_plussign               TRUE if a '+' is present.
11630     **   flag_leftjustify            TRUE if a '-' is present or if the
11631     **                               field width was negative.
11632     **   flag_zeropad                TRUE if the width began with 0.
11633     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
11634     **                               the conversion character.
11635     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
11636     **                               the conversion character.
11637     **   flag_blanksign              TRUE if a ' ' is present.
11638     **   width                       The specified field width.  This is
11639     **                               always non-negative.  Zero is the default.
11640     **   precision                   The specified precision.  The default
11641     **                               is -1.
11642     **   xtype                       The class of the conversion.
11643     **   infop                       Pointer to the appropriate info struct.
11644     */
11645     switch( xtype ){
11646       case etPOINTER:
11647         flag_longlong = sizeof(char*)==sizeof(i64);
11648         flag_long = sizeof(char*)==sizeof(long int);
11649         /* Fall through into the next case */
11650       case etORDINAL:
11651       case etRADIX:
11652         if( infop->flags & FLAG_SIGNED ){
11653           i64 v;
11654           if( flag_longlong )   v = va_arg(ap,i64);
11655           else if( flag_long )  v = va_arg(ap,long int);
11656           else                  v = va_arg(ap,int);
11657           if( v<0 ){
11658             longvalue = -v;
11659             prefix = '-';
11660           }else{
11661             longvalue = v;
11662             if( flag_plussign )        prefix = '+';
11663             else if( flag_blanksign )  prefix = ' ';
11664             else                       prefix = 0;
11665           }
11666         }else{
11667           if( flag_longlong )   longvalue = va_arg(ap,u64);
11668           else if( flag_long )  longvalue = va_arg(ap,unsigned long int);
11669           else                  longvalue = va_arg(ap,unsigned int);
11670           prefix = 0;
11671         }
11672         if( longvalue==0 ) flag_alternateform = 0;
11673         if( flag_zeropad && precision<width-(prefix!=0) ){
11674           precision = width-(prefix!=0);
11675         }
11676         bufpt = &buf[etBUFSIZE-1];
11677         if( xtype==etORDINAL ){
11678           static const char zOrd[] = "thstndrd";
11679           int x = longvalue % 10;
11680           if( x>=4 || (longvalue/10)%10==1 ){
11681             x = 0;
11682           }
11683           buf[etBUFSIZE-3] = zOrd[x*2];
11684           buf[etBUFSIZE-2] = zOrd[x*2+1];
11685           bufpt -= 2;
11686         }
11687         {
11688           register const char *cset;      /* Use registers for speed */
11689           register int base;
11690           cset = &aDigits[infop->charset];
11691           base = infop->base;
11692           do{                                           /* Convert to ascii */
11693             *(--bufpt) = cset[longvalue%base];
11694             longvalue = longvalue/base;
11695           }while( longvalue>0 );
11696         }
11697         length = &buf[etBUFSIZE-1]-bufpt;
11698         for(idx=precision-length; idx>0; idx--){
11699           *(--bufpt) = '0';                             /* Zero pad */
11700         }
11701         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
11702         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
11703           const char *pre;
11704           char x;
11705           pre = &aPrefix[infop->prefix];
11706           if( *bufpt!=pre[0] ){
11707             for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
11708           }
11709         }
11710         length = &buf[etBUFSIZE-1]-bufpt;
11711         break;
11712       case etFLOAT:
11713       case etEXP:
11714       case etGENERIC:
11715         realvalue = va_arg(ap,double);
11716 #ifndef SQLITE_OMIT_FLOATING_POINT
11717         if( precision<0 ) precision = 6;         /* Set default precision */
11718         if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
11719         if( realvalue<0.0 ){
11720           realvalue = -realvalue;
11721           prefix = '-';
11722         }else{
11723           if( flag_plussign )          prefix = '+';
11724           else if( flag_blanksign )    prefix = ' ';
11725           else                         prefix = 0;
11726         }
11727         if( xtype==etGENERIC && precision>0 ) precision--;
11728 #if 0
11729         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
11730         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
11731 #else
11732         /* It makes more sense to use 0.5 */
11733         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
11734 #endif
11735         if( xtype==etFLOAT ) realvalue += rounder;
11736         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
11737         exp = 0;
11738         if( sqlite3_isnan(realvalue) ){
11739           bufpt = "NaN";
11740           length = 3;
11741           break;
11742         }
11743         if( realvalue>0.0 ){
11744           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
11745           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
11746           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
11747           while( realvalue<1e-8 && exp>=-350 ){ realvalue *= 1e8; exp-=8; }
11748           while( realvalue<1.0 && exp>=-350 ){ realvalue *= 10.0; exp--; }
11749           if( exp>350 || exp<-350 ){
11750             if( prefix=='-' ){
11751               bufpt = "-Inf";
11752             }else if( prefix=='+' ){
11753               bufpt = "+Inf";
11754             }else{
11755               bufpt = "Inf";
11756             }
11757             length = strlen(bufpt);
11758             break;
11759           }
11760         }
11761         bufpt = buf;
11762         /*
11763         ** If the field type is etGENERIC, then convert to either etEXP
11764         ** or etFLOAT, as appropriate.
11765         */
11766         flag_exp = xtype==etEXP;
11767         if( xtype!=etFLOAT ){
11768           realvalue += rounder;
11769           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
11770         }
11771         if( xtype==etGENERIC ){
11772           flag_rtz = !flag_alternateform;
11773           if( exp<-4 || exp>precision ){
11774             xtype = etEXP;
11775           }else{
11776             precision = precision - exp;
11777             xtype = etFLOAT;
11778           }
11779         }else{
11780           flag_rtz = 0;
11781         }
11782         if( xtype==etEXP ){
11783           e2 = 0;
11784         }else{
11785           e2 = exp;
11786         }
11787         nsd = 0;
11788         flag_dp = (precision>0) | flag_alternateform | flag_altform2;
11789         /* The sign in front of the number */
11790         if( prefix ){
11791           *(bufpt++) = prefix;
11792         }
11793         /* Digits prior to the decimal point */
11794         if( e2<0 ){
11795           *(bufpt++) = '0';
11796         }else{
11797           for(; e2>=0; e2--){
11798             *(bufpt++) = et_getdigit(&realvalue,&nsd);
11799           }
11800         }
11801         /* The decimal point */
11802         if( flag_dp ){
11803           *(bufpt++) = '.';
11804         }
11805         /* "0" digits after the decimal point but before the first
11806         ** significant digit of the number */
11807         for(e2++; e2<0 && precision>0; precision--, e2++){
11808           *(bufpt++) = '0';
11809         }
11810         /* Significant digits after the decimal point */
11811         while( (precision--)>0 ){
11812           *(bufpt++) = et_getdigit(&realvalue,&nsd);
11813         }
11814         /* Remove trailing zeros and the "." if no digits follow the "." */
11815         if( flag_rtz && flag_dp ){
11816           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
11817           assert( bufpt>buf );
11818           if( bufpt[-1]=='.' ){
11819             if( flag_altform2 ){
11820               *(bufpt++) = '0';
11821             }else{
11822               *(--bufpt) = 0;
11823             }
11824           }
11825         }
11826         /* Add the "eNNN" suffix */
11827         if( flag_exp || (xtype==etEXP && exp) ){
11828           *(bufpt++) = aDigits[infop->charset];
11829           if( exp<0 ){
11830             *(bufpt++) = '-'; exp = -exp;
11831           }else{
11832             *(bufpt++) = '+';
11833           }
11834           if( exp>=100 ){
11835             *(bufpt++) = (exp/100)+'0';                /* 100's digit */
11836             exp %= 100;
11837           }
11838           *(bufpt++) = exp/10+'0';                     /* 10's digit */
11839           *(bufpt++) = exp%10+'0';                     /* 1's digit */
11840         }
11841         *bufpt = 0;
11842
11843         /* The converted number is in buf[] and zero terminated. Output it.
11844         ** Note that the number is in the usual order, not reversed as with
11845         ** integer conversions. */
11846         length = bufpt-buf;
11847         bufpt = buf;
11848
11849         /* Special case:  Add leading zeros if the flag_zeropad flag is
11850         ** set and we are not left justified */
11851         if( flag_zeropad && !flag_leftjustify && length < width){
11852           int i;
11853           int nPad = width - length;
11854           for(i=width; i>=nPad; i--){
11855             bufpt[i] = bufpt[i-nPad];
11856           }
11857           i = prefix!=0;
11858           while( nPad-- ) bufpt[i++] = '0';
11859           length = width;
11860         }
11861 #endif
11862         break;
11863       case etSIZE:
11864         *(va_arg(ap,int*)) = pAccum->nChar;
11865         length = width = 0;
11866         break;
11867       case etPERCENT:
11868         buf[0] = '%';
11869         bufpt = buf;
11870         length = 1;
11871         break;
11872       case etCHARLIT:
11873       case etCHARX:
11874         c = buf[0] = (xtype==etCHARX ? va_arg(ap,int) : *++fmt);
11875         if( precision>=0 ){
11876           for(idx=1; idx<precision; idx++) buf[idx] = c;
11877           length = precision;
11878         }else{
11879           length =1;
11880         }
11881         bufpt = buf;
11882         break;
11883       case etSTRING:
11884       case etDYNSTRING:
11885         bufpt = va_arg(ap,char*);
11886         if( bufpt==0 ){
11887           bufpt = "";
11888         }else if( xtype==etDYNSTRING ){
11889           zExtra = bufpt;
11890         }
11891         length = strlen(bufpt);
11892         if( precision>=0 && precision<length ) length = precision;
11893         break;
11894       case etSQLESCAPE:
11895       case etSQLESCAPE2:
11896       case etSQLESCAPE3: {
11897         int i, j, n, ch, isnull;
11898         int needQuote;
11899         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
11900         char *escarg = va_arg(ap,char*);
11901         isnull = escarg==0;
11902         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
11903         for(i=n=0; (ch=escarg[i])!=0; i++){
11904           if( ch==q )  n++;
11905         }
11906         needQuote = !isnull && xtype==etSQLESCAPE2;
11907         n += i + 1 + needQuote*2;
11908         if( n>etBUFSIZE ){
11909           bufpt = zExtra = sqlite3_malloc( n );
11910           if( bufpt==0 ) return;
11911         }else{
11912           bufpt = buf;
11913         }
11914         j = 0;
11915         if( needQuote ) bufpt[j++] = q;
11916         for(i=0; (ch=escarg[i])!=0; i++){
11917           bufpt[j++] = ch;
11918           if( ch==q ) bufpt[j++] = ch;
11919         }
11920         if( needQuote ) bufpt[j++] = q;
11921         bufpt[j] = 0;
11922         length = j;
11923         /* The precision is ignored on %q and %Q */
11924         /* if( precision>=0 && precision<length ) length = precision; */
11925         break;
11926       }
11927       case etTOKEN: {
11928         Token *pToken = va_arg(ap, Token*);
11929         if( pToken && pToken->z ){
11930           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
11931         }
11932         length = width = 0;
11933         break;
11934       }
11935       case etSRCLIST: {
11936         SrcList *pSrc = va_arg(ap, SrcList*);
11937         int k = va_arg(ap, int);
11938         struct SrcList_item *pItem = &pSrc->a[k];
11939         assert( k>=0 && k<pSrc->nSrc );
11940         if( pItem->zDatabase && pItem->zDatabase[0] ){
11941           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
11942           sqlite3StrAccumAppend(pAccum, ".", 1);
11943         }
11944         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
11945         length = width = 0;
11946         break;
11947       }
11948     }/* End switch over the format type */
11949     /*
11950     ** The text of the conversion is pointed to by "bufpt" and is
11951     ** "length" characters long.  The field width is "width".  Do
11952     ** the output.
11953     */
11954     if( !flag_leftjustify ){
11955       register int nspace;
11956       nspace = width-length;
11957       if( nspace>0 ){
11958         appendSpace(pAccum, nspace);
11959       }
11960     }
11961     if( length>0 ){
11962       sqlite3StrAccumAppend(pAccum, bufpt, length);
11963     }
11964     if( flag_leftjustify ){
11965       register int nspace;
11966       nspace = width-length;
11967       if( nspace>0 ){
11968         appendSpace(pAccum, nspace);
11969       }
11970     }
11971     if( zExtra ){
11972       sqlite3_free(zExtra);
11973     }
11974   }/* End for loop over the format string */
11975 } /* End of function */
11976
11977 /*
11978 ** Append N bytes of text from z to the StrAccum object.
11979 */
11980 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
11981   if( p->tooBig | p->mallocFailed ){
11982     return;
11983   }
11984   if( N<0 ){
11985     N = strlen(z);
11986   }
11987   if( N==0 ){
11988     return;
11989   }
11990   if( p->nChar+N >= p->nAlloc ){
11991     char *zNew;
11992     if( !p->useMalloc ){
11993       p->tooBig = 1;
11994       N = p->nAlloc - p->nChar - 1;
11995       if( N<=0 ){
11996         return;
11997       }
11998     }else{
11999       p->nAlloc += p->nAlloc + N + 1;
12000       if( p->nAlloc > SQLITE_MAX_LENGTH ){
12001         p->nAlloc = SQLITE_MAX_LENGTH;
12002         if( p->nChar+N >= p->nAlloc ){
12003           sqlite3StrAccumReset(p);
12004           p->tooBig = 1;
12005           return;
12006         }
12007       }
12008       zNew = sqlite3_malloc( p->nAlloc );
12009       if( zNew ){
12010         memcpy(zNew, p->zText, p->nChar);
12011         sqlite3StrAccumReset(p);
12012         p->zText = zNew;
12013       }else{
12014         p->mallocFailed = 1;
12015         sqlite3StrAccumReset(p);
12016         return;
12017       }
12018     }
12019   }
12020   memcpy(&p->zText[p->nChar], z, N);
12021   p->nChar += N;
12022 }
12023
12024 /*
12025 ** Finish off a string by making sure it is zero-terminated.
12026 ** Return a pointer to the resulting string.  Return a NULL
12027 ** pointer if any kind of error was encountered.
12028 */
12029 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
12030   if( p->zText ){
12031     p->zText[p->nChar] = 0;
12032     if( p->useMalloc && p->zText==p->zBase ){
12033       p->zText = sqlite3_malloc( p->nChar+1 );
12034       if( p->zText ){
12035         memcpy(p->zText, p->zBase, p->nChar+1);
12036       }else{
12037         p->mallocFailed = 1;
12038       }
12039     }
12040   }
12041   return p->zText;
12042 }
12043
12044 /*
12045 ** Reset an StrAccum string.  Reclaim all malloced memory.
12046 */
12047 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
12048   if( p->zText!=p->zBase ){
12049     sqlite3_free(p->zText);
12050     p->zText = 0;
12051   }
12052 }
12053
12054 /*
12055 ** Initialize a string accumulator
12056 */
12057 static void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n){
12058   p->zText = p->zBase = zBase;
12059   p->nChar = 0;
12060   p->nAlloc = n;
12061   p->useMalloc = 1;
12062   p->tooBig = 0;
12063   p->mallocFailed = 0;
12064 }
12065
12066 /*
12067 ** Print into memory obtained from sqliteMalloc().  Use the internal
12068 ** %-conversion extensions.
12069 */
12070 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
12071   char *z;
12072   char zBase[SQLITE_PRINT_BUF_SIZE];
12073   StrAccum acc;
12074   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase));
12075   vxprintf(&acc, 1, zFormat, ap);
12076   z = sqlite3StrAccumFinish(&acc);
12077   if( acc.mallocFailed && db ){
12078     db->mallocFailed = 1;
12079   }
12080   return z;
12081 }
12082
12083 /*
12084 ** Print into memory obtained from sqliteMalloc().  Use the internal
12085 ** %-conversion extensions.
12086 */
12087 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
12088   va_list ap;
12089   char *z;
12090   va_start(ap, zFormat);
12091   z = sqlite3VMPrintf(db, zFormat, ap);
12092   va_end(ap);
12093   return z;
12094 }
12095
12096 /*
12097 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
12098 ** %-conversion extensions.
12099 */
12100 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
12101   char *z;
12102   char zBase[SQLITE_PRINT_BUF_SIZE];
12103   StrAccum acc;
12104   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase));
12105   vxprintf(&acc, 0, zFormat, ap);
12106   z = sqlite3StrAccumFinish(&acc);
12107   return z;
12108 }
12109
12110 /*
12111 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
12112 ** %-conversion extensions.
12113 */
12114 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
12115   va_list ap;
12116   char *z;
12117   va_start(ap, zFormat);
12118   z = sqlite3_vmprintf(zFormat, ap);
12119   va_end(ap);
12120   return z;
12121 }
12122
12123 /*
12124 ** sqlite3_snprintf() works like snprintf() except that it ignores the
12125 ** current locale settings.  This is important for SQLite because we
12126 ** are not able to use a "," as the decimal point in place of "." as
12127 ** specified by some locales.
12128 */
12129 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
12130   char *z;
12131   va_list ap;
12132   StrAccum acc;
12133
12134   if( n<=0 ){
12135     return zBuf;
12136   }
12137   sqlite3StrAccumInit(&acc, zBuf, n);
12138   acc.useMalloc = 0;
12139   va_start(ap,zFormat);
12140   vxprintf(&acc, 0, zFormat, ap);
12141   va_end(ap);
12142   z = sqlite3StrAccumFinish(&acc);
12143   return z;
12144 }
12145
12146 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) || defined(SQLITE_MEMDEBUG)
12147 /*
12148 ** A version of printf() that understands %lld.  Used for debugging.
12149 ** The printf() built into some versions of windows does not understand %lld
12150 ** and segfaults if you give it a long long int.
12151 */
12152 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
12153   va_list ap;
12154   StrAccum acc;
12155   char zBuf[500];
12156   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf));
12157   acc.useMalloc = 0;
12158   va_start(ap,zFormat);
12159   vxprintf(&acc, 0, zFormat, ap);
12160   va_end(ap);
12161   sqlite3StrAccumFinish(&acc);
12162   fprintf(stdout,"%s", zBuf);
12163   fflush(stdout);
12164 }
12165 #endif
12166
12167 /************** End of printf.c **********************************************/
12168 /************** Begin file random.c ******************************************/
12169 /*
12170 ** 2001 September 15
12171 **
12172 ** The author disclaims copyright to this source code.  In place of
12173 ** a legal notice, here is a blessing:
12174 **
12175 **    May you do good and not evil.
12176 **    May you find forgiveness for yourself and forgive others.
12177 **    May you share freely, never taking more than you give.
12178 **
12179 *************************************************************************
12180 ** This file contains code to implement a pseudo-random number
12181 ** generator (PRNG) for SQLite.
12182 **
12183 ** Random numbers are used by some of the database backends in order
12184 ** to generate random integer keys for tables or random filenames.
12185 **
12186 ** $Id: random.c,v 1.20 2007/08/21 13:51:23 drh Exp $
12187 */
12188
12189
12190 /*
12191 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
12192 ** must be held while executing this routine.
12193 **
12194 ** Why not just use a library random generator like lrand48() for this?
12195 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
12196 ** good source of random numbers.  The lrand48() library function may
12197 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
12198 ** subtle problems on some systems that could cause problems.  It is hard
12199 ** to know.  To minimize the risk of problems due to bad lrand48()
12200 ** implementations, SQLite uses this random number generator based
12201 ** on RC4, which we know works very well.
12202 **
12203 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
12204 ** randomness any more.  But we will leave this code in all the same.
12205 */
12206 static int randomByte(void){
12207   unsigned char t;
12208
12209   /* All threads share a single random number generator.
12210   ** This structure is the current state of the generator.
12211   */
12212   static struct {
12213     unsigned char isInit;          /* True if initialized */
12214     unsigned char i, j;            /* State variables */
12215     unsigned char s[256];          /* State variables */
12216   } prng;
12217
12218   /* Initialize the state of the random number generator once,
12219   ** the first time this routine is called.  The seed value does
12220   ** not need to contain a lot of randomness since we are not
12221   ** trying to do secure encryption or anything like that...
12222   **
12223   ** Nothing in this file or anywhere else in SQLite does any kind of
12224   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
12225   ** number generator) not as an encryption device.
12226   */
12227   if( !prng.isInit ){
12228     int i;
12229     char k[256];
12230     prng.j = 0;
12231     prng.i = 0;
12232     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
12233     for(i=0; i<256; i++){
12234       prng.s[i] = i;
12235     }
12236     for(i=0; i<256; i++){
12237       prng.j += prng.s[i] + k[i];
12238       t = prng.s[prng.j];
12239       prng.s[prng.j] = prng.s[i];
12240       prng.s[i] = t;
12241     }
12242     prng.isInit = 1;
12243   }
12244
12245   /* Generate and return single random byte
12246   */
12247   prng.i++;
12248   t = prng.s[prng.i];
12249   prng.j += t;
12250   prng.s[prng.i] = prng.s[prng.j];
12251   prng.s[prng.j] = t;
12252   t += prng.s[prng.i];
12253   return prng.s[t];
12254 }
12255
12256 /*
12257 ** Return N random bytes.
12258 */
12259 SQLITE_PRIVATE void sqlite3Randomness(int N, void *pBuf){
12260   unsigned char *zBuf = pBuf;
12261   static sqlite3_mutex *mutex = 0;
12262   if( mutex==0 ){
12263     mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PRNG);
12264   }
12265   sqlite3_mutex_enter(mutex);
12266   while( N-- ){
12267     *(zBuf++) = randomByte();
12268   }
12269   sqlite3_mutex_leave(mutex);
12270 }
12271
12272 /************** End of random.c **********************************************/
12273 /************** Begin file utf.c *********************************************/
12274 /*
12275 ** 2004 April 13
12276 **
12277 ** The author disclaims copyright to this source code.  In place of
12278 ** a legal notice, here is a blessing:
12279 **
12280 **    May you do good and not evil.
12281 **    May you find forgiveness for yourself and forgive others.
12282 **    May you share freely, never taking more than you give.
12283 **
12284 *************************************************************************
12285 ** This file contains routines used to translate between UTF-8, 
12286 ** UTF-16, UTF-16BE, and UTF-16LE.
12287 **
12288 ** $Id: utf.c,v 1.59 2007/10/03 08:46:45 danielk1977 Exp $
12289 **
12290 ** Notes on UTF-8:
12291 **
12292 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
12293 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
12294 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
12295 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
12296 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
12297 **
12298 **
12299 ** Notes on UTF-16:  (with wwww+1==uuuuu)
12300 **
12301 **      Word-0               Word-1          Value
12302 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
12303 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
12304 **
12305 **
12306 ** BOM or Byte Order Mark:
12307 **     0xff 0xfe   little-endian utf-16 follows
12308 **     0xfe 0xff   big-endian utf-16 follows
12309 **
12310 */
12311 /************** Include vdbeInt.h in the middle of utf.c *********************/
12312 /************** Begin file vdbeInt.h *****************************************/
12313 /*
12314 ** 2003 September 6
12315 **
12316 ** The author disclaims copyright to this source code.  In place of
12317 ** a legal notice, here is a blessing:
12318 **
12319 **    May you do good and not evil.
12320 **    May you find forgiveness for yourself and forgive others.
12321 **    May you share freely, never taking more than you give.
12322 **
12323 *************************************************************************
12324 ** This is the header file for information that is private to the
12325 ** VDBE.  This information used to all be at the top of the single
12326 ** source code file "vdbe.c".  When that file became too big (over
12327 ** 6000 lines long) it was split up into several smaller files and
12328 ** this header information was factored out.
12329 */
12330 #ifndef _VDBEINT_H_
12331 #define _VDBEINT_H_
12332
12333 /*
12334 ** intToKey() and keyToInt() used to transform the rowid.  But with
12335 ** the latest versions of the design they are no-ops.
12336 */
12337 #define keyToInt(X)   (X)
12338 #define intToKey(X)   (X)
12339
12340
12341 /*
12342 ** SQL is translated into a sequence of instructions to be
12343 ** executed by a virtual machine.  Each instruction is an instance
12344 ** of the following structure.
12345 */
12346 typedef struct VdbeOp Op;
12347
12348 /*
12349 ** Boolean values
12350 */
12351 typedef unsigned char Bool;
12352
12353 /*
12354 ** A cursor is a pointer into a single BTree within a database file.
12355 ** The cursor can seek to a BTree entry with a particular key, or
12356 ** loop over all entries of the Btree.  You can also insert new BTree
12357 ** entries or retrieve the key or data from the entry that the cursor
12358 ** is currently pointing to.
12359 ** 
12360 ** Every cursor that the virtual machine has open is represented by an
12361 ** instance of the following structure.
12362 **
12363 ** If the Cursor.isTriggerRow flag is set it means that this cursor is
12364 ** really a single row that represents the NEW or OLD pseudo-table of
12365 ** a row trigger.  The data for the row is stored in Cursor.pData and
12366 ** the rowid is in Cursor.iKey.
12367 */
12368 struct Cursor {
12369   BtCursor *pCursor;    /* The cursor structure of the backend */
12370   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
12371   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
12372   i64 nextRowid;        /* Next rowid returned by OP_NewRowid */
12373   Bool zeroed;          /* True if zeroed out and ready for reuse */
12374   Bool rowidIsValid;    /* True if lastRowid is valid */
12375   Bool atFirst;         /* True if pointing to first entry */
12376   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
12377   Bool nullRow;         /* True if pointing to a row with no data */
12378   Bool nextRowidValid;  /* True if the nextRowid field is valid */
12379   Bool pseudoTable;     /* This is a NEW or OLD pseudo-tables of a trigger */
12380   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
12381   Bool isTable;         /* True if a table requiring integer keys */
12382   Bool isIndex;         /* True if an index containing keys only - no data */
12383   u8 bogusIncrKey;      /* Something for pIncrKey to point to if pKeyInfo==0 */
12384   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
12385   Btree *pBt;           /* Separate file holding temporary table */
12386   int nData;            /* Number of bytes in pData */
12387   char *pData;          /* Data for a NEW or OLD pseudo-table */
12388   i64 iKey;             /* Key for the NEW or OLD pseudo-table row */
12389   u8 *pIncrKey;         /* Pointer to pKeyInfo->incrKey */
12390   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
12391   int nField;           /* Number of fields in the header */
12392   i64 seqCount;         /* Sequence counter */
12393   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
12394   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
12395
12396   /* Cached information about the header for the data record that the
12397   ** cursor is currently pointing to.  Only valid if cacheValid is true.
12398   ** aRow might point to (ephemeral) data for the current row, or it might
12399   ** be NULL.
12400   */
12401   int cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
12402   int payloadSize;      /* Total number of bytes in the record */
12403   u32 *aType;           /* Type values for all entries in the record */
12404   u32 *aOffset;         /* Cached offsets to the start of each columns data */
12405   u8 *aRow;             /* Data for the current row, if all on one page */
12406 };
12407 typedef struct Cursor Cursor;
12408
12409 /*
12410 ** Number of bytes of string storage space available to each stack
12411 ** layer without having to malloc.  NBFS is short for Number of Bytes
12412 ** For Strings.
12413 */
12414 #define NBFS 32
12415
12416 /*
12417 ** A value for Cursor.cacheValid that means the cache is always invalid.
12418 */
12419 #define CACHE_STALE 0
12420
12421 /*
12422 ** Internally, the vdbe manipulates nearly all SQL values as Mem
12423 ** structures. Each Mem struct may cache multiple representations (string,
12424 ** integer etc.) of the same value.  A value (and therefore Mem structure)
12425 ** has the following properties:
12426 **
12427 ** Each value has a manifest type. The manifest type of the value stored
12428 ** in a Mem struct is returned by the MemType(Mem*) macro. The type is
12429 ** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
12430 ** SQLITE_BLOB.
12431 */
12432 struct Mem {
12433   union {
12434     i64 i;              /* Integer value. Or FuncDef* when flags==MEM_Agg */
12435     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
12436   } u;
12437   double r;           /* Real value */
12438   sqlite3 *db;        /* The associated database connection */
12439   char *z;            /* String or BLOB value */
12440   int n;              /* Number of characters in string value, including '\0' */
12441   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
12442   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
12443   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
12444   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
12445   char zShort[NBFS];  /* Space for short strings */
12446 };
12447 typedef struct Mem Mem;
12448
12449 /* One or more of the following flags are set to indicate the validOK
12450 ** representations of the value stored in the Mem struct.
12451 **
12452 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
12453 ** No other flags may be set in this case.
12454 **
12455 ** If the MEM_Str flag is set then Mem.z points at a string representation.
12456 ** Usually this is encoded in the same unicode encoding as the main
12457 ** database (see below for exceptions). If the MEM_Term flag is also
12458 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
12459 ** flags may coexist with the MEM_Str flag.
12460 **
12461 ** Multiple of these values can appear in Mem.flags.  But only one
12462 ** at a time can appear in Mem.type.
12463 */
12464 #define MEM_Null      0x0001   /* Value is NULL */
12465 #define MEM_Str       0x0002   /* Value is a string */
12466 #define MEM_Int       0x0004   /* Value is an integer */
12467 #define MEM_Real      0x0008   /* Value is a real number */
12468 #define MEM_Blob      0x0010   /* Value is a BLOB */
12469
12470 /* Whenever Mem contains a valid string or blob representation, one of
12471 ** the following flags must be set to determine the memory management
12472 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
12473 ** string is \000 or \u0000 terminated
12474 */
12475 #define MEM_Term      0x0020   /* String rep is nul terminated */
12476 #define MEM_Dyn       0x0040   /* Need to call sqliteFree() on Mem.z */
12477 #define MEM_Static    0x0080   /* Mem.z points to a static string */
12478 #define MEM_Ephem     0x0100   /* Mem.z points to an ephemeral string */
12479 #define MEM_Short     0x0200   /* Mem.z points to Mem.zShort */
12480 #define MEM_Agg       0x0400   /* Mem.z points to an agg function context */
12481 #define MEM_Zero      0x0800   /* Mem.i contains count of 0s appended to blob */
12482
12483 #ifdef SQLITE_OMIT_INCRBLOB
12484   #undef MEM_Zero
12485   #define MEM_Zero 0x0000
12486 #endif
12487
12488
12489 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
12490 ** additional information about auxiliary information bound to arguments
12491 ** of the function.  This is used to implement the sqlite3_get_auxdata()
12492 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
12493 ** that can be associated with a constant argument to a function.  This
12494 ** allows functions such as "regexp" to compile their constant regular
12495 ** expression argument once and reused the compiled code for multiple
12496 ** invocations.
12497 */
12498 struct VdbeFunc {
12499   FuncDef *pFunc;               /* The definition of the function */
12500   int nAux;                     /* Number of entries allocated for apAux[] */
12501   struct AuxData {
12502     void *pAux;                   /* Aux data for the i-th argument */
12503     void (*xDelete)(void *);      /* Destructor for the aux data */
12504   } apAux[1];                   /* One slot for each function argument */
12505 };
12506 typedef struct VdbeFunc VdbeFunc;
12507
12508 /*
12509 ** The "context" argument for a installable function.  A pointer to an
12510 ** instance of this structure is the first argument to the routines used
12511 ** implement the SQL functions.
12512 **
12513 ** There is a typedef for this structure in sqlite.h.  So all routines,
12514 ** even the public interface to SQLite, can use a pointer to this structure.
12515 ** But this file is the only place where the internal details of this
12516 ** structure are known.
12517 **
12518 ** This structure is defined inside of vdbeInt.h because it uses substructures
12519 ** (Mem) which are only defined there.
12520 */
12521 struct sqlite3_context {
12522   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
12523   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
12524   Mem s;                /* The return value is stored here */
12525   Mem *pMem;            /* Memory cell used to store aggregate context */
12526   u8 isError;           /* Set to true for an error */
12527   CollSeq *pColl;       /* Collating sequence */
12528 };
12529
12530 /*
12531 ** A Set structure is used for quick testing to see if a value
12532 ** is part of a small set.  Sets are used to implement code like
12533 ** this:
12534 **            x.y IN ('hi','hoo','hum')
12535 */
12536 typedef struct Set Set;
12537 struct Set {
12538   Hash hash;             /* A set is just a hash table */
12539   HashElem *prev;        /* Previously accessed hash elemen */
12540 };
12541
12542 /*
12543 ** A FifoPage structure holds a single page of valves.  Pages are arranged
12544 ** in a list.
12545 */
12546 typedef struct FifoPage FifoPage;
12547 struct FifoPage {
12548   int nSlot;         /* Number of entries aSlot[] */
12549   int iWrite;        /* Push the next value into this entry in aSlot[] */
12550   int iRead;         /* Read the next value from this entry in aSlot[] */
12551   FifoPage *pNext;   /* Next page in the fifo */
12552   i64 aSlot[1];      /* One or more slots for rowid values */
12553 };
12554
12555 /*
12556 ** The Fifo structure is typedef-ed in vdbeInt.h.  But the implementation
12557 ** of that structure is private to this file.
12558 **
12559 ** The Fifo structure describes the entire fifo.  
12560 */
12561 typedef struct Fifo Fifo;
12562 struct Fifo {
12563   int nEntry;         /* Total number of entries */
12564   FifoPage *pFirst;   /* First page on the list */
12565   FifoPage *pLast;    /* Last page on the list */
12566 };
12567
12568 /*
12569 ** A Context stores the last insert rowid, the last statement change count,
12570 ** and the current statement change count (i.e. changes since last statement).
12571 ** The current keylist is also stored in the context.
12572 ** Elements of Context structure type make up the ContextStack, which is
12573 ** updated by the ContextPush and ContextPop opcodes (used by triggers).
12574 ** The context is pushed before executing a trigger a popped when the
12575 ** trigger finishes.
12576 */
12577 typedef struct Context Context;
12578 struct Context {
12579   i64 lastRowid;    /* Last insert rowid (sqlite3.lastRowid) */
12580   int nChange;      /* Statement changes (Vdbe.nChanges)     */
12581   Fifo sFifo;       /* Records that will participate in a DELETE or UPDATE */
12582 };
12583
12584 /*
12585 ** An instance of the virtual machine.  This structure contains the complete
12586 ** state of the virtual machine.
12587 **
12588 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
12589 ** is really a pointer to an instance of this structure.
12590 **
12591 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
12592 ** any virtual table method invocations made by the vdbe program. It is
12593 ** set to 2 for xDestroy method calls and 1 for all other methods. This
12594 ** variable is used for two purposes: to allow xDestroy methods to execute
12595 ** "DROP TABLE" statements and to prevent some nasty side effects of
12596 ** malloc failure when SQLite is invoked recursively by a virtual table 
12597 ** method function.
12598 */
12599 struct Vdbe {
12600   sqlite3 *db;        /* The whole database */
12601   Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
12602   int nOp;            /* Number of instructions in the program */
12603   int nOpAlloc;       /* Number of slots allocated for aOp[] */
12604   Op *aOp;            /* Space to hold the virtual machine's program */
12605   int nLabel;         /* Number of labels used */
12606   int nLabelAlloc;    /* Number of slots allocated in aLabel[] */
12607   int *aLabel;        /* Space to hold the labels */
12608   Mem *aStack;        /* The operand stack, except string values */
12609   Mem *pTos;          /* Top entry in the operand stack */
12610   Mem **apArg;        /* Arguments to currently executing user function */
12611   Mem *aColName;      /* Column names to return */
12612   int nCursor;        /* Number of slots in apCsr[] */
12613   Cursor **apCsr;     /* One element of this array for each open cursor */
12614   int nVar;           /* Number of entries in aVar[] */
12615   Mem *aVar;          /* Values for the OP_Variable opcode. */
12616   char **azVar;       /* Name of variables */
12617   int okVar;          /* True if azVar[] has been initialized */
12618   int magic;              /* Magic number for sanity checking */
12619   int nMem;               /* Number of memory locations currently allocated */
12620   Mem *aMem;              /* The memory locations */
12621   int nCallback;          /* Number of callbacks invoked so far */
12622   int cacheCtr;           /* Cursor row cache generation counter */
12623   Fifo sFifo;             /* A list of ROWIDs */
12624   int contextStackTop;    /* Index of top element in the context stack */
12625   int contextStackDepth;  /* The size of the "context" stack */
12626   Context *contextStack;  /* Stack used by opcodes ContextPush & ContextPop*/
12627   int pc;                 /* The program counter */
12628   int rc;                 /* Value to return */
12629   unsigned uniqueCnt;     /* Used by OP_MakeRecord when P2!=0 */
12630   int errorAction;        /* Recovery action to do in case of an error */
12631   int inTempTrans;        /* True if temp database is transactioned */
12632   int returnStack[25];    /* Return address stack for OP_Gosub & OP_Return */
12633   int returnDepth;        /* Next unused element in returnStack[] */
12634   int nResColumn;         /* Number of columns in one row of the result set */
12635   char **azResColumn;     /* Values for one row of result */ 
12636   int popStack;           /* Pop the stack this much on entry to VdbeExec() */
12637   char *zErrMsg;          /* Error message written here */
12638   u8 resOnStack;          /* True if there are result values on the stack */
12639   u8 explain;             /* True if EXPLAIN present on SQL command */
12640   u8 changeCntOn;         /* True to update the change-counter */
12641   u8 aborted;             /* True if ROLLBACK in another VM causes an abort */
12642   u8 expired;             /* True if the VM needs to be recompiled */
12643   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
12644   u8 inVtabMethod;        /* See comments above */
12645   int nChange;            /* Number of db changes made since last reset */
12646   i64 startTime;          /* Time when query started - used for profiling */
12647   int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
12648   BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
12649   int nSql;             /* Number of bytes in zSql */
12650   char *zSql;           /* Text of the SQL statement that generated this */
12651 #ifdef SQLITE_DEBUG
12652   FILE *trace;        /* Write an execution trace here, if not NULL */
12653 #endif
12654   int openedStatement;  /* True if this VM has opened a statement journal */
12655 #ifdef SQLITE_SSE
12656   int fetchId;          /* Statement number used by sqlite3_fetch_statement */
12657   int lru;              /* Counter used for LRU cache replacement */
12658 #endif
12659 };
12660
12661 /*
12662 ** The following are allowed values for Vdbe.magic
12663 */
12664 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
12665 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
12666 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
12667 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
12668
12669 /*
12670 ** Function prototypes
12671 */
12672 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, Cursor*);
12673 void sqliteVdbePopStack(Vdbe*,int);
12674 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(Cursor*);
12675 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
12676 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
12677 #endif
12678 SQLITE_PRIVATE int sqlite3VdbeSerialTypeLen(u32);
12679 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
12680 SQLITE_PRIVATE int sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
12681 SQLITE_PRIVATE int sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
12682 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
12683
12684 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
12685 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(Cursor*,int,const unsigned char*,int*);
12686 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(BtCursor *, i64 *);
12687 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
12688 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(void*,int,const void*,int, const void*);
12689 SQLITE_PRIVATE int sqlite3VdbeIdxRowidLen(const u8*);
12690 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
12691 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
12692 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
12693 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
12694 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
12695 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
12696 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
12697 SQLITE_PRIVATE int sqlite3VdbeMemMove(Mem*, Mem*);
12698 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
12699 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
12700 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
12701 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
12702 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
12703 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
12704 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
12705 SQLITE_PRIVATE int sqlite3VdbeMemDynamicify(Mem*);
12706 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
12707 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
12708 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
12709 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
12710 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
12711 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
12712 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
12713 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
12714 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
12715 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
12716 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
12717
12718 #ifndef NDEBUG
12719 SQLITE_PRIVATE   void sqlite3VdbeMemSanity(Mem*);
12720 SQLITE_PRIVATE   int sqlite3VdbeOpcodeNoPush(u8);
12721 #endif
12722 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
12723 #ifdef SQLITE_DEBUG
12724 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
12725 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
12726 #endif
12727 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
12728 SQLITE_PRIVATE void sqlite3VdbeFifoInit(Fifo*);
12729 SQLITE_PRIVATE int sqlite3VdbeFifoPush(Fifo*, i64);
12730 SQLITE_PRIVATE int sqlite3VdbeFifoPop(Fifo*, i64*);
12731 SQLITE_PRIVATE void sqlite3VdbeFifoClear(Fifo*);
12732
12733 #ifndef SQLITE_OMIT_INCRBLOB
12734 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
12735 #else
12736   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
12737 #endif
12738
12739 #endif /* !defined(_VDBEINT_H_) */
12740
12741 /************** End of vdbeInt.h *********************************************/
12742 /************** Continuing where we left off in utf.c ************************/
12743
12744 /*
12745 ** The following constant value is used by the SQLITE_BIGENDIAN and
12746 ** SQLITE_LITTLEENDIAN macros.
12747 */
12748 SQLITE_PRIVATE const int sqlite3one = 1;
12749
12750 /*
12751 ** This lookup table is used to help decode the first byte of
12752 ** a multi-byte UTF8 character.
12753 */
12754 static const unsigned char sqlite3UtfTrans1[] = {
12755   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
12756   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
12757   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
12758   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
12759   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
12760   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
12761   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
12762   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
12763 };
12764
12765
12766 #define WRITE_UTF8(zOut, c) {                          \
12767   if( c<0x00080 ){                                     \
12768     *zOut++ = (c&0xFF);                                \
12769   }                                                    \
12770   else if( c<0x00800 ){                                \
12771     *zOut++ = 0xC0 + ((c>>6)&0x1F);                    \
12772     *zOut++ = 0x80 + (c & 0x3F);                       \
12773   }                                                    \
12774   else if( c<0x10000 ){                                \
12775     *zOut++ = 0xE0 + ((c>>12)&0x0F);                   \
12776     *zOut++ = 0x80 + ((c>>6) & 0x3F);                  \
12777     *zOut++ = 0x80 + (c & 0x3F);                       \
12778   }else{                                               \
12779     *zOut++ = 0xF0 + ((c>>18) & 0x07);                 \
12780     *zOut++ = 0x80 + ((c>>12) & 0x3F);                 \
12781     *zOut++ = 0x80 + ((c>>6) & 0x3F);                  \
12782     *zOut++ = 0x80 + (c & 0x3F);                       \
12783   }                                                    \
12784 }
12785
12786 #define WRITE_UTF16LE(zOut, c) {                                \
12787   if( c<=0xFFFF ){                                              \
12788     *zOut++ = (c&0x00FF);                                       \
12789     *zOut++ = ((c>>8)&0x00FF);                                  \
12790   }else{                                                        \
12791     *zOut++ = (((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
12792     *zOut++ = (0x00D8 + (((c-0x10000)>>18)&0x03));              \
12793     *zOut++ = (c&0x00FF);                                       \
12794     *zOut++ = (0x00DC + ((c>>8)&0x03));                         \
12795   }                                                             \
12796 }
12797
12798 #define WRITE_UTF16BE(zOut, c) {                                \
12799   if( c<=0xFFFF ){                                              \
12800     *zOut++ = ((c>>8)&0x00FF);                                  \
12801     *zOut++ = (c&0x00FF);                                       \
12802   }else{                                                        \
12803     *zOut++ = (0x00D8 + (((c-0x10000)>>18)&0x03));              \
12804     *zOut++ = (((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
12805     *zOut++ = (0x00DC + ((c>>8)&0x03));                         \
12806     *zOut++ = (c&0x00FF);                                       \
12807   }                                                             \
12808 }
12809
12810 #define READ_UTF16LE(zIn, c){                                         \
12811   c = (*zIn++);                                                       \
12812   c += ((*zIn++)<<8);                                                 \
12813   if( c>=0xD800 && c<0xE000 ){                                       \
12814     int c2 = (*zIn++);                                                \
12815     c2 += ((*zIn++)<<8);                                              \
12816     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
12817     if( (c & 0xFFFF0000)==0 ) c = 0xFFFD;                             \
12818   }                                                                   \
12819 }
12820
12821 #define READ_UTF16BE(zIn, c){                                         \
12822   c = ((*zIn++)<<8);                                                  \
12823   c += (*zIn++);                                                      \
12824   if( c>=0xD800 && c<0xE000 ){                                       \
12825     int c2 = ((*zIn++)<<8);                                           \
12826     c2 += (*zIn++);                                                   \
12827     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
12828     if( (c & 0xFFFF0000)==0 ) c = 0xFFFD;                             \
12829   }                                                                   \
12830 }
12831
12832 /*
12833 ** Translate a single UTF-8 character.  Return the unicode value.
12834 **
12835 ** During translation, assume that the byte that zTerm points
12836 ** is a 0x00.
12837 **
12838 ** Write a pointer to the next unread byte back into *pzNext.
12839 **
12840 ** Notes On Invalid UTF-8:
12841 **
12842 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
12843 **     be encoded as a multi-byte character.  Any multi-byte character that
12844 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
12845 **
12846 **  *  This routine never allows a UTF16 surrogate value to be encoded.
12847 **     If a multi-byte character attempts to encode a value between
12848 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
12849 **
12850 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
12851 **     byte of a character are interpreted as single-byte characters
12852 **     and rendered as themselves even though they are technically
12853 **     invalid characters.
12854 **
12855 **  *  This routine accepts an infinite number of different UTF8 encodings
12856 **     for unicode values 0x80 and greater.  It do not change over-length
12857 **     encodings to 0xfffd as some systems recommend.
12858 */
12859 SQLITE_PRIVATE int sqlite3Utf8Read(
12860   const unsigned char *z,         /* First byte of UTF-8 character */
12861   const unsigned char *zTerm,     /* Pretend this byte is 0x00 */
12862   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
12863 ){
12864   int c = *(z++);
12865   if( c>=0xc0 ){
12866     c = sqlite3UtfTrans1[c-0xc0];
12867     while( z!=zTerm && (*z & 0xc0)==0x80 ){
12868       c = (c<<6) + (0x3f & *(z++));
12869     }
12870     if( c<0x80
12871         || (c&0xFFFFF800)==0xD800
12872         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
12873   }
12874   *pzNext = z;
12875   return c;
12876 }
12877
12878
12879
12880 /*
12881 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
12882 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
12883 */ 
12884 /* #define TRANSLATE_TRACE 1 */
12885
12886 #ifndef SQLITE_OMIT_UTF16
12887 /*
12888 ** This routine transforms the internal text encoding used by pMem to
12889 ** desiredEnc. It is an error if the string is already of the desired
12890 ** encoding, or if *pMem does not contain a string value.
12891 */
12892 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
12893   unsigned char zShort[NBFS]; /* Temporary short output buffer */
12894   int len;                    /* Maximum length of output string in bytes */
12895   unsigned char *zOut;                  /* Output buffer */
12896   unsigned char *zIn;                   /* Input iterator */
12897   unsigned char *zTerm;                 /* End of input */
12898   unsigned char *z;                     /* Output iterator */
12899   unsigned int c;
12900
12901   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
12902   assert( pMem->flags&MEM_Str );
12903   assert( pMem->enc!=desiredEnc );
12904   assert( pMem->enc!=0 );
12905   assert( pMem->n>=0 );
12906
12907 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
12908   {
12909     char zBuf[100];
12910     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
12911     fprintf(stderr, "INPUT:  %s\n", zBuf);
12912   }
12913 #endif
12914
12915   /* If the translation is between UTF-16 little and big endian, then 
12916   ** all that is required is to swap the byte order. This case is handled
12917   ** differently from the others.
12918   */
12919   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
12920     u8 temp;
12921     int rc;
12922     rc = sqlite3VdbeMemMakeWriteable(pMem);
12923     if( rc!=SQLITE_OK ){
12924       assert( rc==SQLITE_NOMEM );
12925       return SQLITE_NOMEM;
12926     }
12927     zIn = (u8*)pMem->z;
12928     zTerm = &zIn[pMem->n];
12929     while( zIn<zTerm ){
12930       temp = *zIn;
12931       *zIn = *(zIn+1);
12932       zIn++;
12933       *zIn++ = temp;
12934     }
12935     pMem->enc = desiredEnc;
12936     goto translate_out;
12937   }
12938
12939   /* Set len to the maximum number of bytes required in the output buffer. */
12940   if( desiredEnc==SQLITE_UTF8 ){
12941     /* When converting from UTF-16, the maximum growth results from
12942     ** translating a 2-byte character to a 4-byte UTF-8 character.
12943     ** A single byte is required for the output string
12944     ** nul-terminator.
12945     */
12946     len = pMem->n * 2 + 1;
12947   }else{
12948     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
12949     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
12950     ** character. Two bytes are required in the output buffer for the
12951     ** nul-terminator.
12952     */
12953     len = pMem->n * 2 + 2;
12954   }
12955
12956   /* Set zIn to point at the start of the input buffer and zTerm to point 1
12957   ** byte past the end.
12958   **
12959   ** Variable zOut is set to point at the output buffer. This may be space
12960   ** obtained from sqlite3_malloc(), or Mem.zShort, if it large enough and
12961   ** not in use, or the zShort array on the stack (see above).
12962   */
12963   zIn = (u8*)pMem->z;
12964   zTerm = &zIn[pMem->n];
12965   if( len>NBFS ){
12966     zOut = sqlite3DbMallocRaw(pMem->db, len);
12967     if( !zOut ){
12968       return SQLITE_NOMEM;
12969     }
12970   }else{
12971     zOut = zShort;
12972   }
12973   z = zOut;
12974
12975   if( pMem->enc==SQLITE_UTF8 ){
12976     if( desiredEnc==SQLITE_UTF16LE ){
12977       /* UTF-8 -> UTF-16 Little-endian */
12978       while( zIn<zTerm ){
12979         c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn);
12980         WRITE_UTF16LE(z, c);
12981       }
12982     }else{
12983       assert( desiredEnc==SQLITE_UTF16BE );
12984       /* UTF-8 -> UTF-16 Big-endian */
12985       while( zIn<zTerm ){
12986         c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn);
12987         WRITE_UTF16BE(z, c);
12988       }
12989     }
12990     pMem->n = z - zOut;
12991     *z++ = 0;
12992   }else{
12993     assert( desiredEnc==SQLITE_UTF8 );
12994     if( pMem->enc==SQLITE_UTF16LE ){
12995       /* UTF-16 Little-endian -> UTF-8 */
12996       while( zIn<zTerm ){
12997         READ_UTF16LE(zIn, c); 
12998         WRITE_UTF8(z, c);
12999       }
13000     }else{
13001       /* UTF-16 Little-endian -> UTF-8 */
13002       while( zIn<zTerm ){
13003         READ_UTF16BE(zIn, c); 
13004         WRITE_UTF8(z, c);
13005       }
13006     }
13007     pMem->n = z - zOut;
13008   }
13009   *z = 0;
13010   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
13011
13012   sqlite3VdbeMemRelease(pMem);
13013   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short);
13014   pMem->enc = desiredEnc;
13015   if( zOut==zShort ){
13016     memcpy(pMem->zShort, zOut, len);
13017     zOut = (u8*)pMem->zShort;
13018     pMem->flags |= (MEM_Term|MEM_Short);
13019   }else{
13020     pMem->flags |= (MEM_Term|MEM_Dyn);
13021   }
13022   pMem->z = (char*)zOut;
13023
13024 translate_out:
13025 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
13026   {
13027     char zBuf[100];
13028     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
13029     fprintf(stderr, "OUTPUT: %s\n", zBuf);
13030   }
13031 #endif
13032   return SQLITE_OK;
13033 }
13034
13035 /*
13036 ** This routine checks for a byte-order mark at the beginning of the 
13037 ** UTF-16 string stored in *pMem. If one is present, it is removed and
13038 ** the encoding of the Mem adjusted. This routine does not do any
13039 ** byte-swapping, it just sets Mem.enc appropriately.
13040 **
13041 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
13042 ** changed by this function.
13043 */
13044 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
13045   int rc = SQLITE_OK;
13046   u8 bom = 0;
13047
13048   if( pMem->n<0 || pMem->n>1 ){
13049     u8 b1 = *(u8 *)pMem->z;
13050     u8 b2 = *(((u8 *)pMem->z) + 1);
13051     if( b1==0xFE && b2==0xFF ){
13052       bom = SQLITE_UTF16BE;
13053     }
13054     if( b1==0xFF && b2==0xFE ){
13055       bom = SQLITE_UTF16LE;
13056     }
13057   }
13058   
13059   if( bom ){
13060     /* This function is called as soon as a string is stored in a Mem*,
13061     ** from within sqlite3VdbeMemSetStr(). At that point it is not possible
13062     ** for the string to be stored in Mem.zShort, or for it to be stored
13063     ** in dynamic memory with no destructor.
13064     */
13065     assert( !(pMem->flags&MEM_Short) );
13066     assert( !(pMem->flags&MEM_Dyn) || pMem->xDel );
13067     if( pMem->flags & MEM_Dyn ){
13068       void (*xDel)(void*) = pMem->xDel;
13069       char *z = pMem->z;
13070       pMem->z = 0;
13071       pMem->xDel = 0;
13072       rc = sqlite3VdbeMemSetStr(pMem, &z[2], pMem->n-2, bom, 
13073           SQLITE_TRANSIENT);
13074       xDel(z);
13075     }else{
13076       rc = sqlite3VdbeMemSetStr(pMem, &pMem->z[2], pMem->n-2, bom, 
13077           SQLITE_TRANSIENT);
13078     }
13079   }
13080   return rc;
13081 }
13082 #endif /* SQLITE_OMIT_UTF16 */
13083
13084 /*
13085 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
13086 ** return the number of unicode characters in pZ up to (but not including)
13087 ** the first 0x00 byte. If nByte is not less than zero, return the
13088 ** number of unicode characters in the first nByte of pZ (or up to 
13089 ** the first 0x00, whichever comes first).
13090 */
13091 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
13092   int r = 0;
13093   const u8 *z = (const u8*)zIn;
13094   const u8 *zTerm;
13095   if( nByte>=0 ){
13096     zTerm = &z[nByte];
13097   }else{
13098     zTerm = (const u8*)(-1);
13099   }
13100   assert( z<=zTerm );
13101   while( *z!=0 && z<zTerm ){
13102     SQLITE_SKIP_UTF8(z);
13103     r++;
13104   }
13105   return r;
13106 }
13107
13108 /* This test function is not currently used by the automated test-suite. 
13109 ** Hence it is only available in debug builds.
13110 */
13111 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
13112 /*
13113 ** Translate UTF-8 to UTF-8.
13114 **
13115 ** This has the effect of making sure that the string is well-formed
13116 ** UTF-8.  Miscoded characters are removed.
13117 **
13118 ** The translation is done in-place (since it is impossible for the
13119 ** correct UTF-8 encoding to be longer than a malformed encoding).
13120 */
13121 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
13122   unsigned char *zOut = zIn;
13123   unsigned char *zStart = zIn;
13124   unsigned char *zTerm;
13125   u32 c;
13126
13127   while( zIn[0] ){
13128     c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn);
13129     if( c!=0xfffd ){
13130       WRITE_UTF8(zOut, c);
13131     }
13132   }
13133   *zOut = 0;
13134   return zOut - zStart;
13135 }
13136 #endif
13137
13138 #ifndef SQLITE_OMIT_UTF16
13139 /*
13140 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
13141 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
13142 ** be freed by the calling function.
13143 **
13144 ** NULL is returned if there is an allocation error.
13145 */
13146 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte){
13147   Mem m;
13148   memset(&m, 0, sizeof(m));
13149   m.db = db;
13150   sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC);
13151   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
13152   if( db->mallocFailed ){
13153     sqlite3VdbeMemRelease(&m);
13154     m.z = 0;
13155   }
13156   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
13157   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
13158   return (m.flags & MEM_Dyn)!=0 ? m.z : sqlite3DbStrDup(db, m.z);
13159 }
13160
13161 /*
13162 ** pZ is a UTF-16 encoded unicode string. If nChar is less than zero,
13163 ** return the number of bytes up to (but not including), the first pair
13164 ** of consecutive 0x00 bytes in pZ. If nChar is not less than zero,
13165 ** then return the number of bytes in the first nChar unicode characters
13166 ** in pZ (or up until the first pair of 0x00 bytes, whichever comes first).
13167 */
13168 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
13169   unsigned int c = 1;
13170   char const *z = zIn;
13171   int n = 0;
13172   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
13173     /* Using an "if (SQLITE_UTF16NATIVE==SQLITE_UTF16BE)" construct here
13174     ** and in other parts of this file means that at one branch will
13175     ** not be covered by coverage testing on any single host. But coverage
13176     ** will be complete if the tests are run on both a little-endian and 
13177     ** big-endian host. Because both the UTF16NATIVE and SQLITE_UTF16BE
13178     ** macros are constant at compile time the compiler can determine
13179     ** which branch will be followed. It is therefore assumed that no runtime
13180     ** penalty is paid for this "if" statement.
13181     */
13182     while( c && ((nChar<0) || n<nChar) ){
13183       READ_UTF16BE(z, c);
13184       n++;
13185     }
13186   }else{
13187     while( c && ((nChar<0) || n<nChar) ){
13188       READ_UTF16LE(z, c);
13189       n++;
13190     }
13191   }
13192   return (z-(char const *)zIn)-((c==0)?2:0);
13193 }
13194
13195 #if defined(SQLITE_TEST)
13196 /*
13197 ** This routine is called from the TCL test function "translate_selftest".
13198 ** It checks that the primitives for serializing and deserializing
13199 ** characters in each encoding are inverses of each other.
13200 */
13201 SQLITE_PRIVATE void sqlite3UtfSelfTest(){
13202   unsigned int i, t;
13203   unsigned char zBuf[20];
13204   unsigned char *z;
13205   unsigned char *zTerm;
13206   int n;
13207   unsigned int c;
13208
13209   for(i=0; i<0x00110000; i++){
13210     z = zBuf;
13211     WRITE_UTF8(z, i);
13212     n = z-zBuf;
13213     z[0] = 0;
13214     zTerm = z;
13215     z = zBuf;
13216     c = sqlite3Utf8Read(z, zTerm, (const u8**)&z);
13217     t = i;
13218     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
13219     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
13220     assert( c==t );
13221     assert( (z-zBuf)==n );
13222   }
13223   for(i=0; i<0x00110000; i++){
13224     if( i>=0xD800 && i<0xE000 ) continue;
13225     z = zBuf;
13226     WRITE_UTF16LE(z, i);
13227     n = z-zBuf;
13228     z[0] = 0;
13229     z = zBuf;
13230     READ_UTF16LE(z, c);
13231     assert( c==i );
13232     assert( (z-zBuf)==n );
13233   }
13234   for(i=0; i<0x00110000; i++){
13235     if( i>=0xD800 && i<0xE000 ) continue;
13236     z = zBuf;
13237     WRITE_UTF16BE(z, i);
13238     n = z-zBuf;
13239     z[0] = 0;
13240     z = zBuf;
13241     READ_UTF16BE(z, c);
13242     assert( c==i );
13243     assert( (z-zBuf)==n );
13244   }
13245 }
13246 #endif /* SQLITE_TEST */
13247 #endif /* SQLITE_OMIT_UTF16 */
13248
13249 /************** End of utf.c *************************************************/
13250 /************** Begin file util.c ********************************************/
13251 /*
13252 ** 2001 September 15
13253 **
13254 ** The author disclaims copyright to this source code.  In place of
13255 ** a legal notice, here is a blessing:
13256 **
13257 **    May you do good and not evil.
13258 **    May you find forgiveness for yourself and forgive others.
13259 **    May you share freely, never taking more than you give.
13260 **
13261 *************************************************************************
13262 ** Utility functions used throughout sqlite.
13263 **
13264 ** This file contains functions for allocating memory, comparing
13265 ** strings, and stuff like that.
13266 **
13267 ** $Id: util.c,v 1.213 2007/10/23 15:39:45 drh Exp $
13268 */
13269
13270
13271 /*
13272 ** Set the most recent error code and error string for the sqlite
13273 ** handle "db". The error code is set to "err_code".
13274 **
13275 ** If it is not NULL, string zFormat specifies the format of the
13276 ** error string in the style of the printf functions: The following
13277 ** format characters are allowed:
13278 **
13279 **      %s      Insert a string
13280 **      %z      A string that should be freed after use
13281 **      %d      Insert an integer
13282 **      %T      Insert a token
13283 **      %S      Insert the first element of a SrcList
13284 **
13285 ** zFormat and any string tokens that follow it are assumed to be
13286 ** encoded in UTF-8.
13287 **
13288 ** To clear the most recent error for sqlite handle "db", sqlite3Error
13289 ** should be called with err_code set to SQLITE_OK and zFormat set
13290 ** to NULL.
13291 */
13292 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
13293   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
13294     db->errCode = err_code;
13295     if( zFormat ){
13296       char *z;
13297       va_list ap;
13298       va_start(ap, zFormat);
13299       z = sqlite3VMPrintf(db, zFormat, ap);
13300       va_end(ap);
13301       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, sqlite3_free);
13302     }else{
13303       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
13304     }
13305   }
13306 }
13307
13308 /*
13309 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
13310 ** The following formatting characters are allowed:
13311 **
13312 **      %s      Insert a string
13313 **      %z      A string that should be freed after use
13314 **      %d      Insert an integer
13315 **      %T      Insert a token
13316 **      %S      Insert the first element of a SrcList
13317 **
13318 ** This function should be used to report any error that occurs whilst
13319 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
13320 ** last thing the sqlite3_prepare() function does is copy the error
13321 ** stored by this function into the database handle using sqlite3Error().
13322 ** Function sqlite3Error() should be used during statement execution
13323 ** (sqlite3_step() etc.).
13324 */
13325 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
13326   va_list ap;
13327   pParse->nErr++;
13328   sqlite3_free(pParse->zErrMsg);
13329   va_start(ap, zFormat);
13330   pParse->zErrMsg = sqlite3VMPrintf(pParse->db, zFormat, ap);
13331   va_end(ap);
13332   if( pParse->rc==SQLITE_OK ){
13333     pParse->rc = SQLITE_ERROR;
13334   }
13335 }
13336
13337 /*
13338 ** Clear the error message in pParse, if any
13339 */
13340 SQLITE_PRIVATE void sqlite3ErrorClear(Parse *pParse){
13341   sqlite3_free(pParse->zErrMsg);
13342   pParse->zErrMsg = 0;
13343   pParse->nErr = 0;
13344 }
13345
13346 /*
13347 ** Convert an SQL-style quoted string into a normal string by removing
13348 ** the quote characters.  The conversion is done in-place.  If the
13349 ** input does not begin with a quote character, then this routine
13350 ** is a no-op.
13351 **
13352 ** 2002-Feb-14: This routine is extended to remove MS-Access style
13353 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
13354 ** "a-b-c".
13355 */
13356 SQLITE_PRIVATE void sqlite3Dequote(char *z){
13357   int quote;
13358   int i, j;
13359   if( z==0 ) return;
13360   quote = z[0];
13361   switch( quote ){
13362     case '\'':  break;
13363     case '"':   break;
13364     case '`':   break;                /* For MySQL compatibility */
13365     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
13366     default:    return;
13367   }
13368   for(i=1, j=0; z[i]; i++){
13369     if( z[i]==quote ){
13370       if( z[i+1]==quote ){
13371         z[j++] = quote;
13372         i++;
13373       }else{
13374         z[j++] = 0;
13375         break;
13376       }
13377     }else{
13378       z[j++] = z[i];
13379     }
13380   }
13381 }
13382
13383 /* An array to map all upper-case characters into their corresponding
13384 ** lower-case character. 
13385 */
13386 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
13387 #ifdef SQLITE_ASCII
13388       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
13389      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
13390      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
13391      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
13392     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
13393     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
13394     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
13395     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
13396     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
13397     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
13398     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
13399     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
13400     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
13401     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
13402     252,253,254,255
13403 #endif
13404 #ifdef SQLITE_EBCDIC
13405       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
13406      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
13407      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
13408      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
13409      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
13410      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
13411      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
13412     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
13413     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
13414     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
13415     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
13416     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
13417     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
13418     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
13419     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
13420     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
13421 #endif
13422 };
13423 #define UpperToLower sqlite3UpperToLower
13424
13425 /*
13426 ** Some systems have stricmp().  Others have strcasecmp().  Because
13427 ** there is no consistency, we will define our own.
13428 */
13429 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
13430   register unsigned char *a, *b;
13431   a = (unsigned char *)zLeft;
13432   b = (unsigned char *)zRight;
13433   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
13434   return UpperToLower[*a] - UpperToLower[*b];
13435 }
13436 SQLITE_PRIVATE int sqlite3StrNICmp(const char *zLeft, const char *zRight, int N){
13437   register unsigned char *a, *b;
13438   a = (unsigned char *)zLeft;
13439   b = (unsigned char *)zRight;
13440   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
13441   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
13442 }
13443
13444 /*
13445 ** Return TRUE if z is a pure numeric string.  Return FALSE if the
13446 ** string contains any character which is not part of a number. If
13447 ** the string is numeric and contains the '.' character, set *realnum
13448 ** to TRUE (otherwise FALSE).
13449 **
13450 ** An empty string is considered non-numeric.
13451 */
13452 SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
13453   int incr = (enc==SQLITE_UTF8?1:2);
13454   if( enc==SQLITE_UTF16BE ) z++;
13455   if( *z=='-' || *z=='+' ) z += incr;
13456   if( !isdigit(*(u8*)z) ){
13457     return 0;
13458   }
13459   z += incr;
13460   if( realnum ) *realnum = 0;
13461   while( isdigit(*(u8*)z) ){ z += incr; }
13462   if( *z=='.' ){
13463     z += incr;
13464     if( !isdigit(*(u8*)z) ) return 0;
13465     while( isdigit(*(u8*)z) ){ z += incr; }
13466     if( realnum ) *realnum = 1;
13467   }
13468   if( *z=='e' || *z=='E' ){
13469     z += incr;
13470     if( *z=='+' || *z=='-' ) z += incr;
13471     if( !isdigit(*(u8*)z) ) return 0;
13472     while( isdigit(*(u8*)z) ){ z += incr; }
13473     if( realnum ) *realnum = 1;
13474   }
13475   return *z==0;
13476 }
13477
13478 /*
13479 ** The string z[] is an ascii representation of a real number.
13480 ** Convert this string to a double.
13481 **
13482 ** This routine assumes that z[] really is a valid number.  If it
13483 ** is not, the result is undefined.
13484 **
13485 ** This routine is used instead of the library atof() function because
13486 ** the library atof() might want to use "," as the decimal point instead
13487 ** of "." depending on how locale is set.  But that would cause problems
13488 ** for SQL.  So this routine always uses "." regardless of locale.
13489 */
13490 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult){
13491 #ifndef SQLITE_OMIT_FLOATING_POINT
13492   int sign = 1;
13493   const char *zBegin = z;
13494   LONGDOUBLE_TYPE v1 = 0.0;
13495   while( isspace(*(u8*)z) ) z++;
13496   if( *z=='-' ){
13497     sign = -1;
13498     z++;
13499   }else if( *z=='+' ){
13500     z++;
13501   }
13502   while( isdigit(*(u8*)z) ){
13503     v1 = v1*10.0 + (*z - '0');
13504     z++;
13505   }
13506   if( *z=='.' ){
13507     LONGDOUBLE_TYPE divisor = 1.0;
13508     z++;
13509     while( isdigit(*(u8*)z) ){
13510       v1 = v1*10.0 + (*z - '0');
13511       divisor *= 10.0;
13512       z++;
13513     }
13514     v1 /= divisor;
13515   }
13516   if( *z=='e' || *z=='E' ){
13517     int esign = 1;
13518     int eval = 0;
13519     LONGDOUBLE_TYPE scale = 1.0;
13520     z++;
13521     if( *z=='-' ){
13522       esign = -1;
13523       z++;
13524     }else if( *z=='+' ){
13525       z++;
13526     }
13527     while( isdigit(*(u8*)z) ){
13528       eval = eval*10 + *z - '0';
13529       z++;
13530     }
13531     while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
13532     while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
13533     while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
13534     while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
13535     if( esign<0 ){
13536       v1 /= scale;
13537     }else{
13538       v1 *= scale;
13539     }
13540   }
13541   *pResult = sign<0 ? -v1 : v1;
13542   return z - zBegin;
13543 #else
13544   return sqlite3Atoi64(z, pResult);
13545 #endif /* SQLITE_OMIT_FLOATING_POINT */
13546 }
13547
13548 /*
13549 ** Compare the 19-character string zNum against the text representation
13550 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
13551 ** if zNum is less than, equal to, or greater than the string.
13552 **
13553 ** Unlike memcmp() this routine is guaranteed to return the difference
13554 ** in the values of the last digit if the only difference is in the
13555 ** last digit.  So, for example,
13556 **
13557 **      compare2pow63("9223372036854775800")
13558 **
13559 ** will return -8.
13560 */
13561 static int compare2pow63(const char *zNum){
13562   int c;
13563   c = memcmp(zNum,"922337203685477580",18);
13564   if( c==0 ){
13565     c = zNum[18] - '8';
13566   }
13567   return c;
13568 }
13569
13570
13571 /*
13572 ** Return TRUE if zNum is a 64-bit signed integer and write
13573 ** the value of the integer into *pNum.  If zNum is not an integer
13574 ** or is an integer that is too large to be expressed with 64 bits,
13575 ** then return false.
13576 **
13577 ** When this routine was originally written it dealt with only
13578 ** 32-bit numbers.  At that time, it was much faster than the
13579 ** atoi() library routine in RedHat 7.2.
13580 */
13581 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
13582   i64 v = 0;
13583   int neg;
13584   int i, c;
13585   while( isspace(*(u8*)zNum) ) zNum++;
13586   if( *zNum=='-' ){
13587     neg = 1;
13588     zNum++;
13589   }else if( *zNum=='+' ){
13590     neg = 0;
13591     zNum++;
13592   }else{
13593     neg = 0;
13594   }
13595   while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
13596   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
13597     v = v*10 + c - '0';
13598   }
13599   *pNum = neg ? -v : v;
13600   if( c!=0 || i==0 || i>19 ){
13601     /* zNum is empty or contains non-numeric text or is longer
13602     ** than 19 digits (thus guaranting that it is too large) */
13603     return 0;
13604   }else if( i<19 ){
13605     /* Less than 19 digits, so we know that it fits in 64 bits */
13606     return 1;
13607   }else{
13608     /* 19-digit numbers must be no larger than 9223372036854775807 if positive
13609     ** or 9223372036854775808 if negative.  Note that 9223372036854665808
13610     ** is 2^63. */
13611     return compare2pow63(zNum)<neg;
13612   }
13613 }
13614
13615 /*
13616 ** The string zNum represents an integer.  There might be some other
13617 ** information following the integer too, but that part is ignored.
13618 ** If the integer that the prefix of zNum represents will fit in a
13619 ** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
13620 **
13621 ** This routine returns FALSE for the string -9223372036854775808 even that
13622 ** that number will, in theory fit in a 64-bit integer.  Positive
13623 ** 9223373036854775808 will not fit in 64 bits.  So it seems safer to return
13624 ** false.
13625 */
13626 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
13627   int i, c;
13628   int neg = 0;
13629   if( *zNum=='-' ){
13630     neg = 1;
13631     zNum++;
13632   }else if( *zNum=='+' ){
13633     zNum++;
13634   }
13635   if( negFlag ) neg = 1-neg;
13636   while( *zNum=='0' ){
13637     zNum++;   /* Skip leading zeros.  Ticket #2454 */
13638   }
13639   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
13640   if( i<19 ){
13641     /* Guaranteed to fit if less than 19 digits */
13642     return 1;
13643   }else if( i>19 ){
13644     /* Guaranteed to be too big if greater than 19 digits */
13645     return 0;
13646   }else{
13647     /* Compare against 2^63. */
13648     return compare2pow63(zNum)<neg;
13649   }
13650 }
13651
13652 /*
13653 ** If zNum represents an integer that will fit in 32-bits, then set
13654 ** *pValue to that integer and return true.  Otherwise return false.
13655 **
13656 ** Any non-numeric characters that following zNum are ignored.
13657 ** This is different from sqlite3Atoi64() which requires the
13658 ** input number to be zero-terminated.
13659 */
13660 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
13661   sqlite_int64 v = 0;
13662   int i, c;
13663   int neg = 0;
13664   if( zNum[0]=='-' ){
13665     neg = 1;
13666     zNum++;
13667   }else if( zNum[0]=='+' ){
13668     zNum++;
13669   }
13670   while( zNum[0]=='0' ) zNum++;
13671   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
13672     v = v*10 + c;
13673   }
13674
13675   /* The longest decimal representation of a 32 bit integer is 10 digits:
13676   **
13677   **             1234567890
13678   **     2^31 -> 2147483648
13679   */
13680   if( i>10 ){
13681     return 0;
13682   }
13683   if( v-neg>2147483647 ){
13684     return 0;
13685   }
13686   if( neg ){
13687     v = -v;
13688   }
13689   *pValue = (int)v;
13690   return 1;
13691 }
13692
13693 /*
13694 ** Check to make sure we have a valid db pointer.  This test is not
13695 ** foolproof but it does provide some measure of protection against
13696 ** misuse of the interface such as passing in db pointers that are
13697 ** NULL or which have been previously closed.  If this routine returns
13698 ** TRUE it means that the db pointer is invalid and should not be
13699 ** dereferenced for any reason.  The calling function should invoke
13700 ** SQLITE_MISUSE immediately.
13701 */
13702 SQLITE_PRIVATE int sqlite3SafetyCheck(sqlite3 *db){
13703   int magic;
13704   if( db==0 ) return 1;
13705   magic = db->magic;
13706   if( magic!=SQLITE_MAGIC_CLOSED &&
13707          magic!=SQLITE_MAGIC_OPEN &&
13708          magic!=SQLITE_MAGIC_BUSY ) return 1;
13709   return 0;
13710 }
13711
13712 /*
13713 ** The variable-length integer encoding is as follows:
13714 **
13715 ** KEY:
13716 **         A = 0xxxxxxx    7 bits of data and one flag bit
13717 **         B = 1xxxxxxx    7 bits of data and one flag bit
13718 **         C = xxxxxxxx    8 bits of data
13719 **
13720 **  7 bits - A
13721 ** 14 bits - BA
13722 ** 21 bits - BBA
13723 ** 28 bits - BBBA
13724 ** 35 bits - BBBBA
13725 ** 42 bits - BBBBBA
13726 ** 49 bits - BBBBBBA
13727 ** 56 bits - BBBBBBBA
13728 ** 64 bits - BBBBBBBBC
13729 */
13730
13731 /*
13732 ** Write a 64-bit variable-length integer to memory starting at p[0].
13733 ** The length of data write will be between 1 and 9 bytes.  The number
13734 ** of bytes written is returned.
13735 **
13736 ** A variable-length integer consists of the lower 7 bits of each byte
13737 ** for all bytes that have the 8th bit set and one byte with the 8th
13738 ** bit clear.  Except, if we get to the 9th byte, it stores the full
13739 ** 8 bits and is the last byte.
13740 */
13741 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
13742   int i, j, n;
13743   u8 buf[10];
13744   if( v & (((u64)0xff000000)<<32) ){
13745     p[8] = v;
13746     v >>= 8;
13747     for(i=7; i>=0; i--){
13748       p[i] = (v & 0x7f) | 0x80;
13749       v >>= 7;
13750     }
13751     return 9;
13752   }    
13753   n = 0;
13754   do{
13755     buf[n++] = (v & 0x7f) | 0x80;
13756     v >>= 7;
13757   }while( v!=0 );
13758   buf[0] &= 0x7f;
13759   assert( n<=9 );
13760   for(i=0, j=n-1; j>=0; j--, i++){
13761     p[i] = buf[j];
13762   }
13763   return n;
13764 }
13765
13766 /*
13767 ** Read a 64-bit variable-length integer from memory starting at p[0].
13768 ** Return the number of bytes read.  The value is stored in *v.
13769 */
13770 SQLITE_PRIVATE int sqlite3GetVarint(const unsigned char *p, u64 *v){
13771   u32 x;
13772   u64 x64;
13773   int n;
13774   unsigned char c;
13775   if( ((c = p[0]) & 0x80)==0 ){
13776     *v = c;
13777     return 1;
13778   }
13779   x = c & 0x7f;
13780   if( ((c = p[1]) & 0x80)==0 ){
13781     *v = (x<<7) | c;
13782     return 2;
13783   }
13784   x = (x<<7) | (c&0x7f);
13785   if( ((c = p[2]) & 0x80)==0 ){
13786     *v = (x<<7) | c;
13787     return 3;
13788   }
13789   x = (x<<7) | (c&0x7f);
13790   if( ((c = p[3]) & 0x80)==0 ){
13791     *v = (x<<7) | c;
13792     return 4;
13793   }
13794   x64 = (x<<7) | (c&0x7f);
13795   n = 4;
13796   do{
13797     c = p[n++];
13798     if( n==9 ){
13799       x64 = (x64<<8) | c;
13800       break;
13801     }
13802     x64 = (x64<<7) | (c&0x7f);
13803   }while( (c & 0x80)!=0 );
13804   *v = x64;
13805   return n;
13806 }
13807
13808 /*
13809 ** Read a 32-bit variable-length integer from memory starting at p[0].
13810 ** Return the number of bytes read.  The value is stored in *v.
13811 */
13812 SQLITE_PRIVATE int sqlite3GetVarint32(const unsigned char *p, u32 *v){
13813   u32 x;
13814   int n;
13815   unsigned char c;
13816   if( ((signed char*)p)[0]>=0 ){
13817     *v = p[0];
13818     return 1;
13819   }
13820   x = p[0] & 0x7f;
13821   if( ((signed char*)p)[1]>=0 ){
13822     *v = (x<<7) | p[1];
13823     return 2;
13824   }
13825   x = (x<<7) | (p[1] & 0x7f);
13826   n = 2;
13827   do{
13828     x = (x<<7) | ((c = p[n++])&0x7f);
13829   }while( (c & 0x80)!=0 && n<9 );
13830   *v = x;
13831   return n;
13832 }
13833
13834 /*
13835 ** Return the number of bytes that will be needed to store the given
13836 ** 64-bit integer.
13837 */
13838 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
13839   int i = 0;
13840   do{
13841     i++;
13842     v >>= 7;
13843   }while( v!=0 && i<9 );
13844   return i;
13845 }
13846
13847
13848 /*
13849 ** Read or write a four-byte big-endian integer value.
13850 */
13851 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
13852   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
13853 }
13854 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
13855   p[0] = v>>24;
13856   p[1] = v>>16;
13857   p[2] = v>>8;
13858   p[3] = v;
13859 }
13860
13861
13862
13863 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC) \
13864     || defined(SQLITE_TEST)
13865 /*
13866 ** Translate a single byte of Hex into an integer.
13867 */
13868 static int hexToInt(int h){
13869   if( h>='0' && h<='9' ){
13870     return h - '0';
13871   }else if( h>='a' && h<='f' ){
13872     return h - 'a' + 10;
13873   }else{
13874     assert( h>='A' && h<='F' );
13875     return h - 'A' + 10;
13876   }
13877 }
13878 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC || SQLITE_TEST */
13879
13880 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
13881 /*
13882 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
13883 ** value.  Return a pointer to its binary value.  Space to hold the
13884 ** binary value has been obtained from malloc and must be freed by
13885 ** the calling routine.
13886 */
13887 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z){
13888   char *zBlob;
13889   int i;
13890   int n = strlen(z);
13891   if( n%2 ) return 0;
13892
13893   zBlob = (char *)sqlite3DbMallocRaw(db, n/2);
13894   if( zBlob ){
13895     for(i=0; i<n; i+=2){
13896       zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
13897     }
13898   }
13899   return zBlob;
13900 }
13901 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
13902
13903
13904 /*
13905 ** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
13906 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
13907 ** when this routine is called.
13908 **
13909 ** This routine is called when entering an SQLite API.  The SQLITE_MAGIC_OPEN
13910 ** value indicates that the database connection passed into the API is
13911 ** open and is not being used by another thread.  By changing the value
13912 ** to SQLITE_MAGIC_BUSY we indicate that the connection is in use.
13913 ** sqlite3SafetyOff() below will change the value back to SQLITE_MAGIC_OPEN
13914 ** when the API exits. 
13915 **
13916 ** This routine is a attempt to detect if two threads use the
13917 ** same sqlite* pointer at the same time.  There is a race 
13918 ** condition so it is possible that the error is not detected.
13919 ** But usually the problem will be seen.  The result will be an
13920 ** error which can be used to debug the application that is
13921 ** using SQLite incorrectly.
13922 **
13923 ** Ticket #202:  If db->magic is not a valid open value, take care not
13924 ** to modify the db structure at all.  It could be that db is a stale
13925 ** pointer.  In other words, it could be that there has been a prior
13926 ** call to sqlite3_close(db) and db has been deallocated.  And we do
13927 ** not want to write into deallocated memory.
13928 */
13929 SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3 *db){
13930   if( db->magic==SQLITE_MAGIC_OPEN ){
13931     db->magic = SQLITE_MAGIC_BUSY;
13932     return 0;
13933   }else if( db->magic==SQLITE_MAGIC_BUSY ){
13934     db->magic = SQLITE_MAGIC_ERROR;
13935     db->u1.isInterrupted = 1;
13936   }
13937   return 1;
13938 }
13939
13940 /*
13941 ** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
13942 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
13943 ** when this routine is called.
13944 */
13945 SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3 *db){
13946   if( db->magic==SQLITE_MAGIC_BUSY ){
13947     db->magic = SQLITE_MAGIC_OPEN;
13948     return 0;
13949   }else {
13950     db->magic = SQLITE_MAGIC_ERROR;
13951     db->u1.isInterrupted = 1;
13952     return 1;
13953   }
13954 }
13955
13956 /************** End of util.c ************************************************/
13957 /************** Begin file hash.c ********************************************/
13958 /*
13959 ** 2001 September 22
13960 **
13961 ** The author disclaims copyright to this source code.  In place of
13962 ** a legal notice, here is a blessing:
13963 **
13964 **    May you do good and not evil.
13965 **    May you find forgiveness for yourself and forgive others.
13966 **    May you share freely, never taking more than you give.
13967 **
13968 *************************************************************************
13969 ** This is the implementation of generic hash-tables
13970 ** used in SQLite.
13971 **
13972 ** $Id: hash.c,v 1.24 2007/09/04 14:31:47 danielk1977 Exp $
13973 */
13974
13975 /* Turn bulk memory into a hash table object by initializing the
13976 ** fields of the Hash structure.
13977 **
13978 ** "pNew" is a pointer to the hash table that is to be initialized.
13979 ** keyClass is one of the constants SQLITE_HASH_INT, SQLITE_HASH_POINTER,
13980 ** SQLITE_HASH_BINARY, or SQLITE_HASH_STRING.  The value of keyClass 
13981 ** determines what kind of key the hash table will use.  "copyKey" is
13982 ** true if the hash table should make its own private copy of keys and
13983 ** false if it should just use the supplied pointer.  CopyKey only makes
13984 ** sense for SQLITE_HASH_STRING and SQLITE_HASH_BINARY and is ignored
13985 ** for other key classes.
13986 */
13987 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew, int keyClass, int copyKey){
13988   assert( pNew!=0 );
13989   assert( keyClass>=SQLITE_HASH_STRING && keyClass<=SQLITE_HASH_BINARY );
13990   pNew->keyClass = keyClass;
13991 #if 0
13992   if( keyClass==SQLITE_HASH_POINTER || keyClass==SQLITE_HASH_INT ) copyKey = 0;
13993 #endif
13994   pNew->copyKey = copyKey;
13995   pNew->first = 0;
13996   pNew->count = 0;
13997   pNew->htsize = 0;
13998   pNew->ht = 0;
13999 }
14000
14001 /* Remove all entries from a hash table.  Reclaim all memory.
14002 ** Call this routine to delete a hash table or to reset a hash table
14003 ** to the empty state.
14004 */
14005 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
14006   HashElem *elem;         /* For looping over all elements of the table */
14007
14008   assert( pH!=0 );
14009   elem = pH->first;
14010   pH->first = 0;
14011   if( pH->ht ) sqlite3_free(pH->ht);
14012   pH->ht = 0;
14013   pH->htsize = 0;
14014   while( elem ){
14015     HashElem *next_elem = elem->next;
14016     if( pH->copyKey && elem->pKey ){
14017       sqlite3_free(elem->pKey);
14018     }
14019     sqlite3_free(elem);
14020     elem = next_elem;
14021   }
14022   pH->count = 0;
14023 }
14024
14025 #if 0 /* NOT USED */
14026 /*
14027 ** Hash and comparison functions when the mode is SQLITE_HASH_INT
14028 */
14029 static int intHash(const void *pKey, int nKey){
14030   return nKey ^ (nKey<<8) ^ (nKey>>8);
14031 }
14032 static int intCompare(const void *pKey1, int n1, const void *pKey2, int n2){
14033   return n2 - n1;
14034 }
14035 #endif
14036
14037 #if 0 /* NOT USED */
14038 /*
14039 ** Hash and comparison functions when the mode is SQLITE_HASH_POINTER
14040 */
14041 static int ptrHash(const void *pKey, int nKey){
14042   uptr x = Addr(pKey);
14043   return x ^ (x<<8) ^ (x>>8);
14044 }
14045 static int ptrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
14046   if( pKey1==pKey2 ) return 0;
14047   if( pKey1<pKey2 ) return -1;
14048   return 1;
14049 }
14050 #endif
14051
14052 /*
14053 ** Hash and comparison functions when the mode is SQLITE_HASH_STRING
14054 */
14055 static int strHash(const void *pKey, int nKey){
14056   const char *z = (const char *)pKey;
14057   int h = 0;
14058   if( nKey<=0 ) nKey = strlen(z);
14059   while( nKey > 0  ){
14060     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
14061     nKey--;
14062   }
14063   return h & 0x7fffffff;
14064 }
14065 static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
14066   if( n1!=n2 ) return 1;
14067   return sqlite3StrNICmp((const char*)pKey1,(const char*)pKey2,n1);
14068 }
14069
14070 /*
14071 ** Hash and comparison functions when the mode is SQLITE_HASH_BINARY
14072 */
14073 static int binHash(const void *pKey, int nKey){
14074   int h = 0;
14075   const char *z = (const char *)pKey;
14076   while( nKey-- > 0 ){
14077     h = (h<<3) ^ h ^ *(z++);
14078   }
14079   return h & 0x7fffffff;
14080 }
14081 static int binCompare(const void *pKey1, int n1, const void *pKey2, int n2){
14082   if( n1!=n2 ) return 1;
14083   return memcmp(pKey1,pKey2,n1);
14084 }
14085
14086 /*
14087 ** Return a pointer to the appropriate hash function given the key class.
14088 **
14089 ** The C syntax in this function definition may be unfamilar to some 
14090 ** programmers, so we provide the following additional explanation:
14091 **
14092 ** The name of the function is "hashFunction".  The function takes a
14093 ** single parameter "keyClass".  The return value of hashFunction()
14094 ** is a pointer to another function.  Specifically, the return value
14095 ** of hashFunction() is a pointer to a function that takes two parameters
14096 ** with types "const void*" and "int" and returns an "int".
14097 */
14098 static int (*hashFunction(int keyClass))(const void*,int){
14099 #if 0  /* HASH_INT and HASH_POINTER are never used */
14100   switch( keyClass ){
14101     case SQLITE_HASH_INT:     return &intHash;
14102     case SQLITE_HASH_POINTER: return &ptrHash;
14103     case SQLITE_HASH_STRING:  return &strHash;
14104     case SQLITE_HASH_BINARY:  return &binHash;;
14105     default: break;
14106   }
14107   return 0;
14108 #else
14109   if( keyClass==SQLITE_HASH_STRING ){
14110     return &strHash;
14111   }else{
14112     assert( keyClass==SQLITE_HASH_BINARY );
14113     return &binHash;
14114   }
14115 #endif
14116 }
14117
14118 /*
14119 ** Return a pointer to the appropriate hash function given the key class.
14120 **
14121 ** For help in interpreted the obscure C code in the function definition,
14122 ** see the header comment on the previous function.
14123 */
14124 static int (*compareFunction(int keyClass))(const void*,int,const void*,int){
14125 #if 0 /* HASH_INT and HASH_POINTER are never used */
14126   switch( keyClass ){
14127     case SQLITE_HASH_INT:     return &intCompare;
14128     case SQLITE_HASH_POINTER: return &ptrCompare;
14129     case SQLITE_HASH_STRING:  return &strCompare;
14130     case SQLITE_HASH_BINARY:  return &binCompare;
14131     default: break;
14132   }
14133   return 0;
14134 #else
14135   if( keyClass==SQLITE_HASH_STRING ){
14136     return &strCompare;
14137   }else{
14138     assert( keyClass==SQLITE_HASH_BINARY );
14139     return &binCompare;
14140   }
14141 #endif
14142 }
14143
14144 /* Link an element into the hash table
14145 */
14146 static void insertElement(
14147   Hash *pH,              /* The complete hash table */
14148   struct _ht *pEntry,    /* The entry into which pNew is inserted */
14149   HashElem *pNew         /* The element to be inserted */
14150 ){
14151   HashElem *pHead;       /* First element already in pEntry */
14152   pHead = pEntry->chain;
14153   if( pHead ){
14154     pNew->next = pHead;
14155     pNew->prev = pHead->prev;
14156     if( pHead->prev ){ pHead->prev->next = pNew; }
14157     else             { pH->first = pNew; }
14158     pHead->prev = pNew;
14159   }else{
14160     pNew->next = pH->first;
14161     if( pH->first ){ pH->first->prev = pNew; }
14162     pNew->prev = 0;
14163     pH->first = pNew;
14164   }
14165   pEntry->count++;
14166   pEntry->chain = pNew;
14167 }
14168
14169
14170 /* Resize the hash table so that it cantains "new_size" buckets.
14171 ** "new_size" must be a power of 2.  The hash table might fail 
14172 ** to resize if sqlite3_malloc() fails.
14173 */
14174 static void rehash(Hash *pH, int new_size){
14175   struct _ht *new_ht;            /* The new hash table */
14176   HashElem *elem, *next_elem;    /* For looping over existing elements */
14177   int (*xHash)(const void*,int); /* The hash function */
14178
14179   assert( (new_size & (new_size-1))==0 );
14180
14181   /* There is a call to sqlite3_malloc() inside rehash(). If there is
14182   ** already an allocation at pH->ht, then if this malloc() fails it
14183   ** is benign (since failing to resize a hash table is a performance
14184   ** hit only, not a fatal error).
14185   */
14186   sqlite3MallocBenignFailure(pH->htsize>0);
14187
14188   new_ht = (struct _ht *)sqlite3MallocZero( new_size*sizeof(struct _ht) );
14189   if( new_ht==0 ) return;
14190   if( pH->ht ) sqlite3_free(pH->ht);
14191   pH->ht = new_ht;
14192   pH->htsize = new_size;
14193   xHash = hashFunction(pH->keyClass);
14194   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
14195     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
14196     next_elem = elem->next;
14197     insertElement(pH, &new_ht[h], elem);
14198   }
14199 }
14200
14201 /* This function (for internal use only) locates an element in an
14202 ** hash table that matches the given key.  The hash for this key has
14203 ** already been computed and is passed as the 4th parameter.
14204 */
14205 static HashElem *findElementGivenHash(
14206   const Hash *pH,     /* The pH to be searched */
14207   const void *pKey,   /* The key we are searching for */
14208   int nKey,
14209   int h               /* The hash for this key. */
14210 ){
14211   HashElem *elem;                /* Used to loop thru the element list */
14212   int count;                     /* Number of elements left to test */
14213   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
14214
14215   if( pH->ht ){
14216     struct _ht *pEntry = &pH->ht[h];
14217     elem = pEntry->chain;
14218     count = pEntry->count;
14219     xCompare = compareFunction(pH->keyClass);
14220     while( count-- && elem ){
14221       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
14222         return elem;
14223       }
14224       elem = elem->next;
14225     }
14226   }
14227   return 0;
14228 }
14229
14230 /* Remove a single entry from the hash table given a pointer to that
14231 ** element and a hash on the element's key.
14232 */
14233 static void removeElementGivenHash(
14234   Hash *pH,         /* The pH containing "elem" */
14235   HashElem* elem,   /* The element to be removed from the pH */
14236   int h             /* Hash value for the element */
14237 ){
14238   struct _ht *pEntry;
14239   if( elem->prev ){
14240     elem->prev->next = elem->next; 
14241   }else{
14242     pH->first = elem->next;
14243   }
14244   if( elem->next ){
14245     elem->next->prev = elem->prev;
14246   }
14247   pEntry = &pH->ht[h];
14248   if( pEntry->chain==elem ){
14249     pEntry->chain = elem->next;
14250   }
14251   pEntry->count--;
14252   if( pEntry->count<=0 ){
14253     pEntry->chain = 0;
14254   }
14255   if( pH->copyKey ){
14256     sqlite3_free(elem->pKey);
14257   }
14258   sqlite3_free( elem );
14259   pH->count--;
14260   if( pH->count<=0 ){
14261     assert( pH->first==0 );
14262     assert( pH->count==0 );
14263     sqlite3HashClear(pH);
14264   }
14265 }
14266
14267 /* Attempt to locate an element of the hash table pH with a key
14268 ** that matches pKey,nKey.  Return a pointer to the corresponding 
14269 ** HashElem structure for this element if it is found, or NULL
14270 ** otherwise.
14271 */
14272 SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash *pH, const void *pKey, int nKey){
14273   int h;             /* A hash on key */
14274   HashElem *elem;    /* The element that matches key */
14275   int (*xHash)(const void*,int);  /* The hash function */
14276
14277   if( pH==0 || pH->ht==0 ) return 0;
14278   xHash = hashFunction(pH->keyClass);
14279   assert( xHash!=0 );
14280   h = (*xHash)(pKey,nKey);
14281   assert( (pH->htsize & (pH->htsize-1))==0 );
14282   elem = findElementGivenHash(pH,pKey,nKey, h & (pH->htsize-1));
14283   return elem;
14284 }
14285
14286 /* Attempt to locate an element of the hash table pH with a key
14287 ** that matches pKey,nKey.  Return the data for this element if it is
14288 ** found, or NULL if there is no match.
14289 */
14290 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const void *pKey, int nKey){
14291   HashElem *elem;    /* The element that matches key */
14292   elem = sqlite3HashFindElem(pH, pKey, nKey);
14293   return elem ? elem->data : 0;
14294 }
14295
14296 /* Insert an element into the hash table pH.  The key is pKey,nKey
14297 ** and the data is "data".
14298 **
14299 ** If no element exists with a matching key, then a new
14300 ** element is created.  A copy of the key is made if the copyKey
14301 ** flag is set.  NULL is returned.
14302 **
14303 ** If another element already exists with the same key, then the
14304 ** new data replaces the old data and the old data is returned.
14305 ** The key is not copied in this instance.  If a malloc fails, then
14306 ** the new data is returned and the hash table is unchanged.
14307 **
14308 ** If the "data" parameter to this function is NULL, then the
14309 ** element corresponding to "key" is removed from the hash table.
14310 */
14311 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const void *pKey, int nKey, void *data){
14312   int hraw;             /* Raw hash value of the key */
14313   int h;                /* the hash of the key modulo hash table size */
14314   HashElem *elem;       /* Used to loop thru the element list */
14315   HashElem *new_elem;   /* New element added to the pH */
14316   int (*xHash)(const void*,int);  /* The hash function */
14317
14318   assert( pH!=0 );
14319   xHash = hashFunction(pH->keyClass);
14320   assert( xHash!=0 );
14321   hraw = (*xHash)(pKey, nKey);
14322   assert( (pH->htsize & (pH->htsize-1))==0 );
14323   h = hraw & (pH->htsize-1);
14324   elem = findElementGivenHash(pH,pKey,nKey,h);
14325   if( elem ){
14326     void *old_data = elem->data;
14327     if( data==0 ){
14328       removeElementGivenHash(pH,elem,h);
14329     }else{
14330       elem->data = data;
14331       if( !pH->copyKey ){
14332         elem->pKey = (void *)pKey;
14333       }
14334       assert(nKey==elem->nKey);
14335     }
14336     return old_data;
14337   }
14338   if( data==0 ) return 0;
14339   new_elem = (HashElem*)sqlite3_malloc( sizeof(HashElem) );
14340   if( new_elem==0 ) return data;
14341   if( pH->copyKey && pKey!=0 ){
14342     new_elem->pKey = sqlite3_malloc( nKey );
14343     if( new_elem->pKey==0 ){
14344       sqlite3_free(new_elem);
14345       return data;
14346     }
14347     memcpy((void*)new_elem->pKey, pKey, nKey);
14348   }else{
14349     new_elem->pKey = (void*)pKey;
14350   }
14351   new_elem->nKey = nKey;
14352   pH->count++;
14353   if( pH->htsize==0 ){
14354     rehash(pH,8);
14355     if( pH->htsize==0 ){
14356       pH->count = 0;
14357       if( pH->copyKey ){
14358         sqlite3_free(new_elem->pKey);
14359       }
14360       sqlite3_free(new_elem);
14361       return data;
14362     }
14363   }
14364   if( pH->count > pH->htsize ){
14365     rehash(pH,pH->htsize*2);
14366   }
14367   assert( pH->htsize>0 );
14368   assert( (pH->htsize & (pH->htsize-1))==0 );
14369   h = hraw & (pH->htsize-1);
14370   insertElement(pH, &pH->ht[h], new_elem);
14371   new_elem->data = data;
14372   return 0;
14373 }
14374
14375 /************** End of hash.c ************************************************/
14376 /************** Begin file opcodes.c *****************************************/
14377 /* Automatically generated.  Do not edit */
14378 /* See the mkopcodec.awk script for details. */
14379 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
14380 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
14381  static const char *const azName[] = { "?",
14382      /*   1 */ "MemLoad",
14383      /*   2 */ "VNext",
14384      /*   3 */ "Column",
14385      /*   4 */ "SetCookie",
14386      /*   5 */ "IfMemPos",
14387      /*   6 */ "Sequence",
14388      /*   7 */ "MoveGt",
14389      /*   8 */ "RowKey",
14390      /*   9 */ "OpenWrite",
14391      /*  10 */ "If",
14392      /*  11 */ "Pop",
14393      /*  12 */ "VRowid",
14394      /*  13 */ "CollSeq",
14395      /*  14 */ "OpenRead",
14396      /*  15 */ "Expire",
14397      /*  16 */ "Not",
14398      /*  17 */ "AutoCommit",
14399      /*  18 */ "IntegrityCk",
14400      /*  19 */ "Sort",
14401      /*  20 */ "Function",
14402      /*  21 */ "Noop",
14403      /*  22 */ "Return",
14404      /*  23 */ "NewRowid",
14405      /*  24 */ "IfMemNeg",
14406      /*  25 */ "Variable",
14407      /*  26 */ "String",
14408      /*  27 */ "RealAffinity",
14409      /*  28 */ "VRename",
14410      /*  29 */ "ParseSchema",
14411      /*  30 */ "VOpen",
14412      /*  31 */ "Close",
14413      /*  32 */ "CreateIndex",
14414      /*  33 */ "IsUnique",
14415      /*  34 */ "NotFound",
14416      /*  35 */ "Int64",
14417      /*  36 */ "MustBeInt",
14418      /*  37 */ "Halt",
14419      /*  38 */ "Rowid",
14420      /*  39 */ "IdxLT",
14421      /*  40 */ "AddImm",
14422      /*  41 */ "Statement",
14423      /*  42 */ "RowData",
14424      /*  43 */ "MemMax",
14425      /*  44 */ "Push",
14426      /*  45 */ "NotExists",
14427      /*  46 */ "MemIncr",
14428      /*  47 */ "Gosub",
14429      /*  48 */ "Integer",
14430      /*  49 */ "MemInt",
14431      /*  50 */ "Prev",
14432      /*  51 */ "VColumn",
14433      /*  52 */ "CreateTable",
14434      /*  53 */ "Last",
14435      /*  54 */ "IncrVacuum",
14436      /*  55 */ "IdxRowid",
14437      /*  56 */ "MakeIdxRec",
14438      /*  57 */ "ResetCount",
14439      /*  58 */ "FifoWrite",
14440      /*  59 */ "Callback",
14441      /*  60 */ "Or",
14442      /*  61 */ "And",
14443      /*  62 */ "ContextPush",
14444      /*  63 */ "DropTrigger",
14445      /*  64 */ "DropIndex",
14446      /*  65 */ "IsNull",
14447      /*  66 */ "NotNull",
14448      /*  67 */ "Ne",
14449      /*  68 */ "Eq",
14450      /*  69 */ "Gt",
14451      /*  70 */ "Le",
14452      /*  71 */ "Lt",
14453      /*  72 */ "Ge",
14454      /*  73 */ "IdxGE",
14455      /*  74 */ "BitAnd",
14456      /*  75 */ "BitOr",
14457      /*  76 */ "ShiftLeft",
14458      /*  77 */ "ShiftRight",
14459      /*  78 */ "Add",
14460      /*  79 */ "Subtract",
14461      /*  80 */ "Multiply",
14462      /*  81 */ "Divide",
14463      /*  82 */ "Remainder",
14464      /*  83 */ "Concat",
14465      /*  84 */ "IdxDelete",
14466      /*  85 */ "Negative",
14467      /*  86 */ "Vacuum",
14468      /*  87 */ "BitNot",
14469      /*  88 */ "String8",
14470      /*  89 */ "MoveLe",
14471      /*  90 */ "IfNot",
14472      /*  91 */ "DropTable",
14473      /*  92 */ "MakeRecord",
14474      /*  93 */ "Delete",
14475      /*  94 */ "StackDepth",
14476      /*  95 */ "AggFinal",
14477      /*  96 */ "Dup",
14478      /*  97 */ "Goto",
14479      /*  98 */ "TableLock",
14480      /*  99 */ "FifoRead",
14481      /* 100 */ "Clear",
14482      /* 101 */ "IdxGT",
14483      /* 102 */ "MoveLt",
14484      /* 103 */ "VerifyCookie",
14485      /* 104 */ "AggStep",
14486      /* 105 */ "Pull",
14487      /* 106 */ "SetNumColumns",
14488      /* 107 */ "AbsValue",
14489      /* 108 */ "Transaction",
14490      /* 109 */ "VFilter",
14491      /* 110 */ "VDestroy",
14492      /* 111 */ "ContextPop",
14493      /* 112 */ "Next",
14494      /* 113 */ "IdxInsert",
14495      /* 114 */ "Distinct",
14496      /* 115 */ "Insert",
14497      /* 116 */ "Destroy",
14498      /* 117 */ "ReadCookie",
14499      /* 118 */ "ForceInt",
14500      /* 119 */ "LoadAnalysis",
14501      /* 120 */ "Explain",
14502      /* 121 */ "IfMemZero",
14503      /* 122 */ "OpenPseudo",
14504      /* 123 */ "OpenEphemeral",
14505      /* 124 */ "Null",
14506      /* 125 */ "Real",
14507      /* 126 */ "HexBlob",
14508      /* 127 */ "Blob",
14509      /* 128 */ "MemStore",
14510      /* 129 */ "Rewind",
14511      /* 130 */ "MoveGe",
14512      /* 131 */ "VBegin",
14513      /* 132 */ "VUpdate",
14514      /* 133 */ "VCreate",
14515      /* 134 */ "MemMove",
14516      /* 135 */ "MemNull",
14517      /* 136 */ "Found",
14518      /* 137 */ "NullRow",
14519      /* 138 */ "ToText",
14520      /* 139 */ "ToBlob",
14521      /* 140 */ "ToNumeric",
14522      /* 141 */ "ToInt",
14523      /* 142 */ "ToReal",
14524   };
14525   return azName[i];
14526 }
14527 #endif
14528
14529 /************** End of opcodes.c *********************************************/
14530 /************** Begin file os_os2.c ******************************************/
14531 /*
14532 ** 2006 Feb 14
14533 **
14534 ** The author disclaims copyright to this source code.  In place of
14535 ** a legal notice, here is a blessing:
14536 **
14537 **    May you do good and not evil.
14538 **    May you find forgiveness for yourself and forgive others.
14539 **    May you share freely, never taking more than you give.
14540 **
14541 ******************************************************************************
14542 **
14543 ** This file contains code that is specific to OS/2.
14544 */
14545
14546
14547 #if OS_OS2
14548
14549 /*
14550 ** A Note About Memory Allocation:
14551 **
14552 ** This driver uses malloc()/free() directly rather than going through
14553 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
14554 ** are designed for use on embedded systems where memory is scarce and
14555 ** malloc failures happen frequently.  OS/2 does not typically run on
14556 ** embedded systems, and when it does the developers normally have bigger
14557 ** problems to worry about than running out of memory.  So there is not
14558 ** a compelling need to use the wrappers.
14559 **
14560 ** But there is a good reason to not use the wrappers.  If we use the
14561 ** wrappers then we will get simulated malloc() failures within this
14562 ** driver.  And that causes all kinds of problems for our tests.  We
14563 ** could enhance SQLite to deal with simulated malloc failures within
14564 ** the OS driver, but the code to deal with those failure would not
14565 ** be exercised on Linux (which does not need to malloc() in the driver)
14566 ** and so we would have difficulty writing coverage tests for that
14567 ** code.  Better to leave the code out, we think.
14568 **
14569 ** The point of this discussion is as follows:  When creating a new
14570 ** OS layer for an embedded system, if you use this file as an example,
14571 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
14572 ** desktops but not so well in embedded systems.
14573 */
14574
14575 /*
14576 ** Macros used to determine whether or not to use threads.
14577 */
14578 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
14579 # define SQLITE_OS2_THREADS 1
14580 #endif
14581
14582 /*
14583 ** Include code that is common to all os_*.c files
14584 */
14585 /************** Include os_common.h in the middle of os_os2.c ****************/
14586 /************** Begin file os_common.h ***************************************/
14587 /*
14588 ** 2004 May 22
14589 **
14590 ** The author disclaims copyright to this source code.  In place of
14591 ** a legal notice, here is a blessing:
14592 **
14593 **    May you do good and not evil.
14594 **    May you find forgiveness for yourself and forgive others.
14595 **    May you share freely, never taking more than you give.
14596 **
14597 ******************************************************************************
14598 **
14599 ** This file contains macros and a little bit of code that is common to
14600 ** all of the platform-specific files (os_*.c) and is #included into those
14601 ** files.
14602 **
14603 ** This file should be #included by the os_*.c files only.  It is not a
14604 ** general purpose header file.
14605 */
14606
14607 /*
14608 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
14609 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
14610 ** switch.  The following code should catch this problem at compile-time.
14611 */
14612 #ifdef MEMORY_DEBUG
14613 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
14614 #endif
14615
14616
14617 /*
14618  * When testing, this global variable stores the location of the
14619  * pending-byte in the database file.
14620  */
14621 #ifdef SQLITE_TEST
14622 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
14623 #endif
14624
14625 #ifdef SQLITE_DEBUG
14626 SQLITE_API int sqlite3_os_trace = 0;
14627 #define OSTRACE1(X)         if( sqlite3_os_trace ) sqlite3DebugPrintf(X)
14628 #define OSTRACE2(X,Y)       if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y)
14629 #define OSTRACE3(X,Y,Z)     if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z)
14630 #define OSTRACE4(X,Y,Z,A)   if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z,A)
14631 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z,A,B)
14632 #define OSTRACE6(X,Y,Z,A,B,C) \
14633     if(sqlite3_os_trace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
14634 #define OSTRACE7(X,Y,Z,A,B,C,D) \
14635     if(sqlite3_os_trace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
14636 #else
14637 #define OSTRACE1(X)
14638 #define OSTRACE2(X,Y)
14639 #define OSTRACE3(X,Y,Z)
14640 #define OSTRACE4(X,Y,Z,A)
14641 #define OSTRACE5(X,Y,Z,A,B)
14642 #define OSTRACE6(X,Y,Z,A,B,C)
14643 #define OSTRACE7(X,Y,Z,A,B,C,D)
14644 #endif
14645
14646 /*
14647 ** Macros for performance tracing.  Normally turned off.  Only works
14648 ** on i486 hardware.
14649 */
14650 #ifdef SQLITE_PERFORMANCE_TRACE
14651 __inline__ unsigned long long int hwtime(void){
14652   unsigned long long int x;
14653   __asm__("rdtsc\n\t"
14654           "mov %%edx, %%ecx\n\t"
14655           :"=A" (x));
14656   return x;
14657 }
14658 static unsigned long long int g_start;
14659 static unsigned int elapse;
14660 #define TIMER_START       g_start=hwtime()
14661 #define TIMER_END         elapse=hwtime()-g_start
14662 #define TIMER_ELAPSED     elapse
14663 #else
14664 #define TIMER_START
14665 #define TIMER_END
14666 #define TIMER_ELAPSED     0
14667 #endif
14668
14669 /*
14670 ** If we compile with the SQLITE_TEST macro set, then the following block
14671 ** of code will give us the ability to simulate a disk I/O error.  This
14672 ** is used for testing the I/O recovery logic.
14673 */
14674 #ifdef SQLITE_TEST
14675 SQLITE_API int sqlite3_io_error_hit = 0;
14676 SQLITE_API int sqlite3_io_error_pending = 0;
14677 SQLITE_API int sqlite3_io_error_persist = 0;
14678 SQLITE_API int sqlite3_diskfull_pending = 0;
14679 SQLITE_API int sqlite3_diskfull = 0;
14680 #define SimulateIOError(CODE)  \
14681   if( sqlite3_io_error_pending || sqlite3_io_error_hit ) \
14682      if( sqlite3_io_error_pending-- == 1 \
14683          || (sqlite3_io_error_persist && sqlite3_io_error_hit) ) \
14684                 { local_ioerr(); CODE; }
14685 static void local_ioerr(){
14686   IOTRACE(("IOERR\n"));
14687   sqlite3_io_error_hit = 1;
14688 }
14689 #define SimulateDiskfullError(CODE) \
14690    if( sqlite3_diskfull_pending ){ \
14691      if( sqlite3_diskfull_pending == 1 ){ \
14692        local_ioerr(); \
14693        sqlite3_diskfull = 1; \
14694        sqlite3_io_error_hit = 1; \
14695        CODE; \
14696      }else{ \
14697        sqlite3_diskfull_pending--; \
14698      } \
14699    }
14700 #else
14701 #define SimulateIOError(A)
14702 #define SimulateDiskfullError(A)
14703 #endif
14704
14705 /*
14706 ** When testing, keep a count of the number of open files.
14707 */
14708 #ifdef SQLITE_TEST
14709 SQLITE_API int sqlite3_open_file_count = 0;
14710 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
14711 #else
14712 #define OpenCounter(X)
14713 #endif
14714
14715 /************** End of os_common.h *******************************************/
14716 /************** Continuing where we left off in os_os2.c *********************/
14717
14718 /*
14719 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
14720 ** protability layer.
14721 */
14722 typedef struct os2File os2File;
14723 struct os2File {
14724   const sqlite3_io_methods *pMethod;  /* Always the first entry */
14725   HFILE h;                  /* Handle for accessing the file */
14726   int delOnClose;           /* True if file is to be deleted on close */
14727   char* pathToDel;          /* Name of file to delete on close */
14728   unsigned char locktype;   /* Type of lock currently held on this file */
14729 };
14730
14731 /*****************************************************************************
14732 ** The next group of routines implement the I/O methods specified
14733 ** by the sqlite3_io_methods object.
14734 ******************************************************************************/
14735
14736 /*
14737 ** Close a file.
14738 */
14739 int os2Close( sqlite3_file *id ){
14740   APIRET rc = NO_ERROR;
14741   os2File *pFile;
14742   if( id && (pFile = (os2File*)id) != 0 ){
14743     OSTRACE2( "CLOSE %d\n", pFile->h );
14744     rc = DosClose( pFile->h );
14745     pFile->locktype = NO_LOCK;
14746     if( pFile->delOnClose != 0 ){
14747       rc = DosForceDelete( (PSZ)pFile->pathToDel );
14748     }
14749     if( pFile->pathToDel ){
14750       free( pFile->pathToDel );
14751     }
14752     id = 0;
14753     OpenCounter( -1 );
14754   }
14755
14756   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
14757 }
14758
14759 /*
14760 ** Read data from a file into a buffer.  Return SQLITE_OK if all
14761 ** bytes were read successfully and SQLITE_IOERR if anything goes
14762 ** wrong.
14763 */
14764 int os2Read(
14765   sqlite3_file *id,               /* File to read from */
14766   void *pBuf,                     /* Write content into this buffer */
14767   int amt,                        /* Number of bytes to read */
14768   sqlite3_int64 offset            /* Begin reading at this offset */
14769 ){
14770   ULONG fileLocation = 0L;
14771   ULONG got;
14772   os2File *pFile = (os2File*)id;
14773   assert( id!=0 );
14774   SimulateIOError( return SQLITE_IOERR_READ );
14775   OSTRACE3( "READ %d lock=%d\n", pFile->h, pFile->locktype );
14776   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
14777     return SQLITE_IOERR;
14778   }
14779   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
14780     return SQLITE_IOERR_READ;
14781   }
14782   if( got == (ULONG)amt )
14783     return SQLITE_OK;
14784   else {
14785     memset(&((char*)pBuf)[got], 0, amt-got);
14786     return SQLITE_IOERR_SHORT_READ;
14787   }
14788 }
14789
14790 /*
14791 ** Write data from a buffer into a file.  Return SQLITE_OK on success
14792 ** or some other error code on failure.
14793 */
14794 int os2Write(
14795   sqlite3_file *id,               /* File to write into */
14796   const void *pBuf,               /* The bytes to be written */
14797   int amt,                        /* Number of bytes to write */
14798   sqlite3_int64 offset            /* Offset into the file to begin writing at */
14799 ){
14800   ULONG fileLocation = 0L;
14801   APIRET rc = NO_ERROR;
14802   ULONG wrote;
14803   os2File *pFile = (os2File*)id;
14804   assert( id!=0 );
14805   SimulateIOError( return SQLITE_IOERR_WRITE );
14806   SimulateDiskfullError( return SQLITE_FULL );
14807   OSTRACE3( "WRITE %d lock=%d\n", pFile->h, pFile->locktype );
14808   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
14809     return SQLITE_IOERR;
14810   }
14811   assert( amt>0 );
14812   while( amt > 0 &&
14813          (rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote )) &&
14814          wrote > 0
14815   ){
14816     amt -= wrote;
14817     pBuf = &((char*)pBuf)[wrote];
14818   }
14819
14820   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
14821 }
14822
14823 /*
14824 ** Truncate an open file to a specified size
14825 */
14826 int os2Truncate( sqlite3_file *id, i64 nByte ){
14827   APIRET rc = NO_ERROR;
14828   ULONG filePosition = 0L;
14829   os2File *pFile = (os2File*)id;
14830   OSTRACE3( "TRUNCATE %d %lld\n", pFile->h, nByte );
14831   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
14832   rc = DosSetFilePtr( pFile->h, nByte, FILE_BEGIN, &filePosition );
14833   if( rc != NO_ERROR ){
14834     return SQLITE_IOERR;
14835   }
14836   rc = DosSetFilePtr( pFile->h, 0L, FILE_END, &filePosition );
14837   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
14838 }
14839
14840 #ifdef SQLITE_TEST
14841 /*
14842 ** Count the number of fullsyncs and normal syncs.  This is used to test
14843 ** that syncs and fullsyncs are occuring at the right times.
14844 */
14845 SQLITE_API int sqlite3_sync_count = 0;
14846 SQLITE_API int sqlite3_fullsync_count = 0;
14847 #endif
14848
14849 /*
14850 ** Make sure all writes to a particular file are committed to disk.
14851 */
14852 int os2Sync( sqlite3_file *id, int flags ){
14853   os2File *pFile = (os2File*)id;
14854   OSTRACE3( "SYNC %d lock=%d\n", pFile->h, pFile->locktype );
14855 #ifdef SQLITE_TEST
14856   if( flags & SQLITE_SYNC_FULL){
14857     sqlite3_fullsync_count++;
14858   }
14859   sqlite3_sync_count++;
14860 #endif
14861   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
14862 }
14863
14864 /*
14865 ** Determine the current size of a file in bytes
14866 */
14867 int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
14868   APIRET rc = NO_ERROR;
14869   FILESTATUS3 fsts3FileInfo;
14870   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
14871   assert( id!=0 );
14872   SimulateIOError( return SQLITE_IOERR );
14873   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
14874   if( rc == NO_ERROR ){
14875     *pSize = fsts3FileInfo.cbFile;
14876     return SQLITE_OK;
14877   }else{
14878     return SQLITE_IOERR;
14879   }
14880 }
14881
14882 /*
14883 ** Acquire a reader lock.
14884 */
14885 static int getReadLock( os2File *pFile ){
14886   FILELOCK  LockArea,
14887             UnlockArea;
14888   APIRET res;
14889   memset(&LockArea, 0, sizeof(LockArea));
14890   memset(&UnlockArea, 0, sizeof(UnlockArea));
14891   LockArea.lOffset = SHARED_FIRST;
14892   LockArea.lRange = SHARED_SIZE;
14893   UnlockArea.lOffset = 0L;
14894   UnlockArea.lRange = 0L;
14895   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
14896   OSTRACE3( "GETREADLOCK %d res=%d\n", pFile->h, res );
14897   return res;
14898 }
14899
14900 /*
14901 ** Undo a readlock
14902 */
14903 static int unlockReadLock( os2File *id ){
14904   FILELOCK  LockArea,
14905             UnlockArea;
14906   APIRET res;
14907   memset(&LockArea, 0, sizeof(LockArea));
14908   memset(&UnlockArea, 0, sizeof(UnlockArea));
14909   LockArea.lOffset = 0L;
14910   LockArea.lRange = 0L;
14911   UnlockArea.lOffset = SHARED_FIRST;
14912   UnlockArea.lRange = SHARED_SIZE;
14913   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, 2000L, 1L );
14914   OSTRACE3( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res );
14915   return res;
14916 }
14917
14918 /*
14919 ** Lock the file with the lock specified by parameter locktype - one
14920 ** of the following:
14921 **
14922 **     (1) SHARED_LOCK
14923 **     (2) RESERVED_LOCK
14924 **     (3) PENDING_LOCK
14925 **     (4) EXCLUSIVE_LOCK
14926 **
14927 ** Sometimes when requesting one lock state, additional lock states
14928 ** are inserted in between.  The locking might fail on one of the later
14929 ** transitions leaving the lock state different from what it started but
14930 ** still short of its goal.  The following chart shows the allowed
14931 ** transitions and the inserted intermediate states:
14932 **
14933 **    UNLOCKED -> SHARED
14934 **    SHARED -> RESERVED
14935 **    SHARED -> (PENDING) -> EXCLUSIVE
14936 **    RESERVED -> (PENDING) -> EXCLUSIVE
14937 **    PENDING -> EXCLUSIVE
14938 **
14939 ** This routine will only increase a lock.  The os2Unlock() routine
14940 ** erases all locks at once and returns us immediately to locking level 0.
14941 ** It is not possible to lower the locking level one step at a time.  You
14942 ** must go straight to locking level 0.
14943 */
14944 int os2Lock( sqlite3_file *id, int locktype ){
14945   int rc = SQLITE_OK;       /* Return code from subroutines */
14946   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
14947   int newLocktype;       /* Set pFile->locktype to this value before exiting */
14948   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
14949   FILELOCK  LockArea,
14950             UnlockArea;
14951   os2File *pFile = (os2File*)id;
14952   memset(&LockArea, 0, sizeof(LockArea));
14953   memset(&UnlockArea, 0, sizeof(UnlockArea));
14954   assert( pFile!=0 );
14955   OSTRACE4( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype );
14956
14957   /* If there is already a lock of this type or more restrictive on the
14958   ** os2File, do nothing. Don't use the end_lock: exit path, as
14959   ** sqlite3OsEnterMutex() hasn't been called yet.
14960   */
14961   if( pFile->locktype>=locktype ){
14962     OSTRACE3( "LOCK %d %d ok (already held)\n", pFile->h, locktype );
14963     return SQLITE_OK;
14964   }
14965
14966   /* Make sure the locking sequence is correct
14967   */
14968   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
14969   assert( locktype!=PENDING_LOCK );
14970   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
14971
14972   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
14973   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
14974   ** the PENDING_LOCK byte is temporary.
14975   */
14976   newLocktype = pFile->locktype;
14977   if( pFile->locktype==NO_LOCK
14978       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
14979   ){
14980     int cnt = 3;
14981
14982     LockArea.lOffset = PENDING_BYTE;
14983     LockArea.lRange = 1L;
14984     UnlockArea.lOffset = 0L;
14985     UnlockArea.lRange = 0L;
14986
14987     while( cnt-->0 && ( res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L) )
14988                       != NO_ERROR
14989     ){
14990       /* Try 3 times to get the pending lock.  The pending lock might be
14991       ** held by another reader process who will release it momentarily.
14992       */
14993       OSTRACE2( "LOCK could not get a PENDING lock. cnt=%d\n", cnt );
14994       DosSleep(1);
14995     }
14996     if( res == NO_ERROR){
14997       gotPendingLock = 1;
14998       OSTRACE3( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res );
14999     }
15000   }
15001
15002   /* Acquire a shared lock
15003   */
15004   if( locktype==SHARED_LOCK && res == NO_ERROR ){
15005     assert( pFile->locktype==NO_LOCK );
15006     res = getReadLock(pFile);
15007     if( res == NO_ERROR ){
15008       newLocktype = SHARED_LOCK;
15009     }
15010     OSTRACE3( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res );
15011   }
15012
15013   /* Acquire a RESERVED lock
15014   */
15015   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
15016     assert( pFile->locktype==SHARED_LOCK );
15017     LockArea.lOffset = RESERVED_BYTE;
15018     LockArea.lRange = 1L;
15019     UnlockArea.lOffset = 0L;
15020     UnlockArea.lRange = 0L;
15021     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
15022     if( res == NO_ERROR ){
15023       newLocktype = RESERVED_LOCK;
15024     }
15025     OSTRACE3( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res );
15026   }
15027
15028   /* Acquire a PENDING lock
15029   */
15030   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
15031     newLocktype = PENDING_LOCK;
15032     gotPendingLock = 0;
15033     OSTRACE2( "LOCK %d acquire pending lock. pending lock boolean unset.\n", pFile->h );
15034   }
15035
15036   /* Acquire an EXCLUSIVE lock
15037   */
15038   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
15039     assert( pFile->locktype>=SHARED_LOCK );
15040     res = unlockReadLock(pFile);
15041     OSTRACE2( "unreadlock = %d\n", res );
15042     LockArea.lOffset = SHARED_FIRST;
15043     LockArea.lRange = SHARED_SIZE;
15044     UnlockArea.lOffset = 0L;
15045     UnlockArea.lRange = 0L;
15046     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
15047     if( res == NO_ERROR ){
15048       newLocktype = EXCLUSIVE_LOCK;
15049     }else{
15050       OSTRACE2( "OS/2 error-code = %d\n", res );
15051       getReadLock(pFile);
15052     }
15053     OSTRACE3( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res );
15054   }
15055
15056   /* If we are holding a PENDING lock that ought to be released, then
15057   ** release it now.
15058   */
15059   if( gotPendingLock && locktype==SHARED_LOCK ){
15060     int r;
15061     LockArea.lOffset = 0L;
15062     LockArea.lRange = 0L;
15063     UnlockArea.lOffset = PENDING_BYTE;
15064     UnlockArea.lRange = 1L;
15065     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
15066     OSTRACE3( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r );
15067   }
15068
15069   /* Update the state of the lock has held in the file descriptor then
15070   ** return the appropriate result code.
15071   */
15072   if( res == NO_ERROR ){
15073     rc = SQLITE_OK;
15074   }else{
15075     OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
15076               locktype, newLocktype );
15077     rc = SQLITE_BUSY;
15078   }
15079   pFile->locktype = newLocktype;
15080   OSTRACE3( "LOCK %d now %d\n", pFile->h, pFile->locktype );
15081   return rc;
15082 }
15083
15084 /*
15085 ** This routine checks if there is a RESERVED lock held on the specified
15086 ** file by this or any other process. If such a lock is held, return
15087 ** non-zero, otherwise zero.
15088 */
15089 int os2CheckReservedLock( sqlite3_file *id ){
15090   APIRET rc = NO_ERROR;
15091   os2File *pFile = (os2File*)id;
15092   assert( pFile!=0 );
15093   if( pFile->locktype>=RESERVED_LOCK ){
15094     rc = 1;
15095     OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile->h, rc );
15096   }else{
15097     FILELOCK  LockArea,
15098               UnlockArea;
15099     memset(&LockArea, 0, sizeof(LockArea));
15100     memset(&UnlockArea, 0, sizeof(UnlockArea));
15101     LockArea.lOffset = RESERVED_BYTE;
15102     LockArea.lRange = 1L;
15103     UnlockArea.lOffset = 0L;
15104     UnlockArea.lRange = 0L;
15105     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
15106     OSTRACE3( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc );
15107     if( rc == NO_ERROR ){
15108       int r;
15109       LockArea.lOffset = 0L;
15110       LockArea.lRange = 0L;
15111       UnlockArea.lOffset = RESERVED_BYTE;
15112       UnlockArea.lRange = 1L;
15113       r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
15114       OSTRACE3( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, r );
15115     }
15116     OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile->h, rc );
15117   }
15118   return rc;
15119 }
15120
15121 /*
15122 ** Lower the locking level on file descriptor id to locktype.  locktype
15123 ** must be either NO_LOCK or SHARED_LOCK.
15124 **
15125 ** If the locking level of the file descriptor is already at or below
15126 ** the requested locking level, this routine is a no-op.
15127 **
15128 ** It is not possible for this routine to fail if the second argument
15129 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
15130 ** might return SQLITE_IOERR;
15131 */
15132 int os2Unlock( sqlite3_file *id, int locktype ){
15133   int type;
15134   os2File *pFile = (os2File*)id;
15135   APIRET rc = SQLITE_OK;
15136   APIRET res = NO_ERROR;
15137   FILELOCK  LockArea,
15138             UnlockArea;
15139   memset(&LockArea, 0, sizeof(LockArea));
15140   memset(&UnlockArea, 0, sizeof(UnlockArea));
15141   assert( pFile!=0 );
15142   assert( locktype<=SHARED_LOCK );
15143   OSTRACE4( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype );
15144   type = pFile->locktype;
15145   if( type>=EXCLUSIVE_LOCK ){
15146     LockArea.lOffset = 0L;
15147     LockArea.lRange = 0L;
15148     UnlockArea.lOffset = SHARED_FIRST;
15149     UnlockArea.lRange = SHARED_SIZE;
15150     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
15151     OSTRACE3( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res );
15152     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
15153       /* This should never happen.  We should always be able to
15154       ** reacquire the read lock */
15155       OSTRACE3( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype );
15156       rc = SQLITE_IOERR_UNLOCK;
15157     }
15158   }
15159   if( type>=RESERVED_LOCK ){
15160     LockArea.lOffset = 0L;
15161     LockArea.lRange = 0L;
15162     UnlockArea.lOffset = RESERVED_BYTE;
15163     UnlockArea.lRange = 1L;
15164     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
15165     OSTRACE3( "UNLOCK %d reserved res=%d\n", pFile->h, res );
15166   }
15167   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
15168     res = unlockReadLock(pFile);
15169     OSTRACE5( "UNLOCK %d is %d want %d res=%d\n", pFile->h, type, locktype, res );
15170   }
15171   if( type>=PENDING_LOCK ){
15172     LockArea.lOffset = 0L;
15173     LockArea.lRange = 0L;
15174     UnlockArea.lOffset = PENDING_BYTE;
15175     UnlockArea.lRange = 1L;
15176     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
15177     OSTRACE3( "UNLOCK %d pending res=%d\n", pFile->h, res );
15178   }
15179   pFile->locktype = locktype;
15180   OSTRACE3( "UNLOCK %d now %d\n", pFile->h, pFile->locktype );
15181   return rc;
15182 }
15183
15184 /*
15185 ** Control and query of the open file handle.
15186 */
15187 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
15188   switch( op ){
15189     case SQLITE_FCNTL_LOCKSTATE: {
15190       *(int*)pArg = ((os2File*)id)->locktype;
15191       OSTRACE3( "FCNTL_LOCKSTATE %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
15192       return SQLITE_OK;
15193     }
15194   }
15195   return SQLITE_ERROR;
15196 }
15197
15198 /*
15199 ** Return the sector size in bytes of the underlying block device for
15200 ** the specified file. This is almost always 512 bytes, but may be
15201 ** larger for some devices.
15202 **
15203 ** SQLite code assumes this function cannot fail. It also assumes that
15204 ** if two files are created in the same file-system directory (i.e.
15205 ** a database and its journal file) that the sector size will be the
15206 ** same for both.
15207 */
15208 static int os2SectorSize(sqlite3_file *id){
15209   return SQLITE_DEFAULT_SECTOR_SIZE;
15210 }
15211
15212 /*
15213 ** Return a vector of device characteristics.
15214 */
15215 static int os2DeviceCharacteristics(sqlite3_file *id){
15216   return 0;
15217 }
15218
15219 /*
15220 ** This vector defines all the methods that can operate on an
15221 ** sqlite3_file for os2.
15222 */
15223 static const sqlite3_io_methods os2IoMethod = {
15224   1,                        /* iVersion */
15225   os2Close,
15226   os2Read,
15227   os2Write,
15228   os2Truncate,
15229   os2Sync,
15230   os2FileSize,
15231   os2Lock,
15232   os2Unlock,
15233   os2CheckReservedLock,
15234   os2FileControl,
15235   os2SectorSize,
15236   os2DeviceCharacteristics
15237 };
15238
15239 /***************************************************************************
15240 ** Here ends the I/O methods that form the sqlite3_io_methods object.
15241 **
15242 ** The next block of code implements the VFS methods.
15243 ****************************************************************************/
15244
15245 /*
15246 ** Open a file.
15247 */
15248 static int os2Open(
15249   sqlite3_vfs *pVfs,            /* Not used */
15250   const char *zName,            /* Name of the file */
15251   sqlite3_file *id,             /* Write the SQLite file handle here */
15252   int flags,                    /* Open mode flags */
15253   int *pOutFlags                /* Status return flags */
15254 ){
15255   HFILE h;
15256   ULONG ulFileAttribute = 0;
15257   ULONG ulOpenFlags = 0;
15258   ULONG ulOpenMode = 0;
15259   os2File *pFile = (os2File*)id;
15260   APIRET rc = NO_ERROR;
15261   ULONG ulAction;
15262
15263   memset(pFile, 0, sizeof(*pFile));
15264
15265   OSTRACE2( "OPEN want %d\n", flags );
15266
15267   //ulOpenMode = flags & SQLITE_OPEN_READWRITE ? OPEN_ACCESS_READWRITE : OPEN_ACCESS_READONLY;
15268   if( flags & SQLITE_OPEN_READWRITE ){
15269     ulOpenMode |= OPEN_ACCESS_READWRITE;
15270     OSTRACE1( "OPEN read/write\n" );
15271   }else{
15272     ulOpenMode |= OPEN_ACCESS_READONLY;
15273     OSTRACE1( "OPEN read only\n" );
15274   }
15275
15276   //ulOpenFlags = flags & SQLITE_OPEN_CREATE ? OPEN_ACTION_CREATE_IF_NEW : OPEN_ACTION_FAIL_IF_NEW;
15277   if( flags & SQLITE_OPEN_CREATE ){
15278     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
15279     OSTRACE1( "OPEN open new/create\n" );
15280   }else{
15281     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
15282     OSTRACE1( "OPEN open existing\n" );
15283   }
15284
15285   //ulOpenMode |= flags & SQLITE_OPEN_MAIN_DB ? OPEN_SHARE_DENYNONE : OPEN_SHARE_DENYWRITE;
15286   if( flags & SQLITE_OPEN_MAIN_DB ){
15287     ulOpenMode |= OPEN_SHARE_DENYNONE;
15288     OSTRACE1( "OPEN share read/write\n" );
15289   }else{
15290     ulOpenMode |= OPEN_SHARE_DENYWRITE;
15291     OSTRACE1( "OPEN share read only\n" );
15292   }
15293
15294   if( flags & (SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_TEMP_JOURNAL
15295                | SQLITE_OPEN_SUBJOURNAL) ){
15296     //ulFileAttribute = FILE_HIDDEN;  //for debugging, we want to make sure it is deleted
15297     ulFileAttribute = FILE_NORMAL;
15298     pFile->delOnClose = 1;
15299     pFile->pathToDel = (char*)malloc(sizeof(char) * pVfs->mxPathname);
15300     sqlite3OsFullPathname(pVfs, zName, pVfs->mxPathname, pFile->pathToDel);
15301     OSTRACE1( "OPEN hidden/delete on close file attributes\n" );
15302   }else{
15303     ulFileAttribute = FILE_ARCHIVED | FILE_NORMAL;
15304     pFile->delOnClose = 0;
15305     pFile->pathToDel = NULL;
15306     OSTRACE1( "OPEN normal file attribute\n" );
15307   }
15308
15309   //ulOpenMode |= flags & (SQLITE_OPEN_MAIN_DB | SQLITE_OPEN_TEMP_DB) ?
15310   //                  OPEN_FLAGS_RANDOM : OPEN_FLAGS_SEQUENTIAL;
15311   if( flags & (SQLITE_OPEN_MAIN_DB | SQLITE_OPEN_TEMP_DB) ){
15312     ulOpenMode |= OPEN_FLAGS_RANDOM;
15313     OSTRACE1( "OPEN random access\n" );
15314   }else{
15315     ulOpenMode |= OPEN_FLAGS_SEQUENTIAL;
15316     OSTRACE1( "OPEN sequential access\n" );
15317   }
15318   ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
15319
15320   rc = DosOpen( (PSZ)zName,
15321                 &h,
15322                 &ulAction,
15323                 0L,
15324                 ulFileAttribute,
15325                 ulOpenFlags,
15326                 ulOpenMode,
15327                 (PEAOP2)NULL );
15328   if( rc != NO_ERROR ){
15329     OSTRACE7( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
15330               rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode );
15331     if( flags & SQLITE_OPEN_READWRITE ){
15332       OSTRACE2( "OPEN %d Invalid handle\n", ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) );
15333       return os2Open( 0, zName, id,
15334                       ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
15335                       pOutFlags );
15336     }else{
15337       return SQLITE_CANTOPEN;
15338     }
15339   }
15340
15341   if( pOutFlags ){
15342     *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
15343   }
15344
15345   pFile->pMethod = &os2IoMethod;
15346   pFile->h = h;
15347   OpenCounter(+1);
15348   OSTRACE3( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags );
15349   return SQLITE_OK;
15350 }
15351
15352 /*
15353 ** Delete the named file.
15354 */
15355 int os2Delete(
15356   sqlite3_vfs *pVfs,                     /* Not used on os2 */
15357   const char *zFilename,                 /* Name of file to delete */
15358   int syncDir                            /* Not used on os2 */
15359 ){
15360   APIRET rc = NO_ERROR;
15361   SimulateIOError(return SQLITE_IOERR_DELETE);
15362   rc = DosDelete( (PSZ)zFilename );
15363   OSTRACE2( "DELETE \"%s\"\n", zFilename );
15364   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
15365 }
15366
15367 /*
15368 ** Check the existance and status of a file.
15369 */
15370 static int os2Access(
15371   sqlite3_vfs *pVfs,        /* Not used on os2 */
15372   const char *zFilename,    /* Name of file to check */
15373   int flags                 /* Type of test to make on this file */
15374 ){
15375   FILESTATUS3 fsts3ConfigInfo;
15376   APIRET rc = NO_ERROR;
15377
15378   memset(&fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo));
15379   rc = DosQueryPathInfo( (PSZ)zFilename, FIL_STANDARD,
15380                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
15381   OSTRACE4( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
15382             fsts3ConfigInfo.attrFile, flags, rc );
15383   switch( flags ){
15384     case SQLITE_ACCESS_READ:
15385     case SQLITE_ACCESS_EXISTS:
15386       rc = (rc == NO_ERROR);
15387       OSTRACE3( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc );
15388       break;
15389     case SQLITE_ACCESS_READWRITE:
15390       rc = (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0;
15391       OSTRACE3( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc );
15392       break;
15393     default:
15394       assert( !"Invalid flags argument" );
15395   }
15396   return rc;
15397 }
15398
15399
15400 /*
15401 ** Create a temporary file name in zBuf.  zBuf must be big enough to
15402 ** hold at pVfs->mxPathname characters.
15403 */
15404 static int os2GetTempname( sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
15405   static const unsigned char zChars[] =
15406     "abcdefghijklmnopqrstuvwxyz"
15407     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
15408     "0123456789";
15409   int i, j;
15410   PSZ zTempPath = "";
15411   if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
15412     if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
15413       if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
15414            ULONG ulDriveNum = 0, ulDriveMap = 0;
15415            DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
15416            sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
15417       }
15418     }
15419   }
15420   /* strip off a trailing slashes or backslashes, otherwise we would get *
15421    * multiple (back)slashes which causes DosOpen() to fail               */
15422   j = strlen(zTempPath);
15423   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/' ) ){
15424     j--;
15425   }
15426   zTempPath[j] = '\0';
15427   assert( nBuf>=pVfs->mxPathname );
15428   sqlite3_snprintf( pVfs->mxPathname-30, zBuf,
15429                     "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
15430   j = strlen( zBuf );
15431   sqlite3Randomness( 20, &zBuf[j] );
15432   for( i = 0; i < 20; i++, j++ ){
15433     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
15434   }
15435   zBuf[j] = 0;
15436   OSTRACE2( "TEMP FILENAME: %s\n", zBuf );
15437   return SQLITE_OK;
15438 }
15439
15440
15441 /*
15442 ** Turn a relative pathname into a full pathname.  Write the full
15443 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
15444 ** bytes in size.
15445 */
15446 static int os2FullPathname(
15447   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
15448   const char *zRelative,      /* Possibly relative input path */
15449   int nFull,                  /* Size of output buffer in bytes */
15450   char *zFull                 /* Output buffer */
15451 ){
15452   if( strchr(zRelative, ':') ){
15453     sqlite3SetString( &zFull, zRelative, (char*)0 );
15454   }else{
15455     ULONG ulDriveNum = 0;
15456     ULONG ulDriveMap = 0;
15457     ULONG cbzBufLen = SQLITE_TEMPNAME_SIZE;
15458     char zDrive[2];
15459     char *zBuff = (char*)malloc( cbzBufLen );
15460     if( zBuff == 0 ){
15461       return SQLITE_NOMEM;
15462     }
15463     DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
15464     if( DosQueryCurrentDir( ulDriveNum, (PBYTE)zBuff, &cbzBufLen ) == NO_ERROR ){
15465       sprintf( zDrive, "%c", (char)('A' + ulDriveNum - 1) );
15466       sqlite3SetString( &zFull, zDrive, ":\\", zBuff,
15467                         "\\", zRelative, (char*)0 );
15468     }
15469     free( zBuff );
15470   }
15471   return SQLITE_OK;
15472 }
15473
15474 #ifndef SQLITE_OMIT_LOAD_EXTENSION
15475 /*
15476 ** Interfaces for opening a shared library, finding entry points
15477 ** within the shared library, and closing the shared library.
15478 */
15479 /*
15480 ** Interfaces for opening a shared library, finding entry points
15481 ** within the shared library, and closing the shared library.
15482 */
15483 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
15484   UCHAR loadErr[256];
15485   HMODULE hmod;
15486   APIRET rc;
15487   rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilename, &hmod);
15488   return rc != NO_ERROR ? 0 : (void*)hmod;
15489 }
15490 /*
15491 ** A no-op since the error code is returned on the DosLoadModule call.
15492 ** os2Dlopen returns zero if DosLoadModule is not successful.
15493 */
15494 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
15495 /* no-op */
15496 }
15497 void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
15498   PFN pfn;
15499   APIRET rc;
15500   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
15501   if( rc != NO_ERROR ){
15502     /* if the symbol itself was not found, search again for the same
15503      * symbol with an extra underscore, that might be needed depending
15504      * on the calling convention */
15505     char _zSymbol[256] = "_";
15506     strncat(_zSymbol, zSymbol, 255);
15507     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
15508   }
15509   return rc != NO_ERROR ? 0 : (void*)pfn;
15510 }
15511 void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
15512   DosFreeModule((HMODULE)pHandle);
15513 }
15514 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
15515   #define os2DlOpen 0
15516   #define os2DlError 0
15517   #define os2DlSym 0
15518   #define os2DlClose 0
15519 #endif
15520
15521
15522 /*
15523 ** Write up to nBuf bytes of randomness into zBuf.
15524 */
15525 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
15526   ULONG sizeofULong = sizeof(ULONG);
15527   int n = 0;
15528   if( sizeof(DATETIME) <= nBuf - n ){
15529     DATETIME x;
15530     DosGetDateTime(&x);
15531     memcpy(&zBuf[n], &x, sizeof(x));
15532     n += sizeof(x);
15533   }
15534
15535   if( sizeofULong <= nBuf - n ){
15536     PPIB ppib;
15537     DosGetInfoBlocks(NULL, &ppib);
15538     memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
15539     n += sizeofULong;
15540   }
15541
15542   if( sizeofULong <= nBuf - n ){
15543     PTIB ptib;
15544     DosGetInfoBlocks(&ptib, NULL);
15545     memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
15546     n += sizeofULong;
15547   }
15548
15549   /* if we still haven't filled the buffer yet the following will */
15550   /* grab everything once instead of making several calls for a single item */
15551   if( sizeofULong <= nBuf - n ){
15552     ULONG ulSysInfo[QSV_MAX];
15553     DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
15554
15555     memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
15556     n += sizeofULong;
15557
15558     if( sizeofULong <= nBuf - n ){
15559       memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
15560       n += sizeofULong;
15561     }
15562     if( sizeofULong <= nBuf - n ){
15563       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
15564       n += sizeofULong;
15565     }
15566     if( sizeofULong <= nBuf - n ){
15567       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
15568       n += sizeofULong;
15569     }
15570     if( sizeofULong <= nBuf - n ){
15571       memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
15572       n += sizeofULong;
15573     }
15574   }
15575
15576   return n;
15577 }
15578
15579 /*
15580 ** Sleep for a little while.  Return the amount of time slept.
15581 ** The argument is the number of microseconds we want to sleep.
15582 ** The return value is the number of microseconds of sleep actually
15583 ** requested from the underlying operating system, a number which
15584 ** might be greater than or equal to the argument, but not less
15585 ** than the argument.
15586 */
15587 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
15588   DosSleep( (microsec/1000) );
15589   return microsec;
15590 }
15591
15592 /*
15593 ** The following variable, if set to a non-zero value, becomes the result
15594 ** returned from sqlite3OsCurrentTime().  This is used for testing.
15595 */
15596 #ifdef SQLITE_TEST
15597 SQLITE_API int sqlite3_current_time = 0;
15598 #endif
15599
15600 /*
15601 ** Find the current time (in Universal Coordinated Time).  Write the
15602 ** current time and date as a Julian Day number into *prNow and
15603 ** return 0.  Return 1 if the time and date cannot be found.
15604 */
15605 int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
15606   double now;
15607   SHORT minute; /* needs to be able to cope with negative timezone offset */
15608   USHORT second, hour,
15609          day, month, year;
15610   DATETIME dt;
15611   DosGetDateTime( &dt );
15612   second = (USHORT)dt.seconds;
15613   minute = (SHORT)dt.minutes + dt.timezone;
15614   hour = (USHORT)dt.hours;
15615   day = (USHORT)dt.day;
15616   month = (USHORT)dt.month;
15617   year = (USHORT)dt.year;
15618
15619   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
15620      http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
15621   /* Calculate the Julian days */
15622   now = day - 32076 +
15623     1461*(year + 4800 + (month - 14)/12)/4 +
15624     367*(month - 2 - (month - 14)/12*12)/12 -
15625     3*((year + 4900 + (month - 14)/12)/100)/4;
15626
15627   /* Add the fractional hours, mins and seconds */
15628   now += (hour + 12.0)/24.0;
15629   now += minute/1440.0;
15630   now += second/86400.0;
15631   *prNow = now;
15632 #ifdef SQLITE_TEST
15633   if( sqlite3_current_time ){
15634     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
15635   }
15636 #endif
15637   return 0;
15638 }
15639
15640 /*
15641 ** Return a pointer to the sqlite3DefaultVfs structure.   We use
15642 ** a function rather than give the structure global scope because
15643 ** some compilers (MSVC) do not allow forward declarations of
15644 ** initialized structures.
15645 */
15646 SQLITE_PRIVATE sqlite3_vfs *sqlite3OsDefaultVfs(void){
15647   static sqlite3_vfs os2Vfs = {
15648     1,                 /* iVersion */
15649     sizeof(os2File),   /* szOsFile */
15650     CCHMAXPATH,        /* mxPathname */
15651     0,                 /* pNext */
15652     "os2",             /* zName */
15653     0,                 /* pAppData */
15654
15655     os2Open,           /* xOpen */
15656     os2Delete,         /* xDelete */
15657     os2Access,         /* xAccess */
15658     os2GetTempname,    /* xGetTempname */
15659     os2FullPathname,   /* xFullPathname */
15660     os2DlOpen,         /* xDlOpen */
15661     os2DlError,        /* xDlError */
15662     os2DlSym,          /* xDlSym */
15663     os2DlClose,        /* xDlClose */
15664     os2Randomness,     /* xRandomness */
15665     os2Sleep,          /* xSleep */
15666     os2CurrentTime     /* xCurrentTime */
15667   };
15668
15669   return &os2Vfs;
15670 }
15671
15672 #endif /* OS_OS2 */
15673
15674 /************** End of os_os2.c **********************************************/
15675 /************** Begin file os_unix.c *****************************************/
15676 /*
15677 ** 2004 May 22
15678 **
15679 ** The author disclaims copyright to this source code.  In place of
15680 ** a legal notice, here is a blessing:
15681 **
15682 **    May you do good and not evil.
15683 **    May you find forgiveness for yourself and forgive others.
15684 **    May you share freely, never taking more than you give.
15685 **
15686 ******************************************************************************
15687 **
15688 ** This file contains code that is specific to Unix systems.
15689 */
15690 #if OS_UNIX              /* This file is used on unix only */
15691
15692 /* #define SQLITE_ENABLE_LOCKING_STYLE 0 */
15693
15694 /*
15695 ** These #defines should enable >2GB file support on Posix if the
15696 ** underlying operating system supports it.  If the OS lacks
15697 ** large file support, these should be no-ops.
15698 **
15699 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
15700 ** on the compiler command line.  This is necessary if you are compiling
15701 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
15702 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
15703 ** without this option, LFS is enable.  But LFS does not exist in the kernel
15704 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
15705 ** portability you should omit LFS.
15706 */
15707 #ifndef SQLITE_DISABLE_LFS
15708 # define _LARGE_FILE       1
15709 # ifndef _FILE_OFFSET_BITS
15710 #   define _FILE_OFFSET_BITS 64
15711 # endif
15712 # define _LARGEFILE_SOURCE 1
15713 #endif
15714
15715 /*
15716 ** standard include files.
15717 */
15718 #include <sys/types.h>
15719 #include <sys/stat.h>
15720 #include <fcntl.h>
15721 #include <unistd.h>
15722 #include <sys/time.h>
15723 #include <errno.h>
15724 #ifdef SQLITE_ENABLE_LOCKING_STYLE
15725 #include <sys/ioctl.h>
15726 #include <sys/param.h>
15727 #include <sys/mount.h>
15728 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
15729
15730 /*
15731 ** If we are to be thread-safe, include the pthreads header and define
15732 ** the SQLITE_UNIX_THREADS macro.
15733 */
15734 #if SQLITE_THREADSAFE
15735 # define SQLITE_UNIX_THREADS 1
15736 #endif
15737
15738 /*
15739 ** Default permissions when creating a new file
15740 */
15741 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
15742 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
15743 #endif
15744
15745 /*
15746 ** Maximum supported path-length.
15747 */
15748 #define MAX_PATHNAME 512
15749
15750
15751 /*
15752 ** The unixFile structure is subclass of sqlite3_file specific for the unix
15753 ** protability layer.
15754 */
15755 typedef struct unixFile unixFile;
15756 struct unixFile {
15757   sqlite3_io_methods const *pMethod;  /* Always the first entry */
15758 #ifdef SQLITE_TEST
15759   /* In test mode, increase the size of this structure a bit so that 
15760   ** it is larger than the struct CrashFile defined in test6.c.
15761   */
15762   char aPadding[32];
15763 #endif
15764   struct openCnt *pOpen;    /* Info about all open fd's on this inode */
15765   struct lockInfo *pLock;   /* Info about locks on this inode */
15766 #ifdef SQLITE_ENABLE_LOCKING_STYLE
15767   void *lockingContext;     /* Locking style specific state */
15768 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
15769   int h;                    /* The file descriptor */
15770   unsigned char locktype;   /* The type of lock held on this fd */
15771   int dirfd;                /* File descriptor for the directory */
15772 #if SQLITE_THREADSAFE
15773   pthread_t tid;            /* The thread that "owns" this unixFile */
15774 #endif
15775 };
15776
15777 /*
15778 ** Include code that is common to all os_*.c files
15779 */
15780 /************** Include os_common.h in the middle of os_unix.c ***************/
15781 /************** Begin file os_common.h ***************************************/
15782 /*
15783 ** 2004 May 22
15784 **
15785 ** The author disclaims copyright to this source code.  In place of
15786 ** a legal notice, here is a blessing:
15787 **
15788 **    May you do good and not evil.
15789 **    May you find forgiveness for yourself and forgive others.
15790 **    May you share freely, never taking more than you give.
15791 **
15792 ******************************************************************************
15793 **
15794 ** This file contains macros and a little bit of code that is common to
15795 ** all of the platform-specific files (os_*.c) and is #included into those
15796 ** files.
15797 **
15798 ** This file should be #included by the os_*.c files only.  It is not a
15799 ** general purpose header file.
15800 */
15801
15802 /*
15803 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
15804 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
15805 ** switch.  The following code should catch this problem at compile-time.
15806 */
15807 #ifdef MEMORY_DEBUG
15808 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
15809 #endif
15810
15811
15812 /*
15813  * When testing, this global variable stores the location of the
15814  * pending-byte in the database file.
15815  */
15816 #ifdef SQLITE_TEST
15817 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
15818 #endif
15819
15820 #ifdef SQLITE_DEBUG
15821 SQLITE_API int sqlite3_os_trace = 0;
15822 #define OSTRACE1(X)         if( sqlite3_os_trace ) sqlite3DebugPrintf(X)
15823 #define OSTRACE2(X,Y)       if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y)
15824 #define OSTRACE3(X,Y,Z)     if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z)
15825 #define OSTRACE4(X,Y,Z,A)   if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z,A)
15826 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z,A,B)
15827 #define OSTRACE6(X,Y,Z,A,B,C) \
15828     if(sqlite3_os_trace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
15829 #define OSTRACE7(X,Y,Z,A,B,C,D) \
15830     if(sqlite3_os_trace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
15831 #else
15832 #define OSTRACE1(X)
15833 #define OSTRACE2(X,Y)
15834 #define OSTRACE3(X,Y,Z)
15835 #define OSTRACE4(X,Y,Z,A)
15836 #define OSTRACE5(X,Y,Z,A,B)
15837 #define OSTRACE6(X,Y,Z,A,B,C)
15838 #define OSTRACE7(X,Y,Z,A,B,C,D)
15839 #endif
15840
15841 /*
15842 ** Macros for performance tracing.  Normally turned off.  Only works
15843 ** on i486 hardware.
15844 */
15845 #ifdef SQLITE_PERFORMANCE_TRACE
15846 __inline__ unsigned long long int hwtime(void){
15847   unsigned long long int x;
15848   __asm__("rdtsc\n\t"
15849           "mov %%edx, %%ecx\n\t"
15850           :"=A" (x));
15851   return x;
15852 }
15853 static unsigned long long int g_start;
15854 static unsigned int elapse;
15855 #define TIMER_START       g_start=hwtime()
15856 #define TIMER_END         elapse=hwtime()-g_start
15857 #define TIMER_ELAPSED     elapse
15858 #else
15859 #define TIMER_START
15860 #define TIMER_END
15861 #define TIMER_ELAPSED     0
15862 #endif
15863
15864 /*
15865 ** If we compile with the SQLITE_TEST macro set, then the following block
15866 ** of code will give us the ability to simulate a disk I/O error.  This
15867 ** is used for testing the I/O recovery logic.
15868 */
15869 #ifdef SQLITE_TEST
15870 SQLITE_API int sqlite3_io_error_hit = 0;
15871 SQLITE_API int sqlite3_io_error_pending = 0;
15872 SQLITE_API int sqlite3_io_error_persist = 0;
15873 SQLITE_API int sqlite3_diskfull_pending = 0;
15874 SQLITE_API int sqlite3_diskfull = 0;
15875 #define SimulateIOError(CODE)  \
15876   if( sqlite3_io_error_pending || sqlite3_io_error_hit ) \
15877      if( sqlite3_io_error_pending-- == 1 \
15878          || (sqlite3_io_error_persist && sqlite3_io_error_hit) ) \
15879                 { local_ioerr(); CODE; }
15880 static void local_ioerr(){
15881   IOTRACE(("IOERR\n"));
15882   sqlite3_io_error_hit = 1;
15883 }
15884 #define SimulateDiskfullError(CODE) \
15885    if( sqlite3_diskfull_pending ){ \
15886      if( sqlite3_diskfull_pending == 1 ){ \
15887        local_ioerr(); \
15888        sqlite3_diskfull = 1; \
15889        sqlite3_io_error_hit = 1; \
15890        CODE; \
15891      }else{ \
15892        sqlite3_diskfull_pending--; \
15893      } \
15894    }
15895 #else
15896 #define SimulateIOError(A)
15897 #define SimulateDiskfullError(A)
15898 #endif
15899
15900 /*
15901 ** When testing, keep a count of the number of open files.
15902 */
15903 #ifdef SQLITE_TEST
15904 SQLITE_API int sqlite3_open_file_count = 0;
15905 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
15906 #else
15907 #define OpenCounter(X)
15908 #endif
15909
15910 /************** End of os_common.h *******************************************/
15911 /************** Continuing where we left off in os_unix.c ********************/
15912
15913 /*
15914 ** Define various macros that are missing from some systems.
15915 */
15916 #ifndef O_LARGEFILE
15917 # define O_LARGEFILE 0
15918 #endif
15919 #ifdef SQLITE_DISABLE_LFS
15920 # undef O_LARGEFILE
15921 # define O_LARGEFILE 0
15922 #endif
15923 #ifndef O_NOFOLLOW
15924 # define O_NOFOLLOW 0
15925 #endif
15926 #ifndef O_BINARY
15927 # define O_BINARY 0
15928 #endif
15929
15930 /*
15931 ** The DJGPP compiler environment looks mostly like Unix, but it
15932 ** lacks the fcntl() system call.  So redefine fcntl() to be something
15933 ** that always succeeds.  This means that locking does not occur under
15934 ** DJGPP.  But it is DOS - what did you expect?
15935 */
15936 #ifdef __DJGPP__
15937 # define fcntl(A,B,C) 0
15938 #endif
15939
15940 /*
15941 ** The threadid macro resolves to the thread-id or to 0.  Used for
15942 ** testing and debugging only.
15943 */
15944 #if SQLITE_THREADSAFE
15945 #define threadid pthread_self()
15946 #else
15947 #define threadid 0
15948 #endif
15949
15950 /*
15951 ** Set or check the unixFile.tid field.  This field is set when an unixFile
15952 ** is first opened.  All subsequent uses of the unixFile verify that the
15953 ** same thread is operating on the unixFile.  Some operating systems do
15954 ** not allow locks to be overridden by other threads and that restriction
15955 ** means that sqlite3* database handles cannot be moved from one thread
15956 ** to another.  This logic makes sure a user does not try to do that
15957 ** by mistake.
15958 **
15959 ** Version 3.3.1 (2006-01-15):  unixFile can be moved from one thread to
15960 ** another as long as we are running on a system that supports threads
15961 ** overriding each others locks (which now the most common behavior)
15962 ** or if no locks are held.  But the unixFile.pLock field needs to be
15963 ** recomputed because its key includes the thread-id.  See the 
15964 ** transferOwnership() function below for additional information
15965 */
15966 #if SQLITE_THREADSAFE
15967 # define SET_THREADID(X)   (X)->tid = pthread_self()
15968 # define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
15969                             !pthread_equal((X)->tid, pthread_self()))
15970 #else
15971 # define SET_THREADID(X)
15972 # define CHECK_THREADID(X) 0
15973 #endif
15974
15975 /*
15976 ** Here is the dirt on POSIX advisory locks:  ANSI STD 1003.1 (1996)
15977 ** section 6.5.2.2 lines 483 through 490 specify that when a process
15978 ** sets or clears a lock, that operation overrides any prior locks set
15979 ** by the same process.  It does not explicitly say so, but this implies
15980 ** that it overrides locks set by the same process using a different
15981 ** file descriptor.  Consider this test case:
15982 **
15983 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
15984 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
15985 **
15986 ** Suppose ./file1 and ./file2 are really the same file (because
15987 ** one is a hard or symbolic link to the other) then if you set
15988 ** an exclusive lock on fd1, then try to get an exclusive lock
15989 ** on fd2, it works.  I would have expected the second lock to
15990 ** fail since there was already a lock on the file due to fd1.
15991 ** But not so.  Since both locks came from the same process, the
15992 ** second overrides the first, even though they were on different
15993 ** file descriptors opened on different file names.
15994 **
15995 ** Bummer.  If you ask me, this is broken.  Badly broken.  It means
15996 ** that we cannot use POSIX locks to synchronize file access among
15997 ** competing threads of the same process.  POSIX locks will work fine
15998 ** to synchronize access for threads in separate processes, but not
15999 ** threads within the same process.
16000 **
16001 ** To work around the problem, SQLite has to manage file locks internally
16002 ** on its own.  Whenever a new database is opened, we have to find the
16003 ** specific inode of the database file (the inode is determined by the
16004 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
16005 ** and check for locks already existing on that inode.  When locks are
16006 ** created or removed, we have to look at our own internal record of the
16007 ** locks to see if another thread has previously set a lock on that same
16008 ** inode.
16009 **
16010 ** The sqlite3_file structure for POSIX is no longer just an integer file
16011 ** descriptor.  It is now a structure that holds the integer file
16012 ** descriptor and a pointer to a structure that describes the internal
16013 ** locks on the corresponding inode.  There is one locking structure
16014 ** per inode, so if the same inode is opened twice, both unixFile structures
16015 ** point to the same locking structure.  The locking structure keeps
16016 ** a reference count (so we will know when to delete it) and a "cnt"
16017 ** field that tells us its internal lock status.  cnt==0 means the
16018 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
16019 ** cnt>0 means there are cnt shared locks on the file.
16020 **
16021 ** Any attempt to lock or unlock a file first checks the locking
16022 ** structure.  The fcntl() system call is only invoked to set a 
16023 ** POSIX lock if the internal lock structure transitions between
16024 ** a locked and an unlocked state.
16025 **
16026 ** 2004-Jan-11:
16027 ** More recent discoveries about POSIX advisory locks.  (The more
16028 ** I discover, the more I realize the a POSIX advisory locks are
16029 ** an abomination.)
16030 **
16031 ** If you close a file descriptor that points to a file that has locks,
16032 ** all locks on that file that are owned by the current process are
16033 ** released.  To work around this problem, each unixFile structure contains
16034 ** a pointer to an openCnt structure.  There is one openCnt structure
16035 ** per open inode, which means that multiple unixFile can point to a single
16036 ** openCnt.  When an attempt is made to close an unixFile, if there are
16037 ** other unixFile open on the same inode that are holding locks, the call
16038 ** to close() the file descriptor is deferred until all of the locks clear.
16039 ** The openCnt structure keeps a list of file descriptors that need to
16040 ** be closed and that list is walked (and cleared) when the last lock
16041 ** clears.
16042 **
16043 ** First, under Linux threads, because each thread has a separate
16044 ** process ID, lock operations in one thread do not override locks
16045 ** to the same file in other threads.  Linux threads behave like
16046 ** separate processes in this respect.  But, if you close a file
16047 ** descriptor in linux threads, all locks are cleared, even locks
16048 ** on other threads and even though the other threads have different
16049 ** process IDs.  Linux threads is inconsistent in this respect.
16050 ** (I'm beginning to think that linux threads is an abomination too.)
16051 ** The consequence of this all is that the hash table for the lockInfo
16052 ** structure has to include the process id as part of its key because
16053 ** locks in different threads are treated as distinct.  But the 
16054 ** openCnt structure should not include the process id in its
16055 ** key because close() clears lock on all threads, not just the current
16056 ** thread.  Were it not for this goofiness in linux threads, we could
16057 ** combine the lockInfo and openCnt structures into a single structure.
16058 **
16059 ** 2004-Jun-28:
16060 ** On some versions of linux, threads can override each others locks.
16061 ** On others not.  Sometimes you can change the behavior on the same
16062 ** system by setting the LD_ASSUME_KERNEL environment variable.  The
16063 ** POSIX standard is silent as to which behavior is correct, as far
16064 ** as I can tell, so other versions of unix might show the same
16065 ** inconsistency.  There is no little doubt in my mind that posix
16066 ** advisory locks and linux threads are profoundly broken.
16067 **
16068 ** To work around the inconsistencies, we have to test at runtime 
16069 ** whether or not threads can override each others locks.  This test
16070 ** is run once, the first time any lock is attempted.  A static 
16071 ** variable is set to record the results of this test for future
16072 ** use.
16073 */
16074
16075 /*
16076 ** An instance of the following structure serves as the key used
16077 ** to locate a particular lockInfo structure given its inode.
16078 **
16079 ** If threads cannot override each others locks, then we set the
16080 ** lockKey.tid field to the thread ID.  If threads can override
16081 ** each others locks then tid is always set to zero.  tid is omitted
16082 ** if we compile without threading support.
16083 */
16084 struct lockKey {
16085   dev_t dev;       /* Device number */
16086   ino_t ino;       /* Inode number */
16087 #if SQLITE_THREADSAFE
16088   pthread_t tid;   /* Thread ID or zero if threads can override each other */
16089 #endif
16090 };
16091
16092 /*
16093 ** An instance of the following structure is allocated for each open
16094 ** inode on each thread with a different process ID.  (Threads have
16095 ** different process IDs on linux, but not on most other unixes.)
16096 **
16097 ** A single inode can have multiple file descriptors, so each unixFile
16098 ** structure contains a pointer to an instance of this object and this
16099 ** object keeps a count of the number of unixFile pointing to it.
16100 */
16101 struct lockInfo {
16102   struct lockKey key;  /* The lookup key */
16103   int cnt;             /* Number of SHARED locks held */
16104   int locktype;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
16105   int nRef;            /* Number of pointers to this structure */
16106 };
16107
16108 /*
16109 ** An instance of the following structure serves as the key used
16110 ** to locate a particular openCnt structure given its inode.  This
16111 ** is the same as the lockKey except that the thread ID is omitted.
16112 */
16113 struct openKey {
16114   dev_t dev;   /* Device number */
16115   ino_t ino;   /* Inode number */
16116 };
16117
16118 /*
16119 ** An instance of the following structure is allocated for each open
16120 ** inode.  This structure keeps track of the number of locks on that
16121 ** inode.  If a close is attempted against an inode that is holding
16122 ** locks, the close is deferred until all locks clear by adding the
16123 ** file descriptor to be closed to the pending list.
16124 */
16125 struct openCnt {
16126   struct openKey key;   /* The lookup key */
16127   int nRef;             /* Number of pointers to this structure */
16128   int nLock;            /* Number of outstanding locks */
16129   int nPending;         /* Number of pending close() operations */
16130   int *aPending;        /* Malloced space holding fd's awaiting a close() */
16131 };
16132
16133 /* 
16134 ** These hash tables map inodes and file descriptors (really, lockKey and
16135 ** openKey structures) into lockInfo and openCnt structures.  Access to 
16136 ** these hash tables must be protected by a mutex.
16137 */
16138 static Hash lockHash = {SQLITE_HASH_BINARY, 0, 0, 0, 0, 0};
16139 static Hash openHash = {SQLITE_HASH_BINARY, 0, 0, 0, 0, 0};
16140
16141 #ifdef SQLITE_ENABLE_LOCKING_STYLE
16142 /*
16143 ** The locking styles are associated with the different file locking
16144 ** capabilities supported by different file systems.  
16145 **
16146 ** POSIX locking style fully supports shared and exclusive byte-range locks 
16147 ** ADP locking only supports exclusive byte-range locks
16148 ** FLOCK only supports a single file-global exclusive lock
16149 ** DOTLOCK isn't a true locking style, it refers to the use of a special
16150 **   file named the same as the database file with a '.lock' extension, this
16151 **   can be used on file systems that do not offer any reliable file locking
16152 ** NO locking means that no locking will be attempted, this is only used for
16153 **   read-only file systems currently
16154 ** UNSUPPORTED means that no locking will be attempted, this is only used for
16155 **   file systems that are known to be unsupported
16156 */
16157 typedef enum {
16158         posixLockingStyle = 0,       /* standard posix-advisory locks */
16159         afpLockingStyle,             /* use afp locks */
16160         flockLockingStyle,           /* use flock() */
16161         dotlockLockingStyle,         /* use <file>.lock files */
16162         noLockingStyle,              /* useful for read-only file system */
16163         unsupportedLockingStyle      /* indicates unsupported file system */
16164 } sqlite3LockingStyle;
16165 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
16166
16167 /*
16168 ** Helper functions to obtain and relinquish the global mutex.
16169 */
16170 static void enterMutex(){
16171   sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
16172 }
16173 static void leaveMutex(){
16174   sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
16175 }
16176
16177 #if SQLITE_THREADSAFE
16178 /*
16179 ** This variable records whether or not threads can override each others
16180 ** locks.
16181 **
16182 **    0:  No.  Threads cannot override each others locks.
16183 **    1:  Yes.  Threads can override each others locks.
16184 **   -1:  We don't know yet.
16185 **
16186 ** On some systems, we know at compile-time if threads can override each
16187 ** others locks.  On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
16188 ** will be set appropriately.  On other systems, we have to check at
16189 ** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
16190 ** undefined.
16191 **
16192 ** This variable normally has file scope only.  But during testing, we make
16193 ** it a global so that the test code can change its value in order to verify
16194 ** that the right stuff happens in either case.
16195 */
16196 #ifndef SQLITE_THREAD_OVERRIDE_LOCK
16197 # define SQLITE_THREAD_OVERRIDE_LOCK -1
16198 #endif
16199 #ifdef SQLITE_TEST
16200 int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
16201 #else
16202 static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
16203 #endif
16204
16205 /*
16206 ** This structure holds information passed into individual test
16207 ** threads by the testThreadLockingBehavior() routine.
16208 */
16209 struct threadTestData {
16210   int fd;                /* File to be locked */
16211   struct flock lock;     /* The locking operation */
16212   int result;            /* Result of the locking operation */
16213 };
16214
16215 #ifdef SQLITE_LOCK_TRACE
16216 /*
16217 ** Print out information about all locking operations.
16218 **
16219 ** This routine is used for troubleshooting locks on multithreaded
16220 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
16221 ** command-line option on the compiler.  This code is normally
16222 ** turned off.
16223 */
16224 static int lockTrace(int fd, int op, struct flock *p){
16225   char *zOpName, *zType;
16226   int s;
16227   int savedErrno;
16228   if( op==F_GETLK ){
16229     zOpName = "GETLK";
16230   }else if( op==F_SETLK ){
16231     zOpName = "SETLK";
16232   }else{
16233     s = fcntl(fd, op, p);
16234     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
16235     return s;
16236   }
16237   if( p->l_type==F_RDLCK ){
16238     zType = "RDLCK";
16239   }else if( p->l_type==F_WRLCK ){
16240     zType = "WRLCK";
16241   }else if( p->l_type==F_UNLCK ){
16242     zType = "UNLCK";
16243   }else{
16244     assert( 0 );
16245   }
16246   assert( p->l_whence==SEEK_SET );
16247   s = fcntl(fd, op, p);
16248   savedErrno = errno;
16249   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
16250      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
16251      (int)p->l_pid, s);
16252   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
16253     struct flock l2;
16254     l2 = *p;
16255     fcntl(fd, F_GETLK, &l2);
16256     if( l2.l_type==F_RDLCK ){
16257       zType = "RDLCK";
16258     }else if( l2.l_type==F_WRLCK ){
16259       zType = "WRLCK";
16260     }else if( l2.l_type==F_UNLCK ){
16261       zType = "UNLCK";
16262     }else{
16263       assert( 0 );
16264     }
16265     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
16266        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
16267   }
16268   errno = savedErrno;
16269   return s;
16270 }
16271 #define fcntl lockTrace
16272 #endif /* SQLITE_LOCK_TRACE */
16273
16274 /*
16275 ** The testThreadLockingBehavior() routine launches two separate
16276 ** threads on this routine.  This routine attempts to lock a file
16277 ** descriptor then returns.  The success or failure of that attempt
16278 ** allows the testThreadLockingBehavior() procedure to determine
16279 ** whether or not threads can override each others locks.
16280 */
16281 static void *threadLockingTest(void *pArg){
16282   struct threadTestData *pData = (struct threadTestData*)pArg;
16283   pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
16284   return pArg;
16285 }
16286
16287 /*
16288 ** This procedure attempts to determine whether or not threads
16289 ** can override each others locks then sets the 
16290 ** threadsOverrideEachOthersLocks variable appropriately.
16291 */
16292 static void testThreadLockingBehavior(int fd_orig){
16293   int fd;
16294   struct threadTestData d[2];
16295   pthread_t t[2];
16296
16297   fd = dup(fd_orig);
16298   if( fd<0 ) return;
16299   memset(d, 0, sizeof(d));
16300   d[0].fd = fd;
16301   d[0].lock.l_type = F_RDLCK;
16302   d[0].lock.l_len = 1;
16303   d[0].lock.l_start = 0;
16304   d[0].lock.l_whence = SEEK_SET;
16305   d[1] = d[0];
16306   d[1].lock.l_type = F_WRLCK;
16307   pthread_create(&t[0], 0, threadLockingTest, &d[0]);
16308   pthread_create(&t[1], 0, threadLockingTest, &d[1]);
16309   pthread_join(t[0], 0);
16310   pthread_join(t[1], 0);
16311   close(fd);
16312   threadsOverrideEachOthersLocks =  d[0].result==0 && d[1].result==0;
16313 }
16314 #endif /* SQLITE_THREADSAFE */
16315
16316 /*
16317 ** Release a lockInfo structure previously allocated by findLockInfo().
16318 */
16319 static void releaseLockInfo(struct lockInfo *pLock){
16320   if (pLock == NULL)
16321     return;
16322   pLock->nRef--;
16323   if( pLock->nRef==0 ){
16324     sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
16325     sqlite3_free(pLock);
16326   }
16327 }
16328
16329 /*
16330 ** Release a openCnt structure previously allocated by findLockInfo().
16331 */
16332 static void releaseOpenCnt(struct openCnt *pOpen){
16333   if (pOpen == NULL)
16334     return;
16335   pOpen->nRef--;
16336   if( pOpen->nRef==0 ){
16337     sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
16338     free(pOpen->aPending);
16339     sqlite3_free(pOpen);
16340   }
16341 }
16342
16343 #ifdef SQLITE_ENABLE_LOCKING_STYLE
16344 /*
16345 ** Tests a byte-range locking query to see if byte range locks are 
16346 ** supported, if not we fall back to dotlockLockingStyle.
16347 */
16348 static sqlite3LockingStyle sqlite3TestLockingStyle(
16349   const char *filePath, 
16350   int fd
16351 ){
16352   /* test byte-range lock using fcntl */
16353   struct flock lockInfo;
16354   
16355   lockInfo.l_len = 1;
16356   lockInfo.l_start = 0;
16357   lockInfo.l_whence = SEEK_SET;
16358   lockInfo.l_type = F_RDLCK;
16359   
16360   if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
16361     return posixLockingStyle;
16362   } 
16363   
16364   /* testing for flock can give false positives.  So if if the above test
16365   ** fails, then we fall back to using dot-lock style locking.
16366   */  
16367   return dotlockLockingStyle;
16368 }
16369
16370 /* 
16371 ** Examines the f_fstypename entry in the statfs structure as returned by 
16372 ** stat() for the file system hosting the database file, assigns the 
16373 ** appropriate locking style based on its value.  These values and 
16374 ** assignments are based on Darwin/OSX behavior and have not been tested on 
16375 ** other systems.
16376 */
16377 static sqlite3LockingStyle sqlite3DetectLockingStyle(
16378   const char *filePath, 
16379   int fd
16380 ){
16381
16382 #ifdef SQLITE_FIXED_LOCKING_STYLE
16383   return (sqlite3LockingStyle)SQLITE_FIXED_LOCKING_STYLE;
16384 #else
16385   struct statfs fsInfo;
16386
16387   if (statfs(filePath, &fsInfo) == -1)
16388     return sqlite3TestLockingStyle(filePath, fd);
16389   
16390   if (fsInfo.f_flags & MNT_RDONLY)
16391     return noLockingStyle;
16392   
16393   if( (!strcmp(fsInfo.f_fstypename, "hfs")) ||
16394     (!strcmp(fsInfo.f_fstypename, "ufs")) )
16395                 return posixLockingStyle;
16396   
16397   if(!strcmp(fsInfo.f_fstypename, "afpfs"))
16398     return afpLockingStyle;
16399   
16400   if(!strcmp(fsInfo.f_fstypename, "nfs")) 
16401     return sqlite3TestLockingStyle(filePath, fd);
16402   
16403   if(!strcmp(fsInfo.f_fstypename, "smbfs"))
16404     return flockLockingStyle;
16405   
16406   if(!strcmp(fsInfo.f_fstypename, "msdos"))
16407     return dotlockLockingStyle;
16408   
16409   if(!strcmp(fsInfo.f_fstypename, "webdav"))
16410     return unsupportedLockingStyle;
16411   
16412   return sqlite3TestLockingStyle(filePath, fd);  
16413 #endif /* SQLITE_FIXED_LOCKING_STYLE */
16414 }
16415
16416 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
16417
16418 /*
16419 ** Given a file descriptor, locate lockInfo and openCnt structures that
16420 ** describes that file descriptor.  Create new ones if necessary.  The
16421 ** return values might be uninitialized if an error occurs.
16422 **
16423 ** Return the number of errors.
16424 */
16425 static int findLockInfo(
16426   int fd,                      /* The file descriptor used in the key */
16427   struct lockInfo **ppLock,    /* Return the lockInfo structure here */
16428   struct openCnt **ppOpen      /* Return the openCnt structure here */
16429 ){
16430   int rc;
16431   struct lockKey key1;
16432   struct openKey key2;
16433   struct stat statbuf;
16434   struct lockInfo *pLock;
16435   struct openCnt *pOpen;
16436   rc = fstat(fd, &statbuf);
16437   if( rc!=0 ) return 1;
16438
16439   memset(&key1, 0, sizeof(key1));
16440   key1.dev = statbuf.st_dev;
16441   key1.ino = statbuf.st_ino;
16442 #if SQLITE_THREADSAFE
16443   if( threadsOverrideEachOthersLocks<0 ){
16444     testThreadLockingBehavior(fd);
16445   }
16446   key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
16447 #endif
16448   memset(&key2, 0, sizeof(key2));
16449   key2.dev = statbuf.st_dev;
16450   key2.ino = statbuf.st_ino;
16451   pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
16452   if( pLock==0 ){
16453     struct lockInfo *pOld;
16454     pLock = sqlite3_malloc( sizeof(*pLock) );
16455     if( pLock==0 ){
16456       rc = 1;
16457       goto exit_findlockinfo;
16458     }
16459     pLock->key = key1;
16460     pLock->nRef = 1;
16461     pLock->cnt = 0;
16462     pLock->locktype = 0;
16463     pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
16464     if( pOld!=0 ){
16465       assert( pOld==pLock );
16466       sqlite3_free(pLock);
16467       rc = 1;
16468       goto exit_findlockinfo;
16469     }
16470   }else{
16471     pLock->nRef++;
16472   }
16473   *ppLock = pLock;
16474   if( ppOpen!=0 ){
16475     pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
16476     if( pOpen==0 ){
16477       struct openCnt *pOld;
16478       pOpen = sqlite3_malloc( sizeof(*pOpen) );
16479       if( pOpen==0 ){
16480         releaseLockInfo(pLock);
16481         rc = 1;
16482         goto exit_findlockinfo;
16483       }
16484       pOpen->key = key2;
16485       pOpen->nRef = 1;
16486       pOpen->nLock = 0;
16487       pOpen->nPending = 0;
16488       pOpen->aPending = 0;
16489       pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
16490       if( pOld!=0 ){
16491         assert( pOld==pOpen );
16492         sqlite3_free(pOpen);
16493         releaseLockInfo(pLock);
16494         rc = 1;
16495         goto exit_findlockinfo;
16496       }
16497     }else{
16498       pOpen->nRef++;
16499     }
16500     *ppOpen = pOpen;
16501   }
16502
16503 exit_findlockinfo:
16504   return rc;
16505 }
16506
16507 #ifdef SQLITE_DEBUG
16508 /*
16509 ** Helper function for printing out trace information from debugging
16510 ** binaries. This returns the string represetation of the supplied
16511 ** integer lock-type.
16512 */
16513 static const char *locktypeName(int locktype){
16514   switch( locktype ){
16515   case NO_LOCK: return "NONE";
16516   case SHARED_LOCK: return "SHARED";
16517   case RESERVED_LOCK: return "RESERVED";
16518   case PENDING_LOCK: return "PENDING";
16519   case EXCLUSIVE_LOCK: return "EXCLUSIVE";
16520   }
16521   return "ERROR";
16522 }
16523 #endif
16524
16525 /*
16526 ** If we are currently in a different thread than the thread that the
16527 ** unixFile argument belongs to, then transfer ownership of the unixFile
16528 ** over to the current thread.
16529 **
16530 ** A unixFile is only owned by a thread on systems where one thread is
16531 ** unable to override locks created by a different thread.  RedHat9 is
16532 ** an example of such a system.
16533 **
16534 ** Ownership transfer is only allowed if the unixFile is currently unlocked.
16535 ** If the unixFile is locked and an ownership is wrong, then return
16536 ** SQLITE_MISUSE.  SQLITE_OK is returned if everything works.
16537 */
16538 #if SQLITE_THREADSAFE
16539 static int transferOwnership(unixFile *pFile){
16540   int rc;
16541   pthread_t hSelf;
16542   if( threadsOverrideEachOthersLocks ){
16543     /* Ownership transfers not needed on this system */
16544     return SQLITE_OK;
16545   }
16546   hSelf = pthread_self();
16547   if( pthread_equal(pFile->tid, hSelf) ){
16548     /* We are still in the same thread */
16549     OSTRACE1("No-transfer, same thread\n");
16550     return SQLITE_OK;
16551   }
16552   if( pFile->locktype!=NO_LOCK ){
16553     /* We cannot change ownership while we are holding a lock! */
16554     return SQLITE_MISUSE;
16555   }
16556   OSTRACE4("Transfer ownership of %d from %d to %d\n",
16557             pFile->h, pFile->tid, hSelf);
16558   pFile->tid = hSelf;
16559   if (pFile->pLock != NULL) {
16560     releaseLockInfo(pFile->pLock);
16561     rc = findLockInfo(pFile->h, &pFile->pLock, 0);
16562     OSTRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
16563            locktypeName(pFile->locktype),
16564            locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
16565     return rc;
16566   } else {
16567     return SQLITE_OK;
16568   }
16569 }
16570 #else
16571   /* On single-threaded builds, ownership transfer is a no-op */
16572 # define transferOwnership(X) SQLITE_OK
16573 #endif
16574
16575 /*
16576 ** Seek to the offset passed as the second argument, then read cnt 
16577 ** bytes into pBuf. Return the number of bytes actually read.
16578 **
16579 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
16580 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
16581 ** one system to another.  Since SQLite does not define USE_PREAD
16582 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
16583 ** See tickets #2741 and #2681.
16584 */
16585 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
16586   int got;
16587   i64 newOffset;
16588   TIMER_START;
16589 #if defined(USE_PREAD)
16590   got = pread(id->h, pBuf, cnt, offset);
16591   SimulateIOError( got = -1 );
16592 #elif defined(USE_PREAD64)
16593   got = pread64(id->h, pBuf, cnt, offset);
16594   SimulateIOError( got = -1 );
16595 #else
16596   newOffset = lseek(id->h, offset, SEEK_SET);
16597   SimulateIOError( newOffset-- );
16598   if( newOffset!=offset ){
16599     return -1;
16600   }
16601   got = read(id->h, pBuf, cnt);
16602 #endif
16603   TIMER_END;
16604   OSTRACE5("READ    %-3d %5d %7lld %d\n", id->h, got, offset, TIMER_ELAPSED);
16605   return got;
16606 }
16607
16608 /*
16609 ** Read data from a file into a buffer.  Return SQLITE_OK if all
16610 ** bytes were read successfully and SQLITE_IOERR if anything goes
16611 ** wrong.
16612 */
16613 static int unixRead(
16614   sqlite3_file *id, 
16615   void *pBuf, 
16616   int amt,
16617   sqlite3_int64 offset
16618 ){
16619   int got;
16620   assert( id );
16621   got = seekAndRead((unixFile*)id, offset, pBuf, amt);
16622   if( got==amt ){
16623     return SQLITE_OK;
16624   }else if( got<0 ){
16625     return SQLITE_IOERR_READ;
16626   }else{
16627     memset(&((char*)pBuf)[got], 0, amt-got);
16628     return SQLITE_IOERR_SHORT_READ;
16629   }
16630 }
16631
16632 /*
16633 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
16634 ** Return the number of bytes actually read.  Update the offset.
16635 */
16636 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
16637   int got;
16638   i64 newOffset;
16639   TIMER_START;
16640 #if defined(USE_PREAD)
16641   got = pwrite(id->h, pBuf, cnt, offset);
16642 #elif defined(USE_PREAD64)
16643   got = pwrite64(id->h, pBuf, cnt, offset);
16644 #else
16645   newOffset = lseek(id->h, offset, SEEK_SET);
16646   if( newOffset!=offset ){
16647     return -1;
16648   }
16649   got = write(id->h, pBuf, cnt);
16650 #endif
16651   TIMER_END;
16652   OSTRACE5("WRITE   %-3d %5d %7lld %d\n", id->h, got, offset, TIMER_ELAPSED);
16653   return got;
16654 }
16655
16656
16657 /*
16658 ** Write data from a buffer into a file.  Return SQLITE_OK on success
16659 ** or some other error code on failure.
16660 */
16661 static int unixWrite(
16662   sqlite3_file *id, 
16663   const void *pBuf, 
16664   int amt,
16665   sqlite3_int64 offset 
16666 ){
16667   int wrote = 0;
16668   assert( id );
16669   assert( amt>0 );
16670   while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
16671     amt -= wrote;
16672     offset += wrote;
16673     pBuf = &((char*)pBuf)[wrote];
16674   }
16675   SimulateIOError(( wrote=(-1), amt=1 ));
16676   SimulateDiskfullError(( wrote=0, amt=1 ));
16677   if( amt>0 ){
16678     if( wrote<0 ){
16679       return SQLITE_IOERR_WRITE;
16680     }else{
16681       return SQLITE_FULL;
16682     }
16683   }
16684   return SQLITE_OK;
16685 }
16686
16687 #ifdef SQLITE_TEST
16688 /*
16689 ** Count the number of fullsyncs and normal syncs.  This is used to test
16690 ** that syncs and fullsyncs are occuring at the right times.
16691 */
16692 SQLITE_API int sqlite3_sync_count = 0;
16693 SQLITE_API int sqlite3_fullsync_count = 0;
16694 #endif
16695
16696 /*
16697 ** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
16698 ** Otherwise use fsync() in its place.
16699 */
16700 #ifndef HAVE_FDATASYNC
16701 # define fdatasync fsync
16702 #endif
16703
16704 /*
16705 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
16706 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
16707 ** only available on Mac OS X.  But that could change.
16708 */
16709 #ifdef F_FULLFSYNC
16710 # define HAVE_FULLFSYNC 1
16711 #else
16712 # define HAVE_FULLFSYNC 0
16713 #endif
16714
16715
16716 /*
16717 ** The fsync() system call does not work as advertised on many
16718 ** unix systems.  The following procedure is an attempt to make
16719 ** it work better.
16720 **
16721 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
16722 ** for testing when we want to run through the test suite quickly.
16723 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
16724 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
16725 ** or power failure will likely corrupt the database file.
16726 */
16727 static int full_fsync(int fd, int fullSync, int dataOnly){
16728   int rc;
16729
16730   /* Record the number of times that we do a normal fsync() and 
16731   ** FULLSYNC.  This is used during testing to verify that this procedure
16732   ** gets called with the correct arguments.
16733   */
16734 #ifdef SQLITE_TEST
16735   if( fullSync ) sqlite3_fullsync_count++;
16736   sqlite3_sync_count++;
16737 #endif
16738
16739   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
16740   ** no-op
16741   */
16742 #ifdef SQLITE_NO_SYNC
16743   rc = SQLITE_OK;
16744 #else
16745
16746 #if HAVE_FULLFSYNC
16747   if( fullSync ){
16748     rc = fcntl(fd, F_FULLFSYNC, 0);
16749   }else{
16750     rc = 1;
16751   }
16752   /* If the FULLFSYNC failed, fall back to attempting an fsync().
16753    * It shouldn't be possible for fullfsync to fail on the local 
16754    * file system (on OSX), so failure indicates that FULLFSYNC
16755    * isn't supported for this file system. So, attempt an fsync 
16756    * and (for now) ignore the overhead of a superfluous fcntl call.  
16757    * It'd be better to detect fullfsync support once and avoid 
16758    * the fcntl call every time sync is called.
16759    */
16760   if( rc ) rc = fsync(fd);
16761
16762 #else 
16763   if( dataOnly ){
16764     rc = fdatasync(fd);
16765   }else{
16766     rc = fsync(fd);
16767   }
16768 #endif /* HAVE_FULLFSYNC */
16769 #endif /* defined(SQLITE_NO_SYNC) */
16770
16771   return rc;
16772 }
16773
16774 /*
16775 ** Make sure all writes to a particular file are committed to disk.
16776 **
16777 ** If dataOnly==0 then both the file itself and its metadata (file
16778 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
16779 ** file data is synced.
16780 **
16781 ** Under Unix, also make sure that the directory entry for the file
16782 ** has been created by fsync-ing the directory that contains the file.
16783 ** If we do not do this and we encounter a power failure, the directory
16784 ** entry for the journal might not exist after we reboot.  The next
16785 ** SQLite to access the file will not know that the journal exists (because
16786 ** the directory entry for the journal was never created) and the transaction
16787 ** will not roll back - possibly leading to database corruption.
16788 */
16789 static int unixSync(sqlite3_file *id, int flags){
16790   int rc;
16791   unixFile *pFile = (unixFile*)id;
16792
16793   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
16794   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
16795
16796   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
16797   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
16798       || (flags&0x0F)==SQLITE_SYNC_FULL
16799   );
16800
16801   assert( pFile );
16802   OSTRACE2("SYNC    %-3d\n", pFile->h);
16803   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
16804   SimulateIOError( rc=1 );
16805   if( rc ){
16806     return SQLITE_IOERR_FSYNC;
16807   }
16808   if( pFile->dirfd>=0 ){
16809     OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
16810             HAVE_FULLFSYNC, isFullsync);
16811 #ifndef SQLITE_DISABLE_DIRSYNC
16812     /* The directory sync is only attempted if full_fsync is
16813     ** turned off or unavailable.  If a full_fsync occurred above,
16814     ** then the directory sync is superfluous.
16815     */
16816     if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
16817        /*
16818        ** We have received multiple reports of fsync() returning
16819        ** errors when applied to directories on certain file systems.
16820        ** A failed directory sync is not a big deal.  So it seems
16821        ** better to ignore the error.  Ticket #1657
16822        */
16823        /* return SQLITE_IOERR; */
16824     }
16825 #endif
16826     close(pFile->dirfd);  /* Only need to sync once, so close the directory */
16827     pFile->dirfd = -1;    /* when we are done. */
16828   }
16829   return SQLITE_OK;
16830 }
16831
16832 /*
16833 ** Truncate an open file to a specified size
16834 */
16835 static int unixTruncate(sqlite3_file *id, i64 nByte){
16836   int rc;
16837   assert( id );
16838   rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
16839   SimulateIOError( rc=1 );
16840   if( rc ){
16841     return SQLITE_IOERR_TRUNCATE;
16842   }else{
16843     return SQLITE_OK;
16844   }
16845 }
16846
16847 /*
16848 ** Determine the current size of a file in bytes
16849 */
16850 static int unixFileSize(sqlite3_file *id, i64 *pSize){
16851   int rc;
16852   struct stat buf;
16853   assert( id );
16854   rc = fstat(((unixFile*)id)->h, &buf);
16855   SimulateIOError( rc=1 );
16856   if( rc!=0 ){
16857     return SQLITE_IOERR_FSTAT;
16858   }
16859   *pSize = buf.st_size;
16860   return SQLITE_OK;
16861 }
16862
16863 /*
16864 ** This routine checks if there is a RESERVED lock held on the specified
16865 ** file by this or any other process. If such a lock is held, return
16866 ** non-zero.  If the file is unlocked or holds only SHARED locks, then
16867 ** return zero.
16868 */
16869 static int unixCheckReservedLock(sqlite3_file *id){
16870   int r = 0;
16871   unixFile *pFile = (unixFile*)id;
16872
16873   assert( pFile );
16874   enterMutex(); /* Because pFile->pLock is shared across threads */
16875
16876   /* Check if a thread in this process holds such a lock */
16877   if( pFile->pLock->locktype>SHARED_LOCK ){
16878     r = 1;
16879   }
16880
16881   /* Otherwise see if some other process holds it.
16882   */
16883   if( !r ){
16884     struct flock lock;
16885     lock.l_whence = SEEK_SET;
16886     lock.l_start = RESERVED_BYTE;
16887     lock.l_len = 1;
16888     lock.l_type = F_WRLCK;
16889     fcntl(pFile->h, F_GETLK, &lock);
16890     if( lock.l_type!=F_UNLCK ){
16891       r = 1;
16892     }
16893   }
16894   
16895   leaveMutex();
16896   OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
16897
16898   return r;
16899 }
16900
16901 /*
16902 ** Lock the file with the lock specified by parameter locktype - one
16903 ** of the following:
16904 **
16905 **     (1) SHARED_LOCK
16906 **     (2) RESERVED_LOCK
16907 **     (3) PENDING_LOCK
16908 **     (4) EXCLUSIVE_LOCK
16909 **
16910 ** Sometimes when requesting one lock state, additional lock states
16911 ** are inserted in between.  The locking might fail on one of the later
16912 ** transitions leaving the lock state different from what it started but
16913 ** still short of its goal.  The following chart shows the allowed
16914 ** transitions and the inserted intermediate states:
16915 **
16916 **    UNLOCKED -> SHARED
16917 **    SHARED -> RESERVED
16918 **    SHARED -> (PENDING) -> EXCLUSIVE
16919 **    RESERVED -> (PENDING) -> EXCLUSIVE
16920 **    PENDING -> EXCLUSIVE
16921 **
16922 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
16923 ** routine to lower a locking level.
16924 */
16925 static int unixLock(sqlite3_file *id, int locktype){
16926   /* The following describes the implementation of the various locks and
16927   ** lock transitions in terms of the POSIX advisory shared and exclusive
16928   ** lock primitives (called read-locks and write-locks below, to avoid
16929   ** confusion with SQLite lock names). The algorithms are complicated
16930   ** slightly in order to be compatible with windows systems simultaneously
16931   ** accessing the same database file, in case that is ever required.
16932   **
16933   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
16934   ** byte', each single bytes at well known offsets, and the 'shared byte
16935   ** range', a range of 510 bytes at a well known offset.
16936   **
16937   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
16938   ** byte'.  If this is successful, a random byte from the 'shared byte
16939   ** range' is read-locked and the lock on the 'pending byte' released.
16940   **
16941   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
16942   ** A RESERVED lock is implemented by grabbing a write-lock on the
16943   ** 'reserved byte'. 
16944   **
16945   ** A process may only obtain a PENDING lock after it has obtained a
16946   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
16947   ** on the 'pending byte'. This ensures that no new SHARED locks can be
16948   ** obtained, but existing SHARED locks are allowed to persist. A process
16949   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
16950   ** This property is used by the algorithm for rolling back a journal file
16951   ** after a crash.
16952   **
16953   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
16954   ** implemented by obtaining a write-lock on the entire 'shared byte
16955   ** range'. Since all other locks require a read-lock on one of the bytes
16956   ** within this range, this ensures that no other locks are held on the
16957   ** database. 
16958   **
16959   ** The reason a single byte cannot be used instead of the 'shared byte
16960   ** range' is that some versions of windows do not support read-locks. By
16961   ** locking a random byte from a range, concurrent SHARED locks may exist
16962   ** even if the locking primitive used is always a write-lock.
16963   */
16964   int rc = SQLITE_OK;
16965   unixFile *pFile = (unixFile*)id;
16966   struct lockInfo *pLock = pFile->pLock;
16967   struct flock lock;
16968   int s;
16969
16970   assert( pFile );
16971   OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d\n", pFile->h,
16972       locktypeName(locktype), locktypeName(pFile->locktype),
16973       locktypeName(pLock->locktype), pLock->cnt , getpid());
16974
16975   /* If there is already a lock of this type or more restrictive on the
16976   ** unixFile, do nothing. Don't use the end_lock: exit path, as
16977   ** enterMutex() hasn't been called yet.
16978   */
16979   if( pFile->locktype>=locktype ){
16980     OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
16981             locktypeName(locktype));
16982     return SQLITE_OK;
16983   }
16984
16985   /* Make sure the locking sequence is correct
16986   */
16987   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
16988   assert( locktype!=PENDING_LOCK );
16989   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
16990
16991   /* This mutex is needed because pFile->pLock is shared across threads
16992   */
16993   enterMutex();
16994
16995   /* Make sure the current thread owns the pFile.
16996   */
16997   rc = transferOwnership(pFile);
16998   if( rc!=SQLITE_OK ){
16999     leaveMutex();
17000     return rc;
17001   }
17002   pLock = pFile->pLock;
17003
17004   /* If some thread using this PID has a lock via a different unixFile*
17005   ** handle that precludes the requested lock, return BUSY.
17006   */
17007   if( (pFile->locktype!=pLock->locktype && 
17008           (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
17009   ){
17010     rc = SQLITE_BUSY;
17011     goto end_lock;
17012   }
17013
17014   /* If a SHARED lock is requested, and some thread using this PID already
17015   ** has a SHARED or RESERVED lock, then increment reference counts and
17016   ** return SQLITE_OK.
17017   */
17018   if( locktype==SHARED_LOCK && 
17019       (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
17020     assert( locktype==SHARED_LOCK );
17021     assert( pFile->locktype==0 );
17022     assert( pLock->cnt>0 );
17023     pFile->locktype = SHARED_LOCK;
17024     pLock->cnt++;
17025     pFile->pOpen->nLock++;
17026     goto end_lock;
17027   }
17028
17029   lock.l_len = 1L;
17030
17031   lock.l_whence = SEEK_SET;
17032
17033   /* A PENDING lock is needed before acquiring a SHARED lock and before
17034   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
17035   ** be released.
17036   */
17037   if( locktype==SHARED_LOCK 
17038       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
17039   ){
17040     lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
17041     lock.l_start = PENDING_BYTE;
17042     s = fcntl(pFile->h, F_SETLK, &lock);
17043     if( s==(-1) ){
17044       rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
17045       goto end_lock;
17046     }
17047   }
17048
17049
17050   /* If control gets to this point, then actually go ahead and make
17051   ** operating system calls for the specified lock.
17052   */
17053   if( locktype==SHARED_LOCK ){
17054     assert( pLock->cnt==0 );
17055     assert( pLock->locktype==0 );
17056
17057     /* Now get the read-lock */
17058     lock.l_start = SHARED_FIRST;
17059     lock.l_len = SHARED_SIZE;
17060     s = fcntl(pFile->h, F_SETLK, &lock);
17061
17062     /* Drop the temporary PENDING lock */
17063     lock.l_start = PENDING_BYTE;
17064     lock.l_len = 1L;
17065     lock.l_type = F_UNLCK;
17066     if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
17067       rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
17068       goto end_lock;
17069     }
17070     if( s==(-1) ){
17071       rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
17072     }else{
17073       pFile->locktype = SHARED_LOCK;
17074       pFile->pOpen->nLock++;
17075       pLock->cnt = 1;
17076     }
17077   }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
17078     /* We are trying for an exclusive lock but another thread in this
17079     ** same process is still holding a shared lock. */
17080     rc = SQLITE_BUSY;
17081   }else{
17082     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
17083     ** assumed that there is a SHARED or greater lock on the file
17084     ** already.
17085     */
17086     assert( 0!=pFile->locktype );
17087     lock.l_type = F_WRLCK;
17088     switch( locktype ){
17089       case RESERVED_LOCK:
17090         lock.l_start = RESERVED_BYTE;
17091         break;
17092       case EXCLUSIVE_LOCK:
17093         lock.l_start = SHARED_FIRST;
17094         lock.l_len = SHARED_SIZE;
17095         break;
17096       default:
17097         assert(0);
17098     }
17099     s = fcntl(pFile->h, F_SETLK, &lock);
17100     if( s==(-1) ){
17101       rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
17102     }
17103   }
17104   
17105   if( rc==SQLITE_OK ){
17106     pFile->locktype = locktype;
17107     pLock->locktype = locktype;
17108   }else if( locktype==EXCLUSIVE_LOCK ){
17109     pFile->locktype = PENDING_LOCK;
17110     pLock->locktype = PENDING_LOCK;
17111   }
17112
17113 end_lock:
17114   leaveMutex();
17115   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
17116       rc==SQLITE_OK ? "ok" : "failed");
17117   return rc;
17118 }
17119
17120 /*
17121 ** Lower the locking level on file descriptor pFile to locktype.  locktype
17122 ** must be either NO_LOCK or SHARED_LOCK.
17123 **
17124 ** If the locking level of the file descriptor is already at or below
17125 ** the requested locking level, this routine is a no-op.
17126 */
17127 static int unixUnlock(sqlite3_file *id, int locktype){
17128   struct lockInfo *pLock;
17129   struct flock lock;
17130   int rc = SQLITE_OK;
17131   unixFile *pFile = (unixFile*)id;
17132
17133   assert( pFile );
17134   OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
17135       pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
17136
17137   assert( locktype<=SHARED_LOCK );
17138   if( pFile->locktype<=locktype ){
17139     return SQLITE_OK;
17140   }
17141   if( CHECK_THREADID(pFile) ){
17142     return SQLITE_MISUSE;
17143   }
17144   enterMutex();
17145   pLock = pFile->pLock;
17146   assert( pLock->cnt!=0 );
17147   if( pFile->locktype>SHARED_LOCK ){
17148     assert( pLock->locktype==pFile->locktype );
17149     if( locktype==SHARED_LOCK ){
17150       lock.l_type = F_RDLCK;
17151       lock.l_whence = SEEK_SET;
17152       lock.l_start = SHARED_FIRST;
17153       lock.l_len = SHARED_SIZE;
17154       if( fcntl(pFile->h, F_SETLK, &lock)==(-1) ){
17155         /* This should never happen */
17156         rc = SQLITE_IOERR_RDLOCK;
17157       }
17158     }
17159     lock.l_type = F_UNLCK;
17160     lock.l_whence = SEEK_SET;
17161     lock.l_start = PENDING_BYTE;
17162     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
17163     if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
17164       pLock->locktype = SHARED_LOCK;
17165     }else{
17166       rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
17167     }
17168   }
17169   if( locktype==NO_LOCK ){
17170     struct openCnt *pOpen;
17171
17172     /* Decrement the shared lock counter.  Release the lock using an
17173     ** OS call only when all threads in this same process have released
17174     ** the lock.
17175     */
17176     pLock->cnt--;
17177     if( pLock->cnt==0 ){
17178       lock.l_type = F_UNLCK;
17179       lock.l_whence = SEEK_SET;
17180       lock.l_start = lock.l_len = 0L;
17181       if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
17182         pLock->locktype = NO_LOCK;
17183       }else{
17184         rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
17185       }
17186     }
17187
17188     /* Decrement the count of locks against this same file.  When the
17189     ** count reaches zero, close any other file descriptors whose close
17190     ** was deferred because of outstanding locks.
17191     */
17192     pOpen = pFile->pOpen;
17193     pOpen->nLock--;
17194     assert( pOpen->nLock>=0 );
17195     if( pOpen->nLock==0 && pOpen->nPending>0 ){
17196       int i;
17197       for(i=0; i<pOpen->nPending; i++){
17198         close(pOpen->aPending[i]);
17199       }
17200       free(pOpen->aPending);
17201       pOpen->nPending = 0;
17202       pOpen->aPending = 0;
17203     }
17204   }
17205   leaveMutex();
17206   pFile->locktype = locktype;
17207   return rc;
17208 }
17209
17210 /*
17211 ** Close a file.
17212 */
17213 static int unixClose(sqlite3_file *id){
17214   unixFile *pFile = (unixFile *)id;
17215   if( !pFile ) return SQLITE_OK;
17216   unixUnlock(id, NO_LOCK);
17217   if( pFile->dirfd>=0 ) close(pFile->dirfd);
17218   pFile->dirfd = -1;
17219   enterMutex();
17220
17221   if( pFile->pOpen->nLock ){
17222     /* If there are outstanding locks, do not actually close the file just
17223     ** yet because that would clear those locks.  Instead, add the file
17224     ** descriptor to pOpen->aPending.  It will be automatically closed when
17225     ** the last lock is cleared.
17226     */
17227     int *aNew;
17228     struct openCnt *pOpen = pFile->pOpen;
17229     aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
17230     if( aNew==0 ){
17231       /* If a malloc fails, just leak the file descriptor */
17232     }else{
17233       pOpen->aPending = aNew;
17234       pOpen->aPending[pOpen->nPending] = pFile->h;
17235       pOpen->nPending++;
17236     }
17237   }else{
17238     /* There are no outstanding locks so we can close the file immediately */
17239     close(pFile->h);
17240   }
17241   releaseLockInfo(pFile->pLock);
17242   releaseOpenCnt(pFile->pOpen);
17243
17244   leaveMutex();
17245   OSTRACE2("CLOSE   %-3d\n", pFile->h);
17246   OpenCounter(-1);
17247   memset(pFile, 0, sizeof(unixFile));
17248   return SQLITE_OK;
17249 }
17250
17251
17252 #ifdef SQLITE_ENABLE_LOCKING_STYLE
17253 #pragma mark AFP Support
17254
17255 /*
17256  ** The afpLockingContext structure contains all afp lock specific state
17257  */
17258 typedef struct afpLockingContext afpLockingContext;
17259 struct afpLockingContext {
17260   unsigned long long sharedLockByte;
17261   char *filePath;
17262 };
17263
17264 struct ByteRangeLockPB2
17265 {
17266   unsigned long long offset;        /* offset to first byte to lock */
17267   unsigned long long length;        /* nbr of bytes to lock */
17268   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
17269   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
17270   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
17271   int fd;                           /* file desc to assoc this lock with */
17272 };
17273
17274 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
17275
17276 /* 
17277 ** Return 0 on success, 1 on failure.  To match the behavior of the 
17278 ** normal posix file locking (used in unixLock for example), we should 
17279 ** provide 'richer' return codes - specifically to differentiate between
17280 ** 'file busy' and 'file system error' results.
17281 */
17282 static int _AFPFSSetLock(
17283   const char *path, 
17284   int fd, 
17285   unsigned long long offset, 
17286   unsigned long long length, 
17287   int setLockFlag
17288 ){
17289   struct ByteRangeLockPB2       pb;
17290   int                     err;
17291   
17292   pb.unLockFlag = setLockFlag ? 0 : 1;
17293   pb.startEndFlag = 0;
17294   pb.offset = offset;
17295   pb.length = length; 
17296   pb.fd = fd;
17297   OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n", 
17298     (setLockFlag?"ON":"OFF"), fd, offset, length);
17299   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
17300   if ( err==-1 ) {
17301     OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, errno, 
17302       strerror(errno));
17303     return 1; /* error */
17304   } else {
17305     return 0;
17306   }
17307 }
17308
17309 /*
17310  ** This routine checks if there is a RESERVED lock held on the specified
17311  ** file by this or any other process. If such a lock is held, return
17312  ** non-zero.  If the file is unlocked or holds only SHARED locks, then
17313  ** return zero.
17314  */
17315 static int afpUnixCheckReservedLock(sqlite3_file *id){
17316   int r = 0;
17317   unixFile *pFile = (unixFile*)id;
17318   
17319   assert( pFile ); 
17320   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
17321   
17322   /* Check if a thread in this process holds such a lock */
17323   if( pFile->locktype>SHARED_LOCK ){
17324     r = 1;
17325   }
17326   
17327   /* Otherwise see if some other process holds it.
17328    */
17329   if ( !r ) {
17330     /* lock the byte */
17331     int failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);  
17332     if (failed) {
17333       /* if we failed to get the lock then someone else must have it */
17334       r = 1;
17335     } else {
17336       /* if we succeeded in taking the reserved lock, unlock it to restore
17337       ** the original state */
17338       _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0);
17339     }
17340   }
17341   OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
17342   
17343   return r;
17344 }
17345
17346 /* AFP-style locking following the behavior of unixLock, see the unixLock 
17347 ** function comments for details of lock management. */
17348 static int afpUnixLock(sqlite3_file *id, int locktype)
17349 {
17350   int rc = SQLITE_OK;
17351   unixFile *pFile = (unixFile*)id;
17352   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
17353   int gotPendingLock = 0;
17354   
17355   assert( pFile );
17356   OSTRACE5("LOCK    %d %s was %s pid=%d\n", pFile->h,
17357          locktypeName(locktype), locktypeName(pFile->locktype), getpid());  
17358   /* If there is already a lock of this type or more restrictive on the
17359     ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
17360     ** enterMutex() hasn't been called yet.
17361     */
17362   if( pFile->locktype>=locktype ){
17363     OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
17364            locktypeName(locktype));
17365     return SQLITE_OK;
17366   }
17367
17368   /* Make sure the locking sequence is correct
17369     */
17370   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
17371   assert( locktype!=PENDING_LOCK );
17372   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
17373   
17374   /* This mutex is needed because pFile->pLock is shared across threads
17375     */
17376   enterMutex();
17377
17378   /* Make sure the current thread owns the pFile.
17379     */
17380   rc = transferOwnership(pFile);
17381   if( rc!=SQLITE_OK ){
17382     leaveMutex();
17383     return rc;
17384   }
17385     
17386   /* A PENDING lock is needed before acquiring a SHARED lock and before
17387     ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
17388     ** be released.
17389     */
17390   if( locktype==SHARED_LOCK 
17391       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
17392       ){
17393     int failed = _AFPFSSetLock(context->filePath, pFile->h, 
17394       PENDING_BYTE, 1, 1);
17395     if (failed) {
17396       rc = SQLITE_BUSY;
17397       goto afp_end_lock;
17398     }
17399   }
17400   
17401   /* If control gets to this point, then actually go ahead and make
17402     ** operating system calls for the specified lock.
17403     */
17404   if( locktype==SHARED_LOCK ){
17405     int lk, failed;
17406     int tries = 0;
17407     
17408     /* Now get the read-lock */
17409     /* note that the quality of the randomness doesn't matter that much */
17410     lk = random(); 
17411     context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
17412     failed = _AFPFSSetLock(context->filePath, pFile->h, 
17413       SHARED_FIRST+context->sharedLockByte, 1, 1);
17414     
17415     /* Drop the temporary PENDING lock */
17416     if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)) {
17417       rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
17418       goto afp_end_lock;
17419     }
17420     
17421     if( failed ){
17422       rc = SQLITE_BUSY;
17423     } else {
17424       pFile->locktype = SHARED_LOCK;
17425     }
17426   }else{
17427     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
17428     ** assumed that there is a SHARED or greater lock on the file
17429     ** already.
17430     */
17431     int failed = 0;
17432     assert( 0!=pFile->locktype );
17433     if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
17434         /* Acquire a RESERVED lock */
17435         failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
17436     }
17437     if (!failed && locktype == EXCLUSIVE_LOCK) {
17438       /* Acquire an EXCLUSIVE lock */
17439         
17440       /* Remove the shared lock before trying the range.  we'll need to 
17441       ** reestablish the shared lock if we can't get the  afpUnixUnlock
17442       */
17443       if (!_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
17444                          context->sharedLockByte, 1, 0)) {
17445         /* now attemmpt to get the exclusive lock range */
17446         failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST, 
17447                                SHARED_SIZE, 1);
17448         if (failed && _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
17449                                     context->sharedLockByte, 1, 1)) {
17450           rc = SQLITE_IOERR_RDLOCK; /* this should never happen */
17451         }
17452       } else {
17453         /* */
17454         rc = SQLITE_IOERR_UNLOCK; /* this should never happen */
17455       }
17456     }
17457     if( failed && rc == SQLITE_OK){
17458       rc = SQLITE_BUSY;
17459     }
17460   }
17461   
17462   if( rc==SQLITE_OK ){
17463     pFile->locktype = locktype;
17464   }else if( locktype==EXCLUSIVE_LOCK ){
17465     pFile->locktype = PENDING_LOCK;
17466   }
17467   
17468 afp_end_lock:
17469     leaveMutex();
17470   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
17471          rc==SQLITE_OK ? "ok" : "failed");
17472   return rc;
17473 }
17474
17475 /*
17476  ** Lower the locking level on file descriptor pFile to locktype.  locktype
17477  ** must be either NO_LOCK or SHARED_LOCK.
17478  **
17479  ** If the locking level of the file descriptor is already at or below
17480  ** the requested locking level, this routine is a no-op.
17481  */
17482 static int afpUnixUnlock(sqlite3_file *id, int locktype) {
17483   struct flock lock;
17484   int rc = SQLITE_OK;
17485   unixFile *pFile = (unixFile*)id;
17486   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
17487
17488   assert( pFile );
17489   OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
17490          pFile->locktype, getpid());
17491   
17492   assert( locktype<=SHARED_LOCK );
17493   if( pFile->locktype<=locktype ){
17494     return SQLITE_OK;
17495   }
17496   if( CHECK_THREADID(pFile) ){
17497     return SQLITE_MISUSE;
17498   }
17499   enterMutex();
17500   if( pFile->locktype>SHARED_LOCK ){
17501     if( locktype==SHARED_LOCK ){
17502       int failed = 0;
17503
17504       /* unlock the exclusive range - then re-establish the shared lock */
17505       if (pFile->locktype==EXCLUSIVE_LOCK) {
17506         failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST, 
17507                                  SHARED_SIZE, 0);
17508         if (!failed) {
17509           /* successfully removed the exclusive lock */
17510           if (_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST+
17511                             context->sharedLockByte, 1, 1)) {
17512             /* failed to re-establish our shared lock */
17513             rc = SQLITE_IOERR_RDLOCK; /* This should never happen */
17514           }
17515         } else {
17516           /* This should never happen - failed to unlock the exclusive range */
17517           rc = SQLITE_IOERR_UNLOCK;
17518         } 
17519       }
17520     }
17521     if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
17522       if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)){
17523         /* failed to release the pending lock */
17524         rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
17525       }
17526     } 
17527     if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
17528       if (_AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0)) {
17529         /* failed to release the reserved lock */
17530         rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
17531       }
17532     } 
17533   }
17534   if( locktype==NO_LOCK ){
17535     int failed = _AFPFSSetLock(context->filePath, pFile->h, 
17536                                SHARED_FIRST + context->sharedLockByte, 1, 0);
17537     if (failed) {
17538       rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
17539     }
17540   }
17541   if (rc == SQLITE_OK)
17542     pFile->locktype = locktype;
17543   leaveMutex();
17544   return rc;
17545 }
17546
17547 /*
17548  ** Close a file & cleanup AFP specific locking context 
17549  */
17550 static int afpUnixClose(sqlite3_file *id) {
17551   unixFile *pFile = (unixFile*)pId;
17552
17553   if( !pFile ) return SQLITE_OK;
17554   afpUnixUnlock(*pId, NO_LOCK);
17555   /* free the AFP locking structure */
17556   if (pFile->lockingContext != NULL) {
17557     if (((afpLockingContext *)pFile->lockingContext)->filePath != NULL)
17558       sqlite3_free(((afpLockingContext*)pFile->lockingContext)->filePath);
17559     sqlite3_free(pFile->lockingContext);
17560   }
17561
17562   if( pFile->dirfd>=0 ) close(pFile->dirfd);
17563   pFile->dirfd = -1;
17564   close(pFile->h);
17565   OSTRACE2("CLOSE   %-3d\n", pFile->h);
17566   OpenCounter(-1);
17567   return SQLITE_OK;
17568 }
17569
17570
17571 #pragma mark flock() style locking
17572
17573 /*
17574  ** The flockLockingContext is not used
17575  */
17576 typedef void flockLockingContext;
17577
17578 static int flockUnixCheckReservedLock(sqlite3_file *id) {
17579   unixFile *pFile = (unixFile*)id;
17580   
17581   if (pFile->locktype == RESERVED_LOCK) {
17582     return 1; /* already have a reserved lock */
17583   } else {
17584     /* attempt to get the lock */
17585     int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
17586     if (!rc) {
17587       /* got the lock, unlock it */
17588       flock(pFile->h, LOCK_UN);
17589       return 0;  /* no one has it reserved */
17590     }
17591     return 1; /* someone else might have it reserved */
17592   }
17593 }
17594
17595 static int flockUnixLock(sqlite3_file *id, int locktype) {
17596   unixFile *pFile = (unixFile*)id;
17597   
17598   /* if we already have a lock, it is exclusive.  
17599   ** Just adjust level and punt on outta here. */
17600   if (pFile->locktype > NO_LOCK) {
17601     pFile->locktype = locktype;
17602     return SQLITE_OK;
17603   }
17604   
17605   /* grab an exclusive lock */
17606   int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
17607   if (rc) {
17608     /* didn't get, must be busy */
17609     return SQLITE_BUSY;
17610   } else {
17611     /* got it, set the type and return ok */
17612     pFile->locktype = locktype;
17613     return SQLITE_OK;
17614   }
17615 }
17616
17617 static int flockUnixUnlock(sqlite3_file *id, int locktype) {
17618   unixFile *pFile = (unixFile*)id;
17619   
17620   assert( locktype<=SHARED_LOCK );
17621   
17622   /* no-op if possible */
17623   if( pFile->locktype==locktype ){
17624     return SQLITE_OK;
17625   }
17626   
17627   /* shared can just be set because we always have an exclusive */
17628   if (locktype==SHARED_LOCK) {
17629     pFile->locktype = locktype;
17630     return SQLITE_OK;
17631   }
17632   
17633   /* no, really, unlock. */
17634   int rc = flock(pFile->h, LOCK_UN);
17635   if (rc)
17636     return SQLITE_IOERR_UNLOCK;
17637   else {
17638     pFile->locktype = NO_LOCK;
17639     return SQLITE_OK;
17640   }
17641 }
17642
17643 /*
17644  ** Close a file.
17645  */
17646 static int flockUnixClose(sqlite3_file *pId) {
17647   unixFile *pFile = (unixFile*)*pId;
17648   
17649   if( !pFile ) return SQLITE_OK;
17650   flockUnixUnlock(*pId, NO_LOCK);
17651   
17652   if( pFile->dirfd>=0 ) close(pFile->dirfd);
17653   pFile->dirfd = -1;
17654   enterMutex();
17655   
17656   close(pFile->h);  
17657   leaveMutex();
17658   OSTRACE2("CLOSE   %-3d\n", pFile->h);
17659   OpenCounter(-1);
17660   return SQLITE_OK;
17661 }
17662
17663 #pragma mark Old-School .lock file based locking
17664
17665 /*
17666  ** The dotlockLockingContext structure contains all dotlock (.lock) lock
17667  ** specific state
17668  */
17669 typedef struct dotlockLockingContext dotlockLockingContext;
17670 struct dotlockLockingContext {
17671   char *lockPath;
17672 };
17673
17674
17675 static int dotlockUnixCheckReservedLock(sqlite3_file *id) {
17676   unixFile *pFile = (unixFile*)id;
17677   dotlockLockingContext *context = 
17678     (dotlockLockingContext *) pFile->lockingContext;
17679   
17680   if (pFile->locktype == RESERVED_LOCK) {
17681     return 1; /* already have a reserved lock */
17682   } else {
17683     struct stat statBuf;
17684     if (lstat(context->lockPath,&statBuf) == 0)
17685       /* file exists, someone else has the lock */
17686       return 1;
17687     else
17688       /* file does not exist, we could have it if we want it */
17689       return 0;
17690   }
17691 }
17692
17693 static int dotlockUnixLock(sqlite3_file *id, int locktype) {
17694   unixFile *pFile = (unixFile*)id;
17695   dotlockLockingContext *context = 
17696     (dotlockLockingContext *) pFile->lockingContext;
17697   
17698   /* if we already have a lock, it is exclusive.  
17699   ** Just adjust level and punt on outta here. */
17700   if (pFile->locktype > NO_LOCK) {
17701     pFile->locktype = locktype;
17702     
17703     /* Always update the timestamp on the old file */
17704     utimes(context->lockPath,NULL);
17705     return SQLITE_OK;
17706   }
17707   
17708   /* check to see if lock file already exists */
17709   struct stat statBuf;
17710   if (lstat(context->lockPath,&statBuf) == 0){
17711     return SQLITE_BUSY; /* it does, busy */
17712   }
17713   
17714   /* grab an exclusive lock */
17715   int fd = open(context->lockPath,O_RDONLY|O_CREAT|O_EXCL,0600);
17716   if (fd < 0) {
17717     /* failed to open/create the file, someone else may have stolen the lock */
17718     return SQLITE_BUSY; 
17719   }
17720   close(fd);
17721   
17722   /* got it, set the type and return ok */
17723   pFile->locktype = locktype;
17724   return SQLITE_OK;
17725 }
17726
17727 static int dotlockUnixUnlock(sqlite3_file *id, int locktype) {
17728   unixFile *pFile = (unixFile*)id;
17729   dotlockLockingContext *context = 
17730     (dotlockLockingContext *) pFile->lockingContext;
17731   
17732   assert( locktype<=SHARED_LOCK );
17733   
17734   /* no-op if possible */
17735   if( pFile->locktype==locktype ){
17736     return SQLITE_OK;
17737   }
17738   
17739   /* shared can just be set because we always have an exclusive */
17740   if (locktype==SHARED_LOCK) {
17741     pFile->locktype = locktype;
17742     return SQLITE_OK;
17743   }
17744   
17745   /* no, really, unlock. */
17746   unlink(context->lockPath);
17747   pFile->locktype = NO_LOCK;
17748   return SQLITE_OK;
17749 }
17750
17751 /*
17752  ** Close a file.
17753  */
17754 static int dotlockUnixClose(sqlite3_file *id) {
17755   unixFile *pFile = (unixFile*)id;
17756   
17757   if( !pFile ) return SQLITE_OK;
17758   dotlockUnixUnlock(*pId, NO_LOCK);
17759   /* free the dotlock locking structure */
17760   if (pFile->lockingContext != NULL) {
17761     if (((dotlockLockingContext *)pFile->lockingContext)->lockPath != NULL)
17762       sqlite3_free( ( (dotlockLockingContext *)
17763         pFile->lockingContext)->lockPath);
17764     sqlite3_free(pFile->lockingContext);
17765   }
17766   
17767   if( pFile->dirfd>=0 ) close(pFile->dirfd);
17768   pFile->dirfd = -1;
17769   enterMutex();
17770   
17771   close(pFile->h);
17772   
17773   leaveMutex();
17774   OSTRACE2("CLOSE   %-3d\n", pFile->h);
17775   OpenCounter(-1);
17776   return SQLITE_OK;
17777 }
17778
17779
17780 #pragma mark No locking
17781
17782 /*
17783  ** The nolockLockingContext is void
17784  */
17785 typedef void nolockLockingContext;
17786
17787 static int nolockUnixCheckReservedLock(sqlite3_file *id) {
17788   return 0;
17789 }
17790
17791 static int nolockUnixLock(sqlite3_file *id, int locktype) {
17792   return SQLITE_OK;
17793 }
17794
17795 static int nolockUnixUnlock(sqlite3_file *id, int locktype) {
17796   return SQLITE_OK;
17797 }
17798
17799 /*
17800  ** Close a file.
17801  */
17802 static int nolockUnixClose(sqlite3_file *id) {
17803   unixFile *pFile = (unixFile*)id;
17804   
17805   if( !pFile ) return SQLITE_OK;
17806   if( pFile->dirfd>=0 ) close(pFile->dirfd);
17807   pFile->dirfd = -1;
17808   enterMutex();
17809   
17810   close(pFile->h);
17811   
17812   leaveMutex();
17813   OSTRACE2("CLOSE   %-3d\n", pFile->h);
17814   OpenCounter(-1);
17815   return SQLITE_OK;
17816 }
17817
17818 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
17819
17820
17821 /*
17822 ** Information and control of an open file handle.
17823 */
17824 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
17825   switch( op ){
17826     case SQLITE_FCNTL_LOCKSTATE: {
17827       *(int*)pArg = ((unixFile*)id)->locktype;
17828       return SQLITE_OK;
17829     }
17830   }
17831   return SQLITE_ERROR;
17832 }
17833
17834 /*
17835 ** Return the sector size in bytes of the underlying block device for
17836 ** the specified file. This is almost always 512 bytes, but may be
17837 ** larger for some devices.
17838 **
17839 ** SQLite code assumes this function cannot fail. It also assumes that
17840 ** if two files are created in the same file-system directory (i.e.
17841 ** a database and its journal file) that the sector size will be the
17842 ** same for both.
17843 */
17844 static int unixSectorSize(sqlite3_file *id){
17845   return SQLITE_DEFAULT_SECTOR_SIZE;
17846 }
17847
17848 /*
17849 ** Return the device characteristics for the file. This is always 0.
17850 */
17851 static int unixDeviceCharacteristics(sqlite3_file *id){
17852   return 0;
17853 }
17854
17855 /*
17856 ** This vector defines all the methods that can operate on an sqlite3_file
17857 ** for unix.
17858 */
17859 static const sqlite3_io_methods sqlite3UnixIoMethod = {
17860   1,                        /* iVersion */
17861   unixClose,
17862   unixRead,
17863   unixWrite,
17864   unixTruncate,
17865   unixSync,
17866   unixFileSize,
17867   unixLock,
17868   unixUnlock,
17869   unixCheckReservedLock,
17870   unixFileControl,
17871   unixSectorSize,
17872   unixDeviceCharacteristics
17873 };
17874
17875 #ifdef SQLITE_ENABLE_LOCKING_STYLE
17876 /*
17877 ** This vector defines all the methods that can operate on an sqlite3_file
17878 ** for unix with AFP style file locking.
17879 */
17880 static const sqlite3_io_methods sqlite3AFPLockingUnixIoMethod = {
17881   1,                        /* iVersion */
17882   unixClose,
17883   unixRead,
17884   unixWrite,
17885   unixTruncate,
17886   unixSync,
17887   unixFileSize,
17888   afpUnixLock,
17889   afpUnixUnlock,
17890   afpUnixCheckReservedLock,
17891   unixFileControl,
17892   unixSectorSize,
17893   unixDeviceCharacteristics
17894 };
17895
17896 /*
17897 ** This vector defines all the methods that can operate on an sqlite3_file
17898 ** for unix with flock() style file locking.
17899 */
17900 static const sqlite3_io_methods sqlite3FlockLockingUnixIoMethod = {
17901   1,                        /* iVersion */
17902   flockUnixClose,
17903   unixRead,
17904   unixWrite,
17905   unixTruncate,
17906   unixSync,
17907   unixFileSize,
17908   flockUnixLock,
17909   flockUnixUnlock,
17910   flockUnixCheckReservedLock,
17911   unixFileControl,
17912   unixSectorSize,
17913   unixDeviceCharacteristics
17914 };
17915
17916 /*
17917 ** This vector defines all the methods that can operate on an sqlite3_file
17918 ** for unix with dotlock style file locking.
17919 */
17920 static const sqlite3_io_methods sqlite3DotlockLockingUnixIoMethod = {
17921   1,                        /* iVersion */
17922   dotlockUnixClose,
17923   unixRead,
17924   unixWrite,
17925   unixTruncate,
17926   unixSync,
17927   unixFileSize,
17928   dotlockUnixLock,
17929   dotlockUnixUnlock,
17930   dotlockUnixCheckReservedLock,
17931   unixFileControl,
17932   unixSectorSize,
17933   unixDeviceCharacteristics
17934 };
17935
17936 /*
17937 ** This vector defines all the methods that can operate on an sqlite3_file
17938 ** for unix with dotlock style file locking.
17939 */
17940 static const sqlite3_io_methods sqlite3NolockLockingUnixIoMethod = {
17941   1,                        /* iVersion */
17942   nolockUnixClose,
17943   unixRead,
17944   unixWrite,
17945   unixTruncate,
17946   unixSync,
17947   unixFileSize,
17948   nolockUnixLock,
17949   nolockUnixUnlock,
17950   nolockUnixCheckReservedLock,
17951   unixFileControl,
17952   unixSectorSize,
17953   unixDeviceCharacteristics
17954 };
17955
17956 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
17957
17958 /*
17959 ** Allocate memory for a new unixFile and initialize that unixFile.
17960 ** Write a pointer to the new unixFile into *pId.
17961 ** If we run out of memory, close the file and return an error.
17962 */
17963 #ifdef SQLITE_ENABLE_LOCKING_STYLE
17964 /* 
17965 ** When locking extensions are enabled, the filepath and locking style 
17966 ** are needed to determine the unixFile pMethod to use for locking operations.
17967 ** The locking-style specific lockingContext data structure is created 
17968 ** and assigned here also.
17969 */
17970 static int fillInUnixFile(
17971   int h,                  /* Open file descriptor of file being opened */
17972   int dirfd,              /* Directory file descriptor */
17973   sqlite3_file *pId,      /* Write completed initialization here */
17974   const char *zFilename,  /* Name of the file being opened */
17975 ){
17976   sqlite3LockingStyle lockingStyle;
17977   unixFile *pNew = (unixFile *)pId;
17978   int rc;
17979
17980   memset(pNew, 0, sizeof(unixFile));
17981   lockingStyle = sqlite3DetectLockingStyle(zFilename, h);
17982   if ( lockingStyle == posixLockingStyle ) {
17983     enterMutex();
17984     rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
17985     leaveMutex();
17986     if( rc ){
17987       close(h);
17988       unlink(zFilename);
17989       return SQLITE_NOMEM;
17990     }
17991   } else {
17992     /*  pLock and pOpen are only used for posix advisory locking */
17993     pNew->pLock = NULL;
17994     pNew->pOpen = NULL;
17995   }
17996   pNew->dirfd = -1;
17997   pNew->h = h;
17998   SET_THREADID(pNew);
17999   pNew = sqlite3_malloc( sizeof(unixFile) );
18000   if( pNew==0 ){
18001     close(h);
18002     enterMutex();
18003     releaseLockInfo(pNew->pLock);
18004     releaseOpenCnt(pNew->pOpen);
18005     leaveMutex();
18006     return SQLITE_NOMEM;
18007   }else{
18008     switch(lockingStyle) {
18009       case afpLockingStyle: {
18010         /* afp locking uses the file path so it needs to be included in
18011         ** the afpLockingContext */
18012         int nFilename;
18013         pNew->pMethod = &sqlite3AFPLockingUnixIoMethod;
18014         pNew->lockingContext = 
18015           sqlite3_malloc(sizeof(afpLockingContext));
18016         nFilename = strlen(zFilename)+1;
18017         ((afpLockingContext *)pNew->lockingContext)->filePath = 
18018           sqlite3_malloc(nFilename);
18019         memcpy(((afpLockingContext *)pNew->lockingContext)->filePath, 
18020                zFilename, nFilename);
18021         srandomdev();
18022         break;
18023       }
18024       case flockLockingStyle:
18025         /* flock locking doesn't need additional lockingContext information */
18026         pNew->pMethod = &sqlite3FlockLockingUnixIoMethod;
18027         break;
18028       case dotlockLockingStyle: {
18029         /* dotlock locking uses the file path so it needs to be included in
18030          ** the dotlockLockingContext */
18031         int nFilename;
18032         pNew->pMethod = &sqlite3DotlockLockingUnixIoMethod;
18033         pNew->lockingContext = sqlite3_malloc(
18034           sizeof(dotlockLockingContext));
18035         nFilename = strlen(zFilename) + 6;
18036         ((dotlockLockingContext *)pNew->lockingContext)->lockPath = 
18037             sqlite3_malloc( nFilename );
18038         sqlite3_snprintf(nFilename, 
18039                 ((dotlockLockingContext *)pNew->lockingContext)->lockPath, 
18040                 "%s.lock", zFilename);
18041         break;
18042       }
18043       case posixLockingStyle:
18044         /* posix locking doesn't need additional lockingContext information */
18045         pNew->pMethod = &sqlite3UnixIoMethod;
18046         break;
18047       case noLockingStyle:
18048       case unsupportedLockingStyle:
18049       default: 
18050         pNew->pMethod = &sqlite3NolockLockingUnixIoMethod;
18051     }
18052     OpenCounter(+1);
18053     return SQLITE_OK;
18054   }
18055 }
18056 #else /* SQLITE_ENABLE_LOCKING_STYLE */
18057 static int fillInUnixFile(
18058   int h,                 /* Open file descriptor on file being opened */
18059   int dirfd,
18060   sqlite3_file *pId,     /* Write to the unixFile structure here */
18061   const char *zFilename  /* Name of the file being opened */
18062 ){
18063   unixFile *pNew = (unixFile *)pId;
18064   int rc;
18065
18066 #ifdef FD_CLOEXEC
18067   fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
18068 #endif
18069
18070   enterMutex();
18071   rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
18072   leaveMutex();
18073   if( rc ){
18074     if( dirfd>=0 ) close(dirfd);
18075     close(h);
18076     return SQLITE_NOMEM;
18077   }
18078
18079   OSTRACE3("OPEN    %-3d %s\n", h, zFilename);
18080   pNew->dirfd = -1;
18081   pNew->h = h;
18082   pNew->dirfd = dirfd;
18083   SET_THREADID(pNew);
18084
18085   pNew->pMethod = &sqlite3UnixIoMethod;
18086   OpenCounter(+1);
18087   return SQLITE_OK;
18088 }
18089 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
18090
18091 /*
18092 ** Open a file descriptor to the directory containing file zFilename.
18093 ** If successful, *pFd is set to the opened file descriptor and
18094 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
18095 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
18096 ** value.
18097 **
18098 ** If SQLITE_OK is returned, the caller is responsible for closing
18099 ** the file descriptor *pFd using close().
18100 */
18101 static int openDirectory(const char *zFilename, int *pFd){
18102   int ii;
18103   int fd = -1;
18104   char zDirname[MAX_PATHNAME+1];
18105
18106   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
18107   for(ii=strlen(zDirname); ii>=0 && zDirname[ii]!='/'; ii--);
18108   if( ii>0 ){
18109     zDirname[ii] = '\0';
18110     fd = open(zDirname, O_RDONLY|O_BINARY, 0);
18111     if( fd>=0 ){
18112 #ifdef FD_CLOEXEC
18113       fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
18114 #endif
18115       OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
18116     }
18117   }
18118   *pFd = fd;
18119   return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
18120 }
18121
18122 /*
18123 ** Open the file zPath.
18124 ** 
18125 ** Previously, the SQLite OS layer used three functions in place of this
18126 ** one:
18127 **
18128 **     sqlite3OsOpenReadWrite();
18129 **     sqlite3OsOpenReadOnly();
18130 **     sqlite3OsOpenExclusive();
18131 **
18132 ** These calls correspond to the following combinations of flags:
18133 **
18134 **     ReadWrite() ->     (READWRITE | CREATE)
18135 **     ReadOnly()  ->     (READONLY) 
18136 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
18137 **
18138 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
18139 ** true, the file was configured to be automatically deleted when the
18140 ** file handle closed. To achieve the same effect using this new 
18141 ** interface, add the DELETEONCLOSE flag to those specified above for 
18142 ** OpenExclusive().
18143 */
18144 static int unixOpen(
18145   sqlite3_vfs *pVfs, 
18146   const char *zPath, 
18147   sqlite3_file *pFile,
18148   int flags,
18149   int *pOutFlags
18150 ){
18151   int fd = 0;                    /* File descriptor returned by open() */
18152   int dirfd = -1;                /* Directory file descriptor */
18153   int oflags = 0;                /* Flags to pass to open() */
18154   int eType = flags&0xFFFFFF00;  /* Type of file to open */
18155
18156   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
18157   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
18158   int isCreate     = (flags & SQLITE_OPEN_CREATE);
18159   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
18160   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
18161
18162   /* If creating a master or main-file journal, this function will open
18163   ** a file-descriptor on the directory too. The first time unixSync()
18164   ** is called the directory file descriptor will be fsync()ed and close()d.
18165   */
18166   int isOpenDirectory = (isCreate && 
18167       (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
18168   );
18169
18170   /* Check the following statements are true: 
18171   **
18172   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
18173   **   (b) if CREATE is set, then READWRITE must also be set, and
18174   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
18175   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
18176   */
18177   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
18178   assert(isCreate==0 || isReadWrite);
18179   assert(isExclusive==0 || isCreate);
18180   assert(isDelete==0 || isCreate);
18181
18182
18183   /* The main DB, main journal, and master journal are never automatically
18184   ** deleted
18185   */
18186   assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
18187   assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
18188   assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
18189
18190   /* Assert that the upper layer has set one of the "file-type" flags. */
18191   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
18192        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
18193        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
18194        || eType==SQLITE_OPEN_TRANSIENT_DB
18195   );
18196
18197   if( isReadonly )  oflags |= O_RDONLY;
18198   if( isReadWrite ) oflags |= O_RDWR;
18199   if( isCreate )    oflags |= O_CREAT;
18200   if( isExclusive ) oflags |= (O_EXCL|O_NOFOLLOW);
18201   oflags |= (O_LARGEFILE|O_BINARY);
18202
18203   memset(pFile, 0, sizeof(unixFile));
18204   fd = open(zPath, oflags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
18205   if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
18206     /* Failed to open the file for read/write access. Try read-only. */
18207     flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
18208     flags |= SQLITE_OPEN_READONLY;
18209     return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
18210   }
18211   if( fd<0 ){
18212     return SQLITE_CANTOPEN;
18213   }
18214   if( isDelete ){
18215     unlink(zPath);
18216   }
18217   if( pOutFlags ){
18218     *pOutFlags = flags;
18219   }
18220
18221   assert(fd!=0);
18222   if( isOpenDirectory ){
18223     int rc = openDirectory(zPath, &dirfd);
18224     if( rc!=SQLITE_OK ){
18225       close(fd);
18226       return rc;
18227     }
18228   }
18229   return fillInUnixFile(fd, dirfd, pFile, zPath);
18230 }
18231
18232 /*
18233 ** Delete the file at zPath. If the dirSync argument is true, fsync()
18234 ** the directory after deleting the file.
18235 */
18236 static int unixDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
18237   int rc = SQLITE_OK;
18238   SimulateIOError(return SQLITE_IOERR_DELETE);
18239   unlink(zPath);
18240   if( dirSync ){
18241     int fd;
18242     rc = openDirectory(zPath, &fd);
18243     if( rc==SQLITE_OK ){
18244       if( fsync(fd) ){
18245         rc = SQLITE_IOERR_DIR_FSYNC;
18246       }
18247       close(fd);
18248     }
18249   }
18250   return rc;
18251 }
18252
18253 /*
18254 ** Test the existance of or access permissions of file zPath. The
18255 ** test performed depends on the value of flags:
18256 **
18257 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
18258 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
18259 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
18260 **
18261 ** Otherwise return 0.
18262 */
18263 static int unixAccess(sqlite3_vfs *pVfs, const char *zPath, int flags){
18264   int amode = 0;
18265   switch( flags ){
18266     case SQLITE_ACCESS_EXISTS:
18267       amode = F_OK;
18268       break;
18269     case SQLITE_ACCESS_READWRITE:
18270       amode = W_OK|R_OK;
18271       break;
18272     case SQLITE_ACCESS_READ:
18273       amode = R_OK;
18274       break;
18275
18276     default:
18277       assert(!"Invalid flags argument");
18278   }
18279   return (access(zPath, amode)==0);
18280 }
18281
18282 /*
18283 ** Create a temporary file name in zBuf.  zBuf must be allocated
18284 ** by the calling process and must be big enough to hold at least
18285 ** pVfs->mxPathname bytes.
18286 */
18287 static int unixGetTempname(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
18288   static const char *azDirs[] = {
18289      0,
18290      "/var/tmp",
18291      "/usr/tmp",
18292      "/tmp",
18293      ".",
18294   };
18295   static const unsigned char zChars[] =
18296     "abcdefghijklmnopqrstuvwxyz"
18297     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
18298     "0123456789";
18299   int i, j;
18300   struct stat buf;
18301   const char *zDir = ".";
18302
18303   /* It's odd to simulate an io-error here, but really this is just
18304   ** using the io-error infrastructure to test that SQLite handles this
18305   ** function failing. 
18306   */
18307   SimulateIOError( return SQLITE_ERROR );
18308
18309   azDirs[0] = sqlite3_temp_directory;
18310   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
18311     if( azDirs[i]==0 ) continue;
18312     if( stat(azDirs[i], &buf) ) continue;
18313     if( !S_ISDIR(buf.st_mode) ) continue;
18314     if( access(azDirs[i], 07) ) continue;
18315     zDir = azDirs[i];
18316     break;
18317   }
18318   if( strlen(zDir) - sizeof(SQLITE_TEMP_FILE_PREFIX) - 17 <=0 ){
18319     return SQLITE_ERROR;
18320   }
18321   do{
18322     assert( pVfs->mxPathname==MAX_PATHNAME );
18323     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
18324     j = strlen(zBuf);
18325     sqlite3Randomness(15, &zBuf[j]);
18326     for(i=0; i<15; i++, j++){
18327       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
18328     }
18329     zBuf[j] = 0;
18330   }while( access(zBuf,0)==0 );
18331   return SQLITE_OK;
18332 }
18333
18334
18335 /*
18336 ** Turn a relative pathname into a full pathname. The relative path
18337 ** is stored as a nul-terminated string in the buffer pointed to by
18338 ** zPath. 
18339 **
18340 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
18341 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
18342 ** this buffer before returning.
18343 */
18344 static int unixFullPathname(
18345   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
18346   const char *zPath,            /* Possibly relative input path */
18347   int nOut,                     /* Size of output buffer in bytes */
18348   char *zOut                    /* Output buffer */
18349 ){
18350
18351   /* It's odd to simulate an io-error here, but really this is just
18352   ** using the io-error infrastructure to test that SQLite handles this
18353   ** function failing. This function could fail if, for example, the
18354   ** current working directly has been unlinked.
18355   */
18356   SimulateIOError( return SQLITE_ERROR );
18357
18358   assert( pVfs->mxPathname==MAX_PATHNAME );
18359   zOut[nOut-1] = '\0';
18360   if( zPath[0]=='/' ){
18361     sqlite3_snprintf(nOut, zOut, "%s", zPath);
18362   }else{
18363     int nCwd;
18364     if( getcwd(zOut, nOut-1)==0 ){
18365       return SQLITE_CANTOPEN;
18366     }
18367     nCwd = strlen(zOut);
18368     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
18369   }
18370   return SQLITE_OK;
18371
18372 #if 0
18373   /*
18374   ** Remove "/./" path elements and convert "/A/./" path elements
18375   ** to just "/".
18376   */
18377   if( zFull ){
18378     int i, j;
18379     for(i=j=0; zFull[i]; i++){
18380       if( zFull[i]=='/' ){
18381         if( zFull[i+1]=='/' ) continue;
18382         if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
18383           i += 1;
18384           continue;
18385         }
18386         if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
18387           while( j>0 && zFull[j-1]!='/' ){ j--; }
18388           i += 3;
18389           continue;
18390         }
18391       }
18392       zFull[j++] = zFull[i];
18393     }
18394     zFull[j] = 0;
18395   }
18396 #endif
18397 }
18398
18399
18400 #ifndef SQLITE_OMIT_LOAD_EXTENSION
18401 /*
18402 ** Interfaces for opening a shared library, finding entry points
18403 ** within the shared library, and closing the shared library.
18404 */
18405 #include <dlfcn.h>
18406 static void *unixDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
18407   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
18408 }
18409
18410 /*
18411 ** SQLite calls this function immediately after a call to unixDlSym() or
18412 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
18413 ** message is available, it is written to zBufOut. If no error message
18414 ** is available, zBufOut is left unmodified and SQLite uses a default
18415 ** error message.
18416 */
18417 static void unixDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
18418   char *zErr;
18419   enterMutex();
18420   zErr = dlerror();
18421   if( zErr ){
18422     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
18423   }
18424   leaveMutex();
18425 }
18426 static void *unixDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
18427   return dlsym(pHandle, zSymbol);
18428 }
18429 static void unixDlClose(sqlite3_vfs *pVfs, void *pHandle){
18430   dlclose(pHandle);
18431 }
18432 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
18433   #define unixDlOpen  0
18434   #define unixDlError 0
18435   #define unixDlSym   0
18436   #define unixDlClose 0
18437 #endif
18438
18439 /*
18440 ** Write nBuf bytes of random data to the supplied buffer zBuf.
18441 */
18442 static int unixRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
18443
18444   assert(nBuf>=(sizeof(time_t)+sizeof(int)));
18445
18446   /* We have to initialize zBuf to prevent valgrind from reporting
18447   ** errors.  The reports issued by valgrind are incorrect - we would
18448   ** prefer that the randomness be increased by making use of the
18449   ** uninitialized space in zBuf - but valgrind errors tend to worry
18450   ** some users.  Rather than argue, it seems easier just to initialize
18451   ** the whole array and silence valgrind, even if that means less randomness
18452   ** in the random seed.
18453   **
18454   ** When testing, initializing zBuf[] to zero is all we do.  That means
18455   ** that we always use the same random number sequence.  This makes the
18456   ** tests repeatable.
18457   */
18458   memset(zBuf, 0, nBuf);
18459 #if !defined(SQLITE_TEST)
18460   {
18461     int pid, fd;
18462     fd = open("/dev/urandom", O_RDONLY);
18463     if( fd<0 ){
18464       time_t t;
18465       time(&t);
18466       memcpy(zBuf, &t, sizeof(t));
18467       pid = getpid();
18468       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
18469     }else{
18470       read(fd, zBuf, nBuf);
18471       close(fd);
18472     }
18473   }
18474 #endif
18475   return SQLITE_OK;
18476 }
18477
18478
18479 /*
18480 ** Sleep for a little while.  Return the amount of time slept.
18481 ** The argument is the number of microseconds we want to sleep.
18482 ** The return value is the number of microseconds of sleep actually
18483 ** requested from the underlying operating system, a number which
18484 ** might be greater than or equal to the argument, but not less
18485 ** than the argument.
18486 */
18487 static int unixSleep(sqlite3_vfs *pVfs, int microseconds){
18488 #if defined(HAVE_USLEEP) && HAVE_USLEEP
18489   usleep(microseconds);
18490   return microseconds;
18491 #else
18492   int seconds = (microseconds+999999)/1000000;
18493   sleep(seconds);
18494   return seconds*1000000;
18495 #endif
18496 }
18497
18498 /*
18499 ** The following variable, if set to a non-zero value, becomes the result
18500 ** returned from sqlite3OsCurrentTime().  This is used for testing.
18501 */
18502 #ifdef SQLITE_TEST
18503 SQLITE_API int sqlite3_current_time = 0;
18504 #endif
18505
18506 /*
18507 ** Find the current time (in Universal Coordinated Time).  Write the
18508 ** current time and date as a Julian Day number into *prNow and
18509 ** return 0.  Return 1 if the time and date cannot be found.
18510 */
18511 static int unixCurrentTime(sqlite3_vfs *pVfs, double *prNow){
18512 #ifdef NO_GETTOD
18513   time_t t;
18514   time(&t);
18515   *prNow = t/86400.0 + 2440587.5;
18516 #else
18517   struct timeval sNow;
18518   gettimeofday(&sNow, 0);
18519   *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
18520 #endif
18521 #ifdef SQLITE_TEST
18522   if( sqlite3_current_time ){
18523     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
18524   }
18525 #endif
18526   return 0;
18527 }
18528
18529 /*
18530 ** Return a pointer to the sqlite3DefaultVfs structure.   We use
18531 ** a function rather than give the structure global scope because
18532 ** some compilers (MSVC) do not allow forward declarations of
18533 ** initialized structures.
18534 */
18535 SQLITE_PRIVATE sqlite3_vfs *sqlite3OsDefaultVfs(void){
18536   static sqlite3_vfs unixVfs = {
18537     1,                  /* iVersion */
18538     sizeof(unixFile),   /* szOsFile */
18539     MAX_PATHNAME,       /* mxPathname */
18540     0,                  /* pNext */
18541     "unix",             /* zName */
18542     0,                  /* pAppData */
18543   
18544     unixOpen,           /* xOpen */
18545     unixDelete,         /* xDelete */
18546     unixAccess,         /* xAccess */
18547     unixGetTempname,    /* xGetTempName */
18548     unixFullPathname,   /* xFullPathname */
18549     unixDlOpen,         /* xDlOpen */
18550     unixDlError,        /* xDlError */
18551     unixDlSym,          /* xDlSym */
18552     unixDlClose,        /* xDlClose */
18553     unixRandomness,     /* xRandomness */
18554     unixSleep,          /* xSleep */
18555     unixCurrentTime     /* xCurrentTime */
18556   };
18557   
18558   return &unixVfs;
18559 }
18560  
18561 #endif /* OS_UNIX */
18562
18563 /************** End of os_unix.c *********************************************/
18564 /************** Begin file os_win.c ******************************************/
18565 /*
18566 ** 2004 May 22
18567 **
18568 ** The author disclaims copyright to this source code.  In place of
18569 ** a legal notice, here is a blessing:
18570 **
18571 **    May you do good and not evil.
18572 **    May you find forgiveness for yourself and forgive others.
18573 **    May you share freely, never taking more than you give.
18574 **
18575 ******************************************************************************
18576 **
18577 ** This file contains code that is specific to windows.
18578 */
18579 #if OS_WIN               /* This file is used for windows only */
18580
18581
18582 /*
18583 ** A Note About Memory Allocation:
18584 **
18585 ** This driver uses malloc()/free() directly rather than going through
18586 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
18587 ** are designed for use on embedded systems where memory is scarce and
18588 ** malloc failures happen frequently.  Win32 does not typically run on
18589 ** embedded systems, and when it does the developers normally have bigger
18590 ** problems to worry about than running out of memory.  So there is not
18591 ** a compelling need to use the wrappers.
18592 **
18593 ** But there is a good reason to not use the wrappers.  If we use the
18594 ** wrappers then we will get simulated malloc() failures within this
18595 ** driver.  And that causes all kinds of problems for our tests.  We
18596 ** could enhance SQLite to deal with simulated malloc failures within
18597 ** the OS driver, but the code to deal with those failure would not
18598 ** be exercised on Linux (which does not need to malloc() in the driver)
18599 ** and so we would have difficulty writing coverage tests for that
18600 ** code.  Better to leave the code out, we think.
18601 **
18602 ** The point of this discussion is as follows:  When creating a new
18603 ** OS layer for an embedded system, if you use this file as an example,
18604 ** avoid the use of malloc()/free().  Those routines work ok on windows
18605 ** desktops but not so well in embedded systems.
18606 */
18607
18608 #include <winbase.h>
18609
18610 #ifdef __CYGWIN__
18611 # include <sys/cygwin.h>
18612 #endif
18613
18614 /*
18615 ** Macros used to determine whether or not to use threads.
18616 */
18617 #if defined(THREADSAFE) && THREADSAFE
18618 # define SQLITE_W32_THREADS 1
18619 #endif
18620
18621 /*
18622 ** Include code that is common to all os_*.c files
18623 */
18624 /************** Include os_common.h in the middle of os_win.c ****************/
18625 /************** Begin file os_common.h ***************************************/
18626 /*
18627 ** 2004 May 22
18628 **
18629 ** The author disclaims copyright to this source code.  In place of
18630 ** a legal notice, here is a blessing:
18631 **
18632 **    May you do good and not evil.
18633 **    May you find forgiveness for yourself and forgive others.
18634 **    May you share freely, never taking more than you give.
18635 **
18636 ******************************************************************************
18637 **
18638 ** This file contains macros and a little bit of code that is common to
18639 ** all of the platform-specific files (os_*.c) and is #included into those
18640 ** files.
18641 **
18642 ** This file should be #included by the os_*.c files only.  It is not a
18643 ** general purpose header file.
18644 */
18645
18646 /*
18647 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
18648 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
18649 ** switch.  The following code should catch this problem at compile-time.
18650 */
18651 #ifdef MEMORY_DEBUG
18652 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
18653 #endif
18654
18655
18656 /*
18657  * When testing, this global variable stores the location of the
18658  * pending-byte in the database file.
18659  */
18660 #ifdef SQLITE_TEST
18661 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
18662 #endif
18663
18664 #ifdef SQLITE_DEBUG
18665 SQLITE_API int sqlite3_os_trace = 0;
18666 #define OSTRACE1(X)         if( sqlite3_os_trace ) sqlite3DebugPrintf(X)
18667 #define OSTRACE2(X,Y)       if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y)
18668 #define OSTRACE3(X,Y,Z)     if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z)
18669 #define OSTRACE4(X,Y,Z,A)   if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z,A)
18670 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z,A,B)
18671 #define OSTRACE6(X,Y,Z,A,B,C) \
18672     if(sqlite3_os_trace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
18673 #define OSTRACE7(X,Y,Z,A,B,C,D) \
18674     if(sqlite3_os_trace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
18675 #else
18676 #define OSTRACE1(X)
18677 #define OSTRACE2(X,Y)
18678 #define OSTRACE3(X,Y,Z)
18679 #define OSTRACE4(X,Y,Z,A)
18680 #define OSTRACE5(X,Y,Z,A,B)
18681 #define OSTRACE6(X,Y,Z,A,B,C)
18682 #define OSTRACE7(X,Y,Z,A,B,C,D)
18683 #endif
18684
18685 /*
18686 ** Macros for performance tracing.  Normally turned off.  Only works
18687 ** on i486 hardware.
18688 */
18689 #ifdef SQLITE_PERFORMANCE_TRACE
18690 __inline__ unsigned long long int hwtime(void){
18691   unsigned long long int x;
18692   __asm__("rdtsc\n\t"
18693           "mov %%edx, %%ecx\n\t"
18694           :"=A" (x));
18695   return x;
18696 }
18697 static unsigned long long int g_start;
18698 static unsigned int elapse;
18699 #define TIMER_START       g_start=hwtime()
18700 #define TIMER_END         elapse=hwtime()-g_start
18701 #define TIMER_ELAPSED     elapse
18702 #else
18703 #define TIMER_START
18704 #define TIMER_END
18705 #define TIMER_ELAPSED     0
18706 #endif
18707
18708 /*
18709 ** If we compile with the SQLITE_TEST macro set, then the following block
18710 ** of code will give us the ability to simulate a disk I/O error.  This
18711 ** is used for testing the I/O recovery logic.
18712 */
18713 #ifdef SQLITE_TEST
18714 SQLITE_API int sqlite3_io_error_hit = 0;
18715 SQLITE_API int sqlite3_io_error_pending = 0;
18716 SQLITE_API int sqlite3_io_error_persist = 0;
18717 SQLITE_API int sqlite3_diskfull_pending = 0;
18718 SQLITE_API int sqlite3_diskfull = 0;
18719 #define SimulateIOError(CODE)  \
18720   if( sqlite3_io_error_pending || sqlite3_io_error_hit ) \
18721      if( sqlite3_io_error_pending-- == 1 \
18722          || (sqlite3_io_error_persist && sqlite3_io_error_hit) ) \
18723                 { local_ioerr(); CODE; }
18724 static void local_ioerr(){
18725   IOTRACE(("IOERR\n"));
18726   sqlite3_io_error_hit = 1;
18727 }
18728 #define SimulateDiskfullError(CODE) \
18729    if( sqlite3_diskfull_pending ){ \
18730      if( sqlite3_diskfull_pending == 1 ){ \
18731        local_ioerr(); \
18732        sqlite3_diskfull = 1; \
18733        sqlite3_io_error_hit = 1; \
18734        CODE; \
18735      }else{ \
18736        sqlite3_diskfull_pending--; \
18737      } \
18738    }
18739 #else
18740 #define SimulateIOError(A)
18741 #define SimulateDiskfullError(A)
18742 #endif
18743
18744 /*
18745 ** When testing, keep a count of the number of open files.
18746 */
18747 #ifdef SQLITE_TEST
18748 SQLITE_API int sqlite3_open_file_count = 0;
18749 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
18750 #else
18751 #define OpenCounter(X)
18752 #endif
18753
18754 /************** End of os_common.h *******************************************/
18755 /************** Continuing where we left off in os_win.c *********************/
18756
18757 /*
18758 ** Determine if we are dealing with WindowsCE - which has a much
18759 ** reduced API.
18760 */
18761 #if defined(_WIN32_WCE)
18762 # define OS_WINCE 1
18763 # define AreFileApisANSI() 1
18764 #else
18765 # define OS_WINCE 0
18766 #endif
18767
18768 /*
18769 ** WinCE lacks native support for file locking so we have to fake it
18770 ** with some code of our own.
18771 */
18772 #if OS_WINCE
18773 typedef struct winceLock {
18774   int nReaders;       /* Number of reader locks obtained */
18775   BOOL bPending;      /* Indicates a pending lock has been obtained */
18776   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
18777   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
18778 } winceLock;
18779 #endif
18780
18781 /*
18782 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
18783 ** portability layer.
18784 */
18785 typedef struct winFile winFile;
18786 struct winFile {
18787   const sqlite3_io_methods *pMethod;/* Must be first */
18788   HANDLE h;               /* Handle for accessing the file */
18789   unsigned char locktype; /* Type of lock currently held on this file */
18790   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
18791 #if OS_WINCE
18792   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
18793   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
18794   HANDLE hShared;         /* Shared memory segment used for locking */
18795   winceLock local;        /* Locks obtained by this instance of winFile */
18796   winceLock *shared;      /* Global shared lock memory for the file  */
18797 #endif
18798 };
18799
18800
18801 /*
18802 ** The following variable is (normally) set once and never changes
18803 ** thereafter.  It records whether the operating system is Win95
18804 ** or WinNT.
18805 **
18806 ** 0:   Operating system unknown.
18807 ** 1:   Operating system is Win95.
18808 ** 2:   Operating system is WinNT.
18809 **
18810 ** In order to facilitate testing on a WinNT system, the test fixture
18811 ** can manually set this value to 1 to emulate Win98 behavior.
18812 */
18813 #ifdef SQLITE_TEST
18814 SQLITE_API int sqlite3_os_type = 0;
18815 #else
18816 static int sqlite3_os_type = 0;
18817 #endif
18818
18819 /*
18820 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
18821 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
18822 **
18823 ** Here is an interesting observation:  Win95, Win98, and WinME lack
18824 ** the LockFileEx() API.  But we can still statically link against that
18825 ** API as long as we don't call it win running Win95/98/ME.  A call to
18826 ** this routine is used to determine if the host is Win95/98/ME or
18827 ** WinNT/2K/XP so that we will know whether or not we can safely call
18828 ** the LockFileEx() API.
18829 */
18830 #if OS_WINCE
18831 # define isNT()  (1)
18832 #else
18833   static int isNT(void){
18834     if( sqlite3_os_type==0 ){
18835       OSVERSIONINFO sInfo;
18836       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
18837       GetVersionEx(&sInfo);
18838       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
18839     }
18840     return sqlite3_os_type==2;
18841   }
18842 #endif /* OS_WINCE */
18843
18844 /*
18845 ** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
18846 **
18847 ** Space to hold the returned string is obtained from malloc.
18848 */
18849 static WCHAR *utf8ToUnicode(const char *zFilename){
18850   int nChar;
18851   WCHAR *zWideFilename;
18852
18853   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
18854   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
18855   if( zWideFilename==0 ){
18856     return 0;
18857   }
18858   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
18859   if( nChar==0 ){
18860     free(zWideFilename);
18861     zWideFilename = 0;
18862   }
18863   return zWideFilename;
18864 }
18865
18866 /*
18867 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
18868 ** obtained from malloc().
18869 */
18870 static char *unicodeToUtf8(const WCHAR *zWideFilename){
18871   int nByte;
18872   char *zFilename;
18873
18874   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
18875   zFilename = malloc( nByte );
18876   if( zFilename==0 ){
18877     return 0;
18878   }
18879   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
18880                               0, 0);
18881   if( nByte == 0 ){
18882     free(zFilename);
18883     zFilename = 0;
18884   }
18885   return zFilename;
18886 }
18887
18888 /*
18889 ** Convert an ansi string to microsoft unicode, based on the
18890 ** current codepage settings for file apis.
18891 ** 
18892 ** Space to hold the returned string is obtained
18893 ** from malloc.
18894 */
18895 static WCHAR *mbcsToUnicode(const char *zFilename){
18896   int nByte;
18897   WCHAR *zMbcsFilename;
18898   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
18899
18900   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
18901   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
18902   if( zMbcsFilename==0 ){
18903     return 0;
18904   }
18905   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
18906   if( nByte==0 ){
18907     free(zMbcsFilename);
18908     zMbcsFilename = 0;
18909   }
18910   return zMbcsFilename;
18911 }
18912
18913 /*
18914 ** Convert microsoft unicode to multibyte character string, based on the
18915 ** user's Ansi codepage.
18916 **
18917 ** Space to hold the returned string is obtained from
18918 ** malloc().
18919 */
18920 static char *unicodeToMbcs(const WCHAR *zWideFilename){
18921   int nByte;
18922   char *zFilename;
18923   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
18924
18925   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
18926   zFilename = malloc( nByte );
18927   if( zFilename==0 ){
18928     return 0;
18929   }
18930   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
18931                               0, 0);
18932   if( nByte == 0 ){
18933     free(zFilename);
18934     zFilename = 0;
18935   }
18936   return zFilename;
18937 }
18938
18939 /*
18940 ** Convert multibyte character string to UTF-8.  Space to hold the
18941 ** returned string is obtained from malloc().
18942 */
18943 static char *mbcsToUtf8(const char *zFilename){
18944   char *zFilenameUtf8;
18945   WCHAR *zTmpWide;
18946
18947   zTmpWide = mbcsToUnicode(zFilename);
18948   if( zTmpWide==0 ){
18949     return 0;
18950   }
18951   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
18952   free(zTmpWide);
18953   return zFilenameUtf8;
18954 }
18955
18956 /*
18957 ** Convert UTF-8 to multibyte character string.  Space to hold the 
18958 ** returned string is obtained from malloc().
18959 */
18960 static char *utf8ToMbcs(const char *zFilename){
18961   char *zFilenameMbcs;
18962   WCHAR *zTmpWide;
18963
18964   zTmpWide = utf8ToUnicode(zFilename);
18965   if( zTmpWide==0 ){
18966     return 0;
18967   }
18968   zFilenameMbcs = unicodeToMbcs(zTmpWide);
18969   free(zTmpWide);
18970   return zFilenameMbcs;
18971 }
18972
18973 #if OS_WINCE
18974 /*************************************************************************
18975 ** This section contains code for WinCE only.
18976 */
18977 /*
18978 ** WindowsCE does not have a localtime() function.  So create a
18979 ** substitute.
18980 */
18981 struct tm *__cdecl localtime(const time_t *t)
18982 {
18983   static struct tm y;
18984   FILETIME uTm, lTm;
18985   SYSTEMTIME pTm;
18986   sqlite3_int64 t64;
18987   t64 = *t;
18988   t64 = (t64 + 11644473600)*10000000;
18989   uTm.dwLowDateTime = t64 & 0xFFFFFFFF;
18990   uTm.dwHighDateTime= t64 >> 32;
18991   FileTimeToLocalFileTime(&uTm,&lTm);
18992   FileTimeToSystemTime(&lTm,&pTm);
18993   y.tm_year = pTm.wYear - 1900;
18994   y.tm_mon = pTm.wMonth - 1;
18995   y.tm_wday = pTm.wDayOfWeek;
18996   y.tm_mday = pTm.wDay;
18997   y.tm_hour = pTm.wHour;
18998   y.tm_min = pTm.wMinute;
18999   y.tm_sec = pTm.wSecond;
19000   return &y;
19001 }
19002
19003 /* This will never be called, but defined to make the code compile */
19004 #define GetTempPathA(a,b)
19005
19006 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
19007 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
19008 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
19009
19010 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-offsetof(winFile,h)]
19011
19012 /*
19013 ** Acquire a lock on the handle h
19014 */
19015 static void winceMutexAcquire(HANDLE h){
19016    DWORD dwErr;
19017    do {
19018      dwErr = WaitForSingleObject(h, INFINITE);
19019    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
19020 }
19021 /*
19022 ** Release a lock acquired by winceMutexAcquire()
19023 */
19024 #define winceMutexRelease(h) ReleaseMutex(h)
19025
19026 /*
19027 ** Create the mutex and shared memory used for locking in the file
19028 ** descriptor pFile
19029 */
19030 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
19031   WCHAR *zTok;
19032   WCHAR *zName = utf8ToUnicode(zFilename);
19033   BOOL bInit = TRUE;
19034
19035   /* Initialize the local lockdata */
19036   ZeroMemory(&pFile->local, sizeof(pFile->local));
19037
19038   /* Replace the backslashes from the filename and lowercase it
19039   ** to derive a mutex name. */
19040   zTok = CharLowerW(zName);
19041   for (;*zTok;zTok++){
19042     if (*zTok == '\\') *zTok = '_';
19043   }
19044
19045   /* Create/open the named mutex */
19046   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
19047   if (!pFile->hMutex){
19048     free(zName);
19049     return FALSE;
19050   }
19051
19052   /* Acquire the mutex before continuing */
19053   winceMutexAcquire(pFile->hMutex);
19054   
19055   /* Since the names of named mutexes, semaphores, file mappings etc are 
19056   ** case-sensitive, take advantage of that by uppercasing the mutex name
19057   ** and using that as the shared filemapping name.
19058   */
19059   CharUpperW(zName);
19060   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
19061                                        PAGE_READWRITE, 0, sizeof(winceLock),
19062                                        zName);  
19063
19064   /* Set a flag that indicates we're the first to create the memory so it 
19065   ** must be zero-initialized */
19066   if (GetLastError() == ERROR_ALREADY_EXISTS){
19067     bInit = FALSE;
19068   }
19069
19070   free(zName);
19071
19072   /* If we succeeded in making the shared memory handle, map it. */
19073   if (pFile->hShared){
19074     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
19075              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
19076     /* If mapping failed, close the shared memory handle and erase it */
19077     if (!pFile->shared){
19078       CloseHandle(pFile->hShared);
19079       pFile->hShared = NULL;
19080     }
19081   }
19082
19083   /* If shared memory could not be created, then close the mutex and fail */
19084   if (pFile->hShared == NULL){
19085     winceMutexRelease(pFile->hMutex);
19086     CloseHandle(pFile->hMutex);
19087     pFile->hMutex = NULL;
19088     return FALSE;
19089   }
19090   
19091   /* Initialize the shared memory if we're supposed to */
19092   if (bInit) {
19093     ZeroMemory(pFile->shared, sizeof(winceLock));
19094   }
19095
19096   winceMutexRelease(pFile->hMutex);
19097   return TRUE;
19098 }
19099
19100 /*
19101 ** Destroy the part of winFile that deals with wince locks
19102 */
19103 static void winceDestroyLock(winFile *pFile){
19104   if (pFile->hMutex){
19105     /* Acquire the mutex */
19106     winceMutexAcquire(pFile->hMutex);
19107
19108     /* The following blocks should probably assert in debug mode, but they
19109        are to cleanup in case any locks remained open */
19110     if (pFile->local.nReaders){
19111       pFile->shared->nReaders --;
19112     }
19113     if (pFile->local.bReserved){
19114       pFile->shared->bReserved = FALSE;
19115     }
19116     if (pFile->local.bPending){
19117       pFile->shared->bPending = FALSE;
19118     }
19119     if (pFile->local.bExclusive){
19120       pFile->shared->bExclusive = FALSE;
19121     }
19122
19123     /* De-reference and close our copy of the shared memory handle */
19124     UnmapViewOfFile(pFile->shared);
19125     CloseHandle(pFile->hShared);
19126
19127     /* Done with the mutex */
19128     winceMutexRelease(pFile->hMutex);    
19129     CloseHandle(pFile->hMutex);
19130     pFile->hMutex = NULL;
19131   }
19132 }
19133
19134 /* 
19135 ** An implementation of the LockFile() API of windows for wince
19136 */
19137 static BOOL winceLockFile(
19138   HANDLE *phFile,
19139   DWORD dwFileOffsetLow,
19140   DWORD dwFileOffsetHigh,
19141   DWORD nNumberOfBytesToLockLow,
19142   DWORD nNumberOfBytesToLockHigh
19143 ){
19144   winFile *pFile = HANDLE_TO_WINFILE(phFile);
19145   BOOL bReturn = FALSE;
19146
19147   if (!pFile->hMutex) return TRUE;
19148   winceMutexAcquire(pFile->hMutex);
19149
19150   /* Wanting an exclusive lock? */
19151   if (dwFileOffsetLow == SHARED_FIRST
19152        && nNumberOfBytesToLockLow == SHARED_SIZE){
19153     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
19154        pFile->shared->bExclusive = TRUE;
19155        pFile->local.bExclusive = TRUE;
19156        bReturn = TRUE;
19157     }
19158   }
19159
19160   /* Want a read-only lock? */
19161   else if ((dwFileOffsetLow >= SHARED_FIRST &&
19162             dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE) &&
19163             nNumberOfBytesToLockLow == 1){
19164     if (pFile->shared->bExclusive == 0){
19165       pFile->local.nReaders ++;
19166       if (pFile->local.nReaders == 1){
19167         pFile->shared->nReaders ++;
19168       }
19169       bReturn = TRUE;
19170     }
19171   }
19172
19173   /* Want a pending lock? */
19174   else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToLockLow == 1){
19175     /* If no pending lock has been acquired, then acquire it */
19176     if (pFile->shared->bPending == 0) {
19177       pFile->shared->bPending = TRUE;
19178       pFile->local.bPending = TRUE;
19179       bReturn = TRUE;
19180     }
19181   }
19182   /* Want a reserved lock? */
19183   else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
19184     if (pFile->shared->bReserved == 0) {
19185       pFile->shared->bReserved = TRUE;
19186       pFile->local.bReserved = TRUE;
19187       bReturn = TRUE;
19188     }
19189   }
19190
19191   winceMutexRelease(pFile->hMutex);
19192   return bReturn;
19193 }
19194
19195 /*
19196 ** An implementation of the UnlockFile API of windows for wince
19197 */
19198 static BOOL winceUnlockFile(
19199   HANDLE *phFile,
19200   DWORD dwFileOffsetLow,
19201   DWORD dwFileOffsetHigh,
19202   DWORD nNumberOfBytesToUnlockLow,
19203   DWORD nNumberOfBytesToUnlockHigh
19204 ){
19205   winFile *pFile = HANDLE_TO_WINFILE(phFile);
19206   BOOL bReturn = FALSE;
19207
19208   if (!pFile->hMutex) return TRUE;
19209   winceMutexAcquire(pFile->hMutex);
19210
19211   /* Releasing a reader lock or an exclusive lock */
19212   if (dwFileOffsetLow >= SHARED_FIRST &&
19213        dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE){
19214     /* Did we have an exclusive lock? */
19215     if (pFile->local.bExclusive){
19216       pFile->local.bExclusive = FALSE;
19217       pFile->shared->bExclusive = FALSE;
19218       bReturn = TRUE;
19219     }
19220
19221     /* Did we just have a reader lock? */
19222     else if (pFile->local.nReaders){
19223       pFile->local.nReaders --;
19224       if (pFile->local.nReaders == 0)
19225       {
19226         pFile->shared->nReaders --;
19227       }
19228       bReturn = TRUE;
19229     }
19230   }
19231
19232   /* Releasing a pending lock */
19233   else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
19234     if (pFile->local.bPending){
19235       pFile->local.bPending = FALSE;
19236       pFile->shared->bPending = FALSE;
19237       bReturn = TRUE;
19238     }
19239   }
19240   /* Releasing a reserved lock */
19241   else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
19242     if (pFile->local.bReserved) {
19243       pFile->local.bReserved = FALSE;
19244       pFile->shared->bReserved = FALSE;
19245       bReturn = TRUE;
19246     }
19247   }
19248
19249   winceMutexRelease(pFile->hMutex);
19250   return bReturn;
19251 }
19252
19253 /*
19254 ** An implementation of the LockFileEx() API of windows for wince
19255 */
19256 static BOOL winceLockFileEx(
19257   HANDLE *phFile,
19258   DWORD dwFlags,
19259   DWORD dwReserved,
19260   DWORD nNumberOfBytesToLockLow,
19261   DWORD nNumberOfBytesToLockHigh,
19262   LPOVERLAPPED lpOverlapped
19263 ){
19264   /* If the caller wants a shared read lock, forward this call
19265   ** to winceLockFile */
19266   if (lpOverlapped->Offset == SHARED_FIRST &&
19267       dwFlags == 1 &&
19268       nNumberOfBytesToLockLow == SHARED_SIZE){
19269     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
19270   }
19271   return FALSE;
19272 }
19273 /*
19274 ** End of the special code for wince
19275 *****************************************************************************/
19276 #endif /* OS_WINCE */
19277
19278 /*****************************************************************************
19279 ** The next group of routines implement the I/O methods specified
19280 ** by the sqlite3_io_methods object.
19281 ******************************************************************************/
19282
19283 /*
19284 ** Close a file.
19285 **
19286 ** It is reported that an attempt to close a handle might sometimes
19287 ** fail.  This is a very unreasonable result, but windows is notorious
19288 ** for being unreasonable so I do not doubt that it might happen.  If
19289 ** the close fails, we pause for 100 milliseconds and try again.  As
19290 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
19291 ** giving up and returning an error.
19292 */
19293 #define MX_CLOSE_ATTEMPT 3
19294 static int winClose(sqlite3_file *id){
19295   int rc, cnt = 0;
19296   winFile *pFile = (winFile*)id;
19297   OSTRACE2("CLOSE %d\n", pFile->h);
19298   do{
19299     rc = CloseHandle(pFile->h);
19300   }while( rc==0 && cnt++ < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
19301 #if OS_WINCE
19302   winceDestroyLock(pFile);
19303   if( pFile->zDeleteOnClose ){
19304     DeleteFileW(pFile->zDeleteOnClose);
19305     free(pFile->zDeleteOnClose);
19306   }
19307 #endif
19308   OpenCounter(-1);
19309   return rc ? SQLITE_OK : SQLITE_IOERR;
19310 }
19311
19312 /*
19313 ** Some microsoft compilers lack this definition.
19314 */
19315 #ifndef INVALID_SET_FILE_POINTER
19316 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
19317 #endif
19318
19319 /*
19320 ** Read data from a file into a buffer.  Return SQLITE_OK if all
19321 ** bytes were read successfully and SQLITE_IOERR if anything goes
19322 ** wrong.
19323 */
19324 static int winRead(
19325   sqlite3_file *id,          /* File to read from */
19326   void *pBuf,                /* Write content into this buffer */
19327   int amt,                   /* Number of bytes to read */
19328   sqlite3_int64 offset       /* Begin reading at this offset */
19329 ){
19330   LONG upperBits = (offset>>32) & 0x7fffffff;
19331   LONG lowerBits = offset & 0xffffffff;
19332   DWORD rc;
19333   DWORD got;
19334   winFile *pFile = (winFile*)id;
19335   assert( id!=0 );
19336   SimulateIOError(return SQLITE_IOERR_READ);
19337   OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
19338   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
19339   if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
19340     return SQLITE_FULL;
19341   }
19342   if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
19343     return SQLITE_IOERR_READ;
19344   }
19345   if( got==(DWORD)amt ){
19346     return SQLITE_OK;
19347   }else{
19348     memset(&((char*)pBuf)[got], 0, amt-got);
19349     return SQLITE_IOERR_SHORT_READ;
19350   }
19351 }
19352
19353 /*
19354 ** Write data from a buffer into a file.  Return SQLITE_OK on success
19355 ** or some other error code on failure.
19356 */
19357 static int winWrite(
19358   sqlite3_file *id,         /* File to write into */
19359   const void *pBuf,         /* The bytes to be written */
19360   int amt,                  /* Number of bytes to write */
19361   sqlite3_int64 offset      /* Offset into the file to begin writing at */
19362 ){
19363   LONG upperBits = (offset>>32) & 0x7fffffff;
19364   LONG lowerBits = offset & 0xffffffff;
19365   DWORD rc;
19366   DWORD wrote;
19367   winFile *pFile = (winFile*)id;
19368   assert( id!=0 );
19369   SimulateIOError(return SQLITE_IOERR_WRITE);
19370   SimulateDiskfullError(return SQLITE_FULL);
19371   OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
19372   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
19373   if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
19374     return SQLITE_FULL;
19375   }
19376   assert( amt>0 );
19377   while(
19378      amt>0
19379      && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
19380      && wrote>0
19381   ){
19382     amt -= wrote;
19383     pBuf = &((char*)pBuf)[wrote];
19384   }
19385   if( !rc || amt>(int)wrote ){
19386     return SQLITE_FULL;
19387   }
19388   return SQLITE_OK;
19389 }
19390
19391 /*
19392 ** Truncate an open file to a specified size
19393 */
19394 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
19395   LONG upperBits = (nByte>>32) & 0x7fffffff;
19396   LONG lowerBits = nByte & 0xffffffff;
19397   winFile *pFile = (winFile*)id;
19398   OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
19399   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
19400   SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
19401   SetEndOfFile(pFile->h);
19402   return SQLITE_OK;
19403 }
19404
19405 #ifdef SQLITE_TEST
19406 /*
19407 ** Count the number of fullsyncs and normal syncs.  This is used to test
19408 ** that syncs and fullsyncs are occuring at the right times.
19409 */
19410 SQLITE_API int sqlite3_sync_count = 0;
19411 SQLITE_API int sqlite3_fullsync_count = 0;
19412 #endif
19413
19414 /*
19415 ** Make sure all writes to a particular file are committed to disk.
19416 */
19417 static int winSync(sqlite3_file *id, int flags){
19418   winFile *pFile = (winFile*)id;
19419   OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
19420 #ifdef SQLITE_TEST
19421   if( flags & SQLITE_SYNC_FULL ){
19422     sqlite3_fullsync_count++;
19423   }
19424   sqlite3_sync_count++;
19425 #endif
19426   if( FlushFileBuffers(pFile->h) ){
19427     return SQLITE_OK;
19428   }else{
19429     return SQLITE_IOERR;
19430   }
19431 }
19432
19433 /*
19434 ** Determine the current size of a file in bytes
19435 */
19436 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
19437   winFile *pFile = (winFile*)id;
19438   DWORD upperBits, lowerBits;
19439   SimulateIOError(return SQLITE_IOERR_FSTAT);
19440   lowerBits = GetFileSize(pFile->h, &upperBits);
19441   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
19442   return SQLITE_OK;
19443 }
19444
19445 /*
19446 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
19447 */
19448 #ifndef LOCKFILE_FAIL_IMMEDIATELY
19449 # define LOCKFILE_FAIL_IMMEDIATELY 1
19450 #endif
19451
19452 /*
19453 ** Acquire a reader lock.
19454 ** Different API routines are called depending on whether or not this
19455 ** is Win95 or WinNT.
19456 */
19457 static int getReadLock(winFile *pFile){
19458   int res;
19459   if( isNT() ){
19460     OVERLAPPED ovlp;
19461     ovlp.Offset = SHARED_FIRST;
19462     ovlp.OffsetHigh = 0;
19463     ovlp.hEvent = 0;
19464     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
19465                      0, SHARED_SIZE, 0, &ovlp);
19466   }else{
19467     int lk;
19468     sqlite3Randomness(sizeof(lk), &lk);
19469     pFile->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
19470     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
19471   }
19472   return res;
19473 }
19474
19475 /*
19476 ** Undo a readlock
19477 */
19478 static int unlockReadLock(winFile *pFile){
19479   int res;
19480   if( isNT() ){
19481     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
19482   }else{
19483     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
19484   }
19485   return res;
19486 }
19487
19488 /*
19489 ** Lock the file with the lock specified by parameter locktype - one
19490 ** of the following:
19491 **
19492 **     (1) SHARED_LOCK
19493 **     (2) RESERVED_LOCK
19494 **     (3) PENDING_LOCK
19495 **     (4) EXCLUSIVE_LOCK
19496 **
19497 ** Sometimes when requesting one lock state, additional lock states
19498 ** are inserted in between.  The locking might fail on one of the later
19499 ** transitions leaving the lock state different from what it started but
19500 ** still short of its goal.  The following chart shows the allowed
19501 ** transitions and the inserted intermediate states:
19502 **
19503 **    UNLOCKED -> SHARED
19504 **    SHARED -> RESERVED
19505 **    SHARED -> (PENDING) -> EXCLUSIVE
19506 **    RESERVED -> (PENDING) -> EXCLUSIVE
19507 **    PENDING -> EXCLUSIVE
19508 **
19509 ** This routine will only increase a lock.  The winUnlock() routine
19510 ** erases all locks at once and returns us immediately to locking level 0.
19511 ** It is not possible to lower the locking level one step at a time.  You
19512 ** must go straight to locking level 0.
19513 */
19514 static int winLock(sqlite3_file *id, int locktype){
19515   int rc = SQLITE_OK;    /* Return code from subroutines */
19516   int res = 1;           /* Result of a windows lock call */
19517   int newLocktype;       /* Set pFile->locktype to this value before exiting */
19518   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
19519   winFile *pFile = (winFile*)id;
19520
19521   assert( pFile!=0 );
19522   OSTRACE5("LOCK %d %d was %d(%d)\n",
19523           pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
19524
19525   /* If there is already a lock of this type or more restrictive on the
19526   ** OsFile, do nothing. Don't use the end_lock: exit path, as
19527   ** sqlite3OsEnterMutex() hasn't been called yet.
19528   */
19529   if( pFile->locktype>=locktype ){
19530     return SQLITE_OK;
19531   }
19532
19533   /* Make sure the locking sequence is correct
19534   */
19535   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
19536   assert( locktype!=PENDING_LOCK );
19537   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
19538
19539   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
19540   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
19541   ** the PENDING_LOCK byte is temporary.
19542   */
19543   newLocktype = pFile->locktype;
19544   if( pFile->locktype==NO_LOCK
19545    || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
19546   ){
19547     int cnt = 3;
19548     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
19549       /* Try 3 times to get the pending lock.  The pending lock might be
19550       ** held by another reader process who will release it momentarily.
19551       */
19552       OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
19553       Sleep(1);
19554     }
19555     gotPendingLock = res;
19556   }
19557
19558   /* Acquire a shared lock
19559   */
19560   if( locktype==SHARED_LOCK && res ){
19561     assert( pFile->locktype==NO_LOCK );
19562     res = getReadLock(pFile);
19563     if( res ){
19564       newLocktype = SHARED_LOCK;
19565     }
19566   }
19567
19568   /* Acquire a RESERVED lock
19569   */
19570   if( locktype==RESERVED_LOCK && res ){
19571     assert( pFile->locktype==SHARED_LOCK );
19572     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
19573     if( res ){
19574       newLocktype = RESERVED_LOCK;
19575     }
19576   }
19577
19578   /* Acquire a PENDING lock
19579   */
19580   if( locktype==EXCLUSIVE_LOCK && res ){
19581     newLocktype = PENDING_LOCK;
19582     gotPendingLock = 0;
19583   }
19584
19585   /* Acquire an EXCLUSIVE lock
19586   */
19587   if( locktype==EXCLUSIVE_LOCK && res ){
19588     assert( pFile->locktype>=SHARED_LOCK );
19589     res = unlockReadLock(pFile);
19590     OSTRACE2("unreadlock = %d\n", res);
19591     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
19592     if( res ){
19593       newLocktype = EXCLUSIVE_LOCK;
19594     }else{
19595       OSTRACE2("error-code = %d\n", GetLastError());
19596       getReadLock(pFile);
19597     }
19598   }
19599
19600   /* If we are holding a PENDING lock that ought to be released, then
19601   ** release it now.
19602   */
19603   if( gotPendingLock && locktype==SHARED_LOCK ){
19604     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
19605   }
19606
19607   /* Update the state of the lock has held in the file descriptor then
19608   ** return the appropriate result code.
19609   */
19610   if( res ){
19611     rc = SQLITE_OK;
19612   }else{
19613     OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
19614            locktype, newLocktype);
19615     rc = SQLITE_BUSY;
19616   }
19617   pFile->locktype = newLocktype;
19618   return rc;
19619 }
19620
19621 /*
19622 ** This routine checks if there is a RESERVED lock held on the specified
19623 ** file by this or any other process. If such a lock is held, return
19624 ** non-zero, otherwise zero.
19625 */
19626 static int winCheckReservedLock(sqlite3_file *id){
19627   int rc;
19628   winFile *pFile = (winFile*)id;
19629   assert( pFile!=0 );
19630   if( pFile->locktype>=RESERVED_LOCK ){
19631     rc = 1;
19632     OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
19633   }else{
19634     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
19635     if( rc ){
19636       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
19637     }
19638     rc = !rc;
19639     OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
19640   }
19641   return rc;
19642 }
19643
19644 /*
19645 ** Lower the locking level on file descriptor id to locktype.  locktype
19646 ** must be either NO_LOCK or SHARED_LOCK.
19647 **
19648 ** If the locking level of the file descriptor is already at or below
19649 ** the requested locking level, this routine is a no-op.
19650 **
19651 ** It is not possible for this routine to fail if the second argument
19652 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
19653 ** might return SQLITE_IOERR;
19654 */
19655 static int winUnlock(sqlite3_file *id, int locktype){
19656   int type;
19657   winFile *pFile = (winFile*)id;
19658   int rc = SQLITE_OK;
19659   assert( pFile!=0 );
19660   assert( locktype<=SHARED_LOCK );
19661   OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
19662           pFile->locktype, pFile->sharedLockByte);
19663   type = pFile->locktype;
19664   if( type>=EXCLUSIVE_LOCK ){
19665     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
19666     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
19667       /* This should never happen.  We should always be able to
19668       ** reacquire the read lock */
19669       rc = SQLITE_IOERR_UNLOCK;
19670     }
19671   }
19672   if( type>=RESERVED_LOCK ){
19673     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
19674   }
19675   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
19676     unlockReadLock(pFile);
19677   }
19678   if( type>=PENDING_LOCK ){
19679     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
19680   }
19681   pFile->locktype = locktype;
19682   return rc;
19683 }
19684
19685 /*
19686 ** Control and query of the open file handle.
19687 */
19688 static int winFileControl(sqlite3_file *id, int op, void *pArg){
19689   switch( op ){
19690     case SQLITE_FCNTL_LOCKSTATE: {
19691       *(int*)pArg = ((winFile*)id)->locktype;
19692       return SQLITE_OK;
19693     }
19694   }
19695   return SQLITE_ERROR;
19696 }
19697
19698 /*
19699 ** Return the sector size in bytes of the underlying block device for
19700 ** the specified file. This is almost always 512 bytes, but may be
19701 ** larger for some devices.
19702 **
19703 ** SQLite code assumes this function cannot fail. It also assumes that
19704 ** if two files are created in the same file-system directory (i.e.
19705 ** a database and its journal file) that the sector size will be the
19706 ** same for both.
19707 */
19708 static int winSectorSize(sqlite3_file *id){
19709   return SQLITE_DEFAULT_SECTOR_SIZE;
19710 }
19711
19712 /*
19713 ** Return a vector of device characteristics.
19714 */
19715 static int winDeviceCharacteristics(sqlite3_file *id){
19716   return 0;
19717 }
19718
19719 /*
19720 ** This vector defines all the methods that can operate on an
19721 ** sqlite3_file for win32.
19722 */
19723 static const sqlite3_io_methods winIoMethod = {
19724   1,                        /* iVersion */
19725   winClose,
19726   winRead,
19727   winWrite,
19728   winTruncate,
19729   winSync,
19730   winFileSize,
19731   winLock,
19732   winUnlock,
19733   winCheckReservedLock,
19734   winFileControl,
19735   winSectorSize,
19736   winDeviceCharacteristics
19737 };
19738
19739 /***************************************************************************
19740 ** Here ends the I/O methods that form the sqlite3_io_methods object.
19741 **
19742 ** The next block of code implements the VFS methods.
19743 ****************************************************************************/
19744
19745 /*
19746 ** Convert a UTF-8 filename into whatever form the underlying
19747 ** operating system wants filenames in.  Space to hold the result
19748 ** is obtained from malloc and must be freed by the calling
19749 ** function.
19750 */
19751 static void *convertUtf8Filename(const char *zFilename){
19752   void *zConverted = 0;
19753   if( isNT() ){
19754     zConverted = utf8ToUnicode(zFilename);
19755   }else{
19756     zConverted = utf8ToMbcs(zFilename);
19757   }
19758   /* caller will handle out of memory */
19759   return zConverted;
19760 }
19761
19762 /*
19763 ** Open a file.
19764 */
19765 static int winOpen(
19766   sqlite3_vfs *pVfs,        /* Not used */
19767   const char *zName,        /* Name of the file (UTF-8) */
19768   sqlite3_file *id,         /* Write the SQLite file handle here */
19769   int flags,                /* Open mode flags */
19770   int *pOutFlags            /* Status return flags */
19771 ){
19772   HANDLE h;
19773   DWORD dwDesiredAccess;
19774   DWORD dwShareMode;
19775   DWORD dwCreationDisposition;
19776   DWORD dwFlagsAndAttributes = 0;
19777   int isTemp;
19778   winFile *pFile = (winFile*)id;
19779   void *zConverted = convertUtf8Filename(zName);
19780   if( zConverted==0 ){
19781     return SQLITE_NOMEM;
19782   }
19783
19784   if( flags & SQLITE_OPEN_READWRITE ){
19785     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
19786   }else{
19787     dwDesiredAccess = GENERIC_READ;
19788   }
19789   if( flags & SQLITE_OPEN_CREATE ){
19790     dwCreationDisposition = OPEN_ALWAYS;
19791   }else{
19792     dwCreationDisposition = OPEN_EXISTING;
19793   }
19794   if( flags & SQLITE_OPEN_MAIN_DB ){
19795     dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
19796   }else{
19797     dwShareMode = 0;
19798   }
19799   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
19800 #if OS_WINCE
19801     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
19802 #else
19803     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
19804                                | FILE_ATTRIBUTE_HIDDEN
19805                                | FILE_FLAG_DELETE_ON_CLOSE;
19806 #endif
19807     isTemp = 1;
19808   }else{
19809     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
19810     isTemp = 0;
19811   }
19812   /* Reports from the internet are that performance is always
19813   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
19814   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
19815   if( isNT() ){
19816     h = CreateFileW((WCHAR*)zConverted,
19817        dwDesiredAccess,
19818        dwShareMode,
19819        NULL,
19820        dwCreationDisposition,
19821        dwFlagsAndAttributes,
19822        NULL
19823     );
19824   }else{
19825 #if OS_WINCE
19826     return SQLITE_NOMEM;
19827 #else
19828     h = CreateFileA((char*)zConverted,
19829        dwDesiredAccess,
19830        dwShareMode,
19831        NULL,
19832        dwCreationDisposition,
19833        dwFlagsAndAttributes,
19834        NULL
19835     );
19836 #endif
19837   }
19838   if( h==INVALID_HANDLE_VALUE ){
19839     free(zConverted);
19840     if( flags & SQLITE_OPEN_READWRITE ){
19841       return winOpen(0, zName, id, 
19842              ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
19843     }else{
19844       return SQLITE_CANTOPEN;
19845     }
19846   }
19847   if( pOutFlags ){
19848     if( flags & SQLITE_OPEN_READWRITE ){
19849       *pOutFlags = SQLITE_OPEN_READWRITE;
19850     }else{
19851       *pOutFlags = SQLITE_OPEN_READONLY;
19852     }
19853   }
19854   memset(pFile, 0, sizeof(*pFile));
19855   pFile->pMethod = &winIoMethod;
19856   pFile->h = h;
19857 #if OS_WINCE
19858   if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
19859                (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
19860        && !winceCreateLock(zName, pFile)
19861   ){
19862     CloseHandle(h);
19863     free(zConverted);
19864     return SQLITE_CANTOPEN;
19865   }
19866   if( isTemp ){
19867     pFile->zDeleteOnClose = zConverted;
19868   }else
19869 #endif
19870   {
19871     free(zConverted);
19872   }
19873   OpenCounter(+1);
19874   return SQLITE_OK;
19875 }
19876
19877 /*
19878 ** Delete the named file.
19879 **
19880 ** Note that windows does not allow a file to be deleted if some other
19881 ** process has it open.  Sometimes a virus scanner or indexing program
19882 ** will open a journal file shortly after it is created in order to do
19883 ** whatever does.  While this other process is holding the
19884 ** file open, we will be unable to delete it.  To work around this
19885 ** problem, we delay 100 milliseconds and try to delete again.  Up
19886 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
19887 ** up and returning an error.
19888 */
19889 #define MX_DELETION_ATTEMPTS 5
19890 static int winDelete(
19891   sqlite3_vfs *pVfs,          /* Not used on win32 */
19892   const char *zFilename,      /* Name of file to delete */
19893   int syncDir                 /* Not used on win32 */
19894 ){
19895   int cnt = 0;
19896   int rc;
19897   void *zConverted = convertUtf8Filename(zFilename);
19898   if( zConverted==0 ){
19899     return SQLITE_NOMEM;
19900   }
19901   SimulateIOError(return SQLITE_IOERR_DELETE);
19902   if( isNT() ){
19903     do{
19904       DeleteFileW(zConverted);
19905     }while( (rc = GetFileAttributesW(zConverted))!=0xffffffff 
19906             && cnt++ < MX_DELETION_ATTEMPTS && (Sleep(100), 1) );
19907   }else{
19908 #if OS_WINCE
19909     return SQLITE_NOMEM;
19910 #else
19911     do{
19912       DeleteFileA(zConverted);
19913     }while( (rc = GetFileAttributesA(zConverted))!=0xffffffff
19914             && cnt++ < MX_DELETION_ATTEMPTS && (Sleep(100), 1) );
19915 #endif
19916   }
19917   free(zConverted);
19918   OSTRACE2("DELETE \"%s\"\n", zFilename);
19919   return rc==0xffffffff ? SQLITE_OK : SQLITE_IOERR_DELETE;
19920 }
19921
19922 /*
19923 ** Check the existance and status of a file.
19924 */
19925 static int winAccess(
19926   sqlite3_vfs *pVfs,         /* Not used on win32 */
19927   const char *zFilename,     /* Name of file to check */
19928   int flags                  /* Type of test to make on this file */
19929 ){
19930   DWORD attr;
19931   int rc;
19932   void *zConverted = convertUtf8Filename(zFilename);
19933   if( zConverted==0 ){
19934     return SQLITE_NOMEM;
19935   }
19936   if( isNT() ){
19937     attr = GetFileAttributesW((WCHAR*)zConverted);
19938   }else{
19939 #if OS_WINCE
19940     return SQLITE_NOMEM;
19941 #else
19942     attr = GetFileAttributesA((char*)zConverted);
19943 #endif
19944   }
19945   free(zConverted);
19946   switch( flags ){
19947     case SQLITE_ACCESS_READ:
19948     case SQLITE_ACCESS_EXISTS:
19949       rc = attr!=0xffffffff;
19950       break;
19951     case SQLITE_ACCESS_READWRITE:
19952       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
19953       break;
19954     default:
19955       assert(!"Invalid flags argument");
19956   }
19957   return rc;
19958 }
19959
19960
19961 /*
19962 ** Create a temporary file name in zBuf.  zBuf must be big enough to
19963 ** hold at pVfs->mxPathname characters.
19964 */
19965 static int winGetTempname(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
19966   static char zChars[] =
19967     "abcdefghijklmnopqrstuvwxyz"
19968     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
19969     "0123456789";
19970   int i, j;
19971   char zTempPath[MAX_PATH+1];
19972   if( sqlite3_temp_directory ){
19973     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
19974   }else if( isNT() ){
19975     char *zMulti;
19976     WCHAR zWidePath[MAX_PATH];
19977     GetTempPathW(MAX_PATH-30, zWidePath);
19978     zMulti = unicodeToUtf8(zWidePath);
19979     if( zMulti ){
19980       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
19981       free(zMulti);
19982     }else{
19983       return SQLITE_NOMEM;
19984     }
19985   }else{
19986     char *zUtf8;
19987     char zMbcsPath[MAX_PATH];
19988     GetTempPathA(MAX_PATH-30, zMbcsPath);
19989     zUtf8 = mbcsToUtf8(zMbcsPath);
19990     if( zUtf8 ){
19991       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
19992       free(zUtf8);
19993     }else{
19994       return SQLITE_NOMEM;
19995     }
19996   }
19997   for(i=strlen(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
19998   zTempPath[i] = 0;
19999   sqlite3_snprintf(nBuf-30, zBuf,
20000                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
20001   j = strlen(zBuf);
20002   sqlite3Randomness(20, &zBuf[j]);
20003   for(i=0; i<20; i++, j++){
20004     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
20005   }
20006   zBuf[j] = 0;
20007   OSTRACE2("TEMP FILENAME: %s\n", zBuf);
20008   return SQLITE_OK; 
20009 }
20010
20011 /*
20012 ** Turn a relative pathname into a full pathname.  Write the full
20013 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
20014 ** bytes in size.
20015 */
20016 static int winFullPathname(
20017   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
20018   const char *zRelative,        /* Possibly relative input path */
20019   int nFull,                    /* Size of output buffer in bytes */
20020   char *zFull                   /* Output buffer */
20021 ){
20022
20023 #if defined(__CYGWIN__)
20024   cygwin_conv_to_full_win32_path(zRelative, zFull);
20025   return SQLITE_OK;
20026 #endif
20027
20028 #if OS_WINCE
20029   /* WinCE has no concept of a relative pathname, or so I am told. */
20030   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
20031   return SQLITE_OK;
20032 #endif
20033
20034 #if !OS_WINCE && !defined(__CYGWIN__)
20035   int nByte;
20036   void *zConverted;
20037   char *zOut;
20038   zConverted = convertUtf8Filename(zRelative);
20039   if( isNT() ){
20040     WCHAR *zTemp;
20041     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
20042     zTemp = malloc( nByte*sizeof(zTemp[0]) );
20043     if( zTemp==0 ){
20044       free(zConverted);
20045       return SQLITE_NOMEM;
20046     }
20047     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
20048     free(zConverted);
20049     zOut = unicodeToUtf8(zTemp);
20050     free(zTemp);
20051   }else{
20052     char *zTemp;
20053     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
20054     zTemp = malloc( nByte*sizeof(zTemp[0]) );
20055     if( zTemp==0 ){
20056       free(zConverted);
20057       return SQLITE_NOMEM;
20058     }
20059     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
20060     free(zConverted);
20061     zOut = mbcsToUtf8(zTemp);
20062     free(zTemp);
20063   }
20064   if( zOut ){
20065     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
20066     free(zOut);
20067     return SQLITE_OK;
20068   }else{
20069     return SQLITE_NOMEM;
20070   }
20071 #endif
20072 }
20073
20074 #ifndef SQLITE_OMIT_LOAD_EXTENSION
20075 /*
20076 ** Interfaces for opening a shared library, finding entry points
20077 ** within the shared library, and closing the shared library.
20078 */
20079 /*
20080 ** Interfaces for opening a shared library, finding entry points
20081 ** within the shared library, and closing the shared library.
20082 */
20083 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
20084   HANDLE h;
20085   void *zConverted = convertUtf8Filename(zFilename);
20086   if( zConverted==0 ){
20087     return 0;
20088   }
20089   if( isNT() ){
20090     h = LoadLibraryW((WCHAR*)zConverted);
20091   }else{
20092 #if OS_WINCE
20093     return 0;
20094 #else
20095     h = LoadLibraryA((char*)zConverted);
20096 #endif
20097   }
20098   free(zConverted);
20099   return (void*)h;
20100 }
20101 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
20102 #if OS_WINCE
20103   int error = GetLastError();
20104   if( error>0x7FFFFFF ){
20105     sqlite3_snprintf(nBuf, zBufOut, "OsError 0x%x", error);
20106   }else{
20107     sqlite3_snprintf(nBuf, zBufOut, "OsError %d", error);
20108   }
20109 #else
20110   FormatMessageA(
20111     FORMAT_MESSAGE_FROM_SYSTEM,
20112     NULL,
20113     GetLastError(),
20114     0,
20115     zBufOut,
20116     nBuf-1,
20117     0
20118   );
20119 #endif
20120 }
20121 void *winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
20122 #if OS_WINCE
20123   /* The GetProcAddressA() routine is only available on wince. */
20124   return GetProcAddressA((HANDLE)pHandle, zSymbol);
20125 #else
20126   /* All other windows platforms expect GetProcAddress() to take
20127   ** an Ansi string regardless of the _UNICODE setting */
20128   return GetProcAddress((HANDLE)pHandle, zSymbol);
20129 #endif
20130 }
20131 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
20132   FreeLibrary((HANDLE)pHandle);
20133 }
20134 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
20135   #define winDlOpen  0
20136   #define winDlError 0
20137   #define winDlSym   0
20138   #define winDlClose 0
20139 #endif
20140
20141
20142 /*
20143 ** Write up to nBuf bytes of randomness into zBuf.
20144 */
20145 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
20146   int n = 0;
20147   if( sizeof(SYSTEMTIME)<=nBuf-n ){
20148     SYSTEMTIME x;
20149     GetSystemTime(&x);
20150     memcpy(&zBuf[n], &x, sizeof(x));
20151     n += sizeof(x);
20152   }
20153   if( sizeof(DWORD)<=nBuf-n ){
20154     DWORD pid = GetCurrentProcessId();
20155     memcpy(&zBuf[n], &pid, sizeof(pid));
20156     n += sizeof(pid);
20157   }
20158   if( sizeof(DWORD)<=nBuf-n ){
20159     DWORD cnt = GetTickCount();
20160     memcpy(&zBuf[n], &cnt, sizeof(cnt));
20161     n += sizeof(cnt);
20162   }
20163   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
20164     LARGE_INTEGER i;
20165     QueryPerformanceCounter(&i);
20166     memcpy(&zBuf[n], &i, sizeof(i));
20167     n += sizeof(i);
20168   }
20169   return n;
20170 }
20171
20172
20173 /*
20174 ** Sleep for a little while.  Return the amount of time slept.
20175 */
20176 static int winSleep(sqlite3_vfs *pVfs, int microsec){
20177   Sleep((microsec+999)/1000);
20178   return ((microsec+999)/1000)*1000;
20179 }
20180
20181 /*
20182 ** The following variable, if set to a non-zero value, becomes the result
20183 ** returned from sqlite3OsCurrentTime().  This is used for testing.
20184 */
20185 #ifdef SQLITE_TEST
20186 SQLITE_API int sqlite3_current_time = 0;
20187 #endif
20188
20189 /*
20190 ** Find the current time (in Universal Coordinated Time).  Write the
20191 ** current time and date as a Julian Day number into *prNow and
20192 ** return 0.  Return 1 if the time and date cannot be found.
20193 */
20194 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
20195   FILETIME ft;
20196   /* FILETIME structure is a 64-bit value representing the number of 
20197      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
20198   */
20199   double now;
20200 #if OS_WINCE
20201   SYSTEMTIME time;
20202   GetSystemTime(&time);
20203   SystemTimeToFileTime(&time,&ft);
20204 #else
20205   GetSystemTimeAsFileTime( &ft );
20206 #endif
20207   now = ((double)ft.dwHighDateTime) * 4294967296.0; 
20208   *prNow = (now + ft.dwLowDateTime)/864000000000.0 + 2305813.5;
20209 #ifdef SQLITE_TEST
20210   if( sqlite3_current_time ){
20211     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
20212   }
20213 #endif
20214   return 0;
20215 }
20216
20217
20218 /*
20219 ** Return a pointer to the sqlite3DefaultVfs structure.   We use
20220 ** a function rather than give the structure global scope because
20221 ** some compilers (MSVC) do not allow forward declarations of
20222 ** initialized structures.
20223 */
20224 SQLITE_PRIVATE sqlite3_vfs *sqlite3OsDefaultVfs(void){
20225   static sqlite3_vfs winVfs = {
20226     1,                 /* iVersion */
20227     sizeof(winFile),   /* szOsFile */
20228     MAX_PATH,          /* mxPathname */
20229     0,                 /* pNext */
20230     "win32",           /* zName */
20231     0,                 /* pAppData */
20232   
20233     winOpen,           /* xOpen */
20234     winDelete,         /* xDelete */
20235     winAccess,         /* xAccess */
20236     winGetTempname,    /* xGetTempName */
20237     winFullPathname,   /* xFullPathname */
20238     winDlOpen,         /* xDlOpen */
20239     winDlError,        /* xDlError */
20240     winDlSym,          /* xDlSym */
20241     winDlClose,        /* xDlClose */
20242     winRandomness,     /* xRandomness */
20243     winSleep,          /* xSleep */
20244     winCurrentTime     /* xCurrentTime */
20245   };
20246   
20247   return &winVfs;
20248 }
20249
20250 #endif /* OS_WIN */
20251
20252 /************** End of os_win.c **********************************************/
20253 /************** Begin file pager.c *******************************************/
20254 /*
20255 ** 2001 September 15
20256 **
20257 ** The author disclaims copyright to this source code.  In place of
20258 ** a legal notice, here is a blessing:
20259 **
20260 **    May you do good and not evil.
20261 **    May you find forgiveness for yourself and forgive others.
20262 **    May you share freely, never taking more than you give.
20263 **
20264 *************************************************************************
20265 ** This is the implementation of the page cache subsystem or "pager".
20266 ** 
20267 ** The pager is used to access a database disk file.  It implements
20268 ** atomic commit and rollback through the use of a journal file that
20269 ** is separate from the database file.  The pager also implements file
20270 ** locking to prevent two processes from writing the same database
20271 ** file simultaneously, or one process from reading the database while
20272 ** another is writing.
20273 **
20274 ** @(#) $Id: pager.c,v 1.400 2007/12/13 21:54:11 drh Exp $
20275 */
20276 #ifndef SQLITE_OMIT_DISKIO
20277
20278 /*
20279 ** Macros for troubleshooting.  Normally turned off
20280 */
20281 #if 0
20282 #define sqlite3DebugPrintf printf
20283 #define PAGERTRACE1(X)       sqlite3DebugPrintf(X)
20284 #define PAGERTRACE2(X,Y)     sqlite3DebugPrintf(X,Y)
20285 #define PAGERTRACE3(X,Y,Z)   sqlite3DebugPrintf(X,Y,Z)
20286 #define PAGERTRACE4(X,Y,Z,W) sqlite3DebugPrintf(X,Y,Z,W)
20287 #define PAGERTRACE5(X,Y,Z,W,V) sqlite3DebugPrintf(X,Y,Z,W,V)
20288 #else
20289 #define PAGERTRACE1(X)
20290 #define PAGERTRACE2(X,Y)
20291 #define PAGERTRACE3(X,Y,Z)
20292 #define PAGERTRACE4(X,Y,Z,W)
20293 #define PAGERTRACE5(X,Y,Z,W,V)
20294 #endif
20295
20296 /*
20297 ** The following two macros are used within the PAGERTRACEX() macros above
20298 ** to print out file-descriptors. 
20299 **
20300 ** PAGERID() takes a pointer to a Pager struct as its argument. The
20301 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
20302 ** struct as its argument.
20303 */
20304 #define PAGERID(p) ((int)(p->fd))
20305 #define FILEHANDLEID(fd) ((int)fd)
20306
20307 /*
20308 ** The page cache as a whole is always in one of the following
20309 ** states:
20310 **
20311 **   PAGER_UNLOCK        The page cache is not currently reading or 
20312 **                       writing the database file.  There is no
20313 **                       data held in memory.  This is the initial
20314 **                       state.
20315 **
20316 **   PAGER_SHARED        The page cache is reading the database.
20317 **                       Writing is not permitted.  There can be
20318 **                       multiple readers accessing the same database
20319 **                       file at the same time.
20320 **
20321 **   PAGER_RESERVED      This process has reserved the database for writing
20322 **                       but has not yet made any changes.  Only one process
20323 **                       at a time can reserve the database.  The original
20324 **                       database file has not been modified so other
20325 **                       processes may still be reading the on-disk
20326 **                       database file.
20327 **
20328 **   PAGER_EXCLUSIVE     The page cache is writing the database.
20329 **                       Access is exclusive.  No other processes or
20330 **                       threads can be reading or writing while one
20331 **                       process is writing.
20332 **
20333 **   PAGER_SYNCED        The pager moves to this state from PAGER_EXCLUSIVE
20334 **                       after all dirty pages have been written to the
20335 **                       database file and the file has been synced to
20336 **                       disk. All that remains to do is to remove or
20337 **                       truncate the journal file and the transaction 
20338 **                       will be committed.
20339 **
20340 ** The page cache comes up in PAGER_UNLOCK.  The first time a
20341 ** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
20342 ** After all pages have been released using sqlite_page_unref(),
20343 ** the state transitions back to PAGER_UNLOCK.  The first time
20344 ** that sqlite3PagerWrite() is called, the state transitions to
20345 ** PAGER_RESERVED.  (Note that sqlite3PagerWrite() can only be
20346 ** called on an outstanding page which means that the pager must
20347 ** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
20348 ** PAGER_RESERVED means that there is an open rollback journal.
20349 ** The transition to PAGER_EXCLUSIVE occurs before any changes
20350 ** are made to the database file, though writes to the rollback
20351 ** journal occurs with just PAGER_RESERVED.  After an sqlite3PagerRollback()
20352 ** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
20353 ** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
20354 */
20355 #define PAGER_UNLOCK      0
20356 #define PAGER_SHARED      1   /* same as SHARED_LOCK */
20357 #define PAGER_RESERVED    2   /* same as RESERVED_LOCK */
20358 #define PAGER_EXCLUSIVE   4   /* same as EXCLUSIVE_LOCK */
20359 #define PAGER_SYNCED      5
20360
20361 /*
20362 ** If the SQLITE_BUSY_RESERVED_LOCK macro is set to true at compile-time,
20363 ** then failed attempts to get a reserved lock will invoke the busy callback.
20364 ** This is off by default.  To see why, consider the following scenario:
20365 ** 
20366 ** Suppose thread A already has a shared lock and wants a reserved lock.
20367 ** Thread B already has a reserved lock and wants an exclusive lock.  If
20368 ** both threads are using their busy callbacks, it might be a long time
20369 ** be for one of the threads give up and allows the other to proceed.
20370 ** But if the thread trying to get the reserved lock gives up quickly
20371 ** (if it never invokes its busy callback) then the contention will be
20372 ** resolved quickly.
20373 */
20374 #ifndef SQLITE_BUSY_RESERVED_LOCK
20375 # define SQLITE_BUSY_RESERVED_LOCK 0
20376 #endif
20377
20378 /*
20379 ** This macro rounds values up so that if the value is an address it
20380 ** is guaranteed to be an address that is aligned to an 8-byte boundary.
20381 */
20382 #define FORCE_ALIGNMENT(X)   (((X)+7)&~7)
20383
20384 typedef struct PgHdr PgHdr;
20385
20386 /*
20387 ** Each pager stores all currently unreferenced pages in a list sorted
20388 ** in least-recently-used (LRU) order (i.e. the first item on the list has 
20389 ** not been referenced in a long time, the last item has been recently
20390 ** used). An instance of this structure is included as part of each
20391 ** pager structure for this purpose (variable Pager.lru).
20392 **
20393 ** Additionally, if memory-management is enabled, all unreferenced pages 
20394 ** are stored in a global LRU list (global variable sqlite3LruPageList).
20395 **
20396 ** In both cases, the PagerLruList.pFirstSynced variable points to
20397 ** the first page in the corresponding list that does not require an
20398 ** fsync() operation before its memory can be reclaimed. If no such
20399 ** page exists, PagerLruList.pFirstSynced is set to NULL.
20400 */
20401 typedef struct PagerLruList PagerLruList;
20402 struct PagerLruList {
20403   PgHdr *pFirst;         /* First page in LRU list */
20404   PgHdr *pLast;          /* Last page in LRU list (the most recently used) */
20405   PgHdr *pFirstSynced;   /* First page in list with PgHdr.needSync==0 */
20406 };
20407
20408 /*
20409 ** The following structure contains the next and previous pointers used
20410 ** to link a PgHdr structure into a PagerLruList linked list. 
20411 */
20412 typedef struct PagerLruLink PagerLruLink;
20413 struct PagerLruLink {
20414   PgHdr *pNext;
20415   PgHdr *pPrev;
20416 };
20417
20418 /*
20419 ** Each in-memory image of a page begins with the following header.
20420 ** This header is only visible to this pager module.  The client
20421 ** code that calls pager sees only the data that follows the header.
20422 **
20423 ** Client code should call sqlite3PagerWrite() on a page prior to making
20424 ** any modifications to that page.  The first time sqlite3PagerWrite()
20425 ** is called, the original page contents are written into the rollback
20426 ** journal and PgHdr.inJournal and PgHdr.needSync are set.  Later, once
20427 ** the journal page has made it onto the disk surface, PgHdr.needSync
20428 ** is cleared.  The modified page cannot be written back into the original
20429 ** database file until the journal pages has been synced to disk and the
20430 ** PgHdr.needSync has been cleared.
20431 **
20432 ** The PgHdr.dirty flag is set when sqlite3PagerWrite() is called and
20433 ** is cleared again when the page content is written back to the original
20434 ** database file.
20435 **
20436 ** Details of important structure elements:
20437 **
20438 ** needSync
20439 **
20440 **     If this is true, this means that it is not safe to write the page
20441 **     content to the database because the original content needed
20442 **     for rollback has not by synced to the main rollback journal.
20443 **     The original content may have been written to the rollback journal
20444 **     but it has not yet been synced.  So we cannot write to the database
20445 **     file because power failure might cause the page in the journal file
20446 **     to never reach the disk.  It is as if the write to the journal file
20447 **     does not occur until the journal file is synced.
20448 **     
20449 **     This flag is false if the page content exactly matches what
20450 **     currently exists in the database file.  The needSync flag is also
20451 **     false if the original content has been written to the main rollback
20452 **     journal and synced.  If the page represents a new page that has
20453 **     been added onto the end of the database during the current
20454 **     transaction, the needSync flag is true until the original database
20455 **     size in the journal header has been synced to disk.
20456 **
20457 ** inJournal
20458 **
20459 **     This is true if the original page has been written into the main
20460 **     rollback journal.  This is always false for new pages added to
20461 **     the end of the database file during the current transaction.
20462 **     And this flag says nothing about whether or not the journal
20463 **     has been synced to disk.  For pages that are in the original
20464 **     database file, the following expression should always be true:
20465 **
20466 **       inJournal = (pPager->aInJournal[(pgno-1)/8] & (1<<((pgno-1)%8))!=0
20467 **
20468 **     The pPager->aInJournal[] array is only valid for the original
20469 **     pages of the database, not new pages that are added to the end
20470 **     of the database, so obviously the above expression cannot be
20471 **     valid for new pages.  For new pages inJournal is always 0.
20472 **
20473 ** dirty
20474 **
20475 **     When true, this means that the content of the page has been
20476 **     modified and needs to be written back to the database file.
20477 **     If false, it means that either the content of the page is
20478 **     unchanged or else the content is unimportant and we do not
20479 **     care whether or not it is preserved.
20480 **
20481 ** alwaysRollback
20482 **
20483 **     This means that the sqlite3PagerDontRollback() API should be
20484 **     ignored for this page.  The DontRollback() API attempts to say
20485 **     that the content of the page on disk is unimportant (it is an
20486 **     unused page on the freelist) so that it is unnecessary to 
20487 **     rollback changes to this page because the content of the page
20488 **     can change without changing the meaning of the database.  This
20489 **     flag overrides any DontRollback() attempt.  This flag is set
20490 **     when a page that originally contained valid data is added to
20491 **     the freelist.  Later in the same transaction, this page might
20492 **     be pulled from the freelist and reused for something different
20493 **     and at that point the DontRollback() API will be called because
20494 **     pages taken from the freelist do not need to be protected by
20495 **     the rollback journal.  But this flag says that the page was
20496 **     not originally part of the freelist so that it still needs to
20497 **     be rolled back in spite of any subsequent DontRollback() calls.
20498 **
20499 ** needRead 
20500 **
20501 **     This flag means (when true) that the content of the page has
20502 **     not yet been loaded from disk.  The in-memory content is just
20503 **     garbage.  (Actually, we zero the content, but you should not
20504 **     make any assumptions about the content nevertheless.)  If the
20505 **     content is needed in the future, it should be read from the
20506 **     original database file.
20507 */
20508 struct PgHdr {
20509   Pager *pPager;                 /* The pager to which this page belongs */
20510   Pgno pgno;                     /* The page number for this page */
20511   PgHdr *pNextHash, *pPrevHash;  /* Hash collision chain for PgHdr.pgno */
20512   PagerLruLink free;             /* Next and previous free pages */
20513   PgHdr *pNextAll;               /* A list of all pages */
20514   u8 inJournal;                  /* TRUE if has been written to journal */
20515   u8 dirty;                      /* TRUE if we need to write back changes */
20516   u8 needSync;                   /* Sync journal before writing this page */
20517   u8 alwaysRollback;             /* Disable DontRollback() for this page */
20518   u8 needRead;                   /* Read content if PagerWrite() is called */
20519   short int nRef;                /* Number of users of this page */
20520   PgHdr *pDirty, *pPrevDirty;    /* Dirty pages */
20521 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
20522   PagerLruLink gfree;            /* Global list of nRef==0 pages */
20523 #endif
20524 #ifdef SQLITE_CHECK_PAGES
20525   u32 pageHash;
20526 #endif
20527   void *pData;                   /* Page data */
20528   /* Pager.nExtra bytes of local data appended to this header */
20529 };
20530
20531 /*
20532 ** For an in-memory only database, some extra information is recorded about
20533 ** each page so that changes can be rolled back.  (Journal files are not
20534 ** used for in-memory databases.)  The following information is added to
20535 ** the end of every EXTRA block for in-memory databases.
20536 **
20537 ** This information could have been added directly to the PgHdr structure.
20538 ** But then it would take up an extra 8 bytes of storage on every PgHdr
20539 ** even for disk-based databases.  Splitting it out saves 8 bytes.  This
20540 ** is only a savings of 0.8% but those percentages add up.
20541 */
20542 typedef struct PgHistory PgHistory;
20543 struct PgHistory {
20544   u8 *pOrig;     /* Original page text.  Restore to this on a full rollback */
20545   u8 *pStmt;     /* Text as it was at the beginning of the current statement */
20546   PgHdr *pNextStmt, *pPrevStmt;  /* List of pages in the statement journal */
20547   u8 inStmt;                     /* TRUE if in the statement subjournal */
20548 };
20549
20550 /*
20551 ** A macro used for invoking the codec if there is one
20552 */
20553 #ifdef SQLITE_HAS_CODEC
20554 # define CODEC1(P,D,N,X) if( P->xCodec!=0 ){ P->xCodec(P->pCodecArg,D,N,X); }
20555 # define CODEC2(P,D,N,X) ((char*)(P->xCodec!=0?P->xCodec(P->pCodecArg,D,N,X):D))
20556 #else
20557 # define CODEC1(P,D,N,X) /* NO-OP */
20558 # define CODEC2(P,D,N,X) ((char*)D)
20559 #endif
20560
20561 /*
20562 ** Convert a pointer to a PgHdr into a pointer to its data
20563 ** and back again.
20564 */
20565 #define PGHDR_TO_DATA(P)    ((P)->pData)
20566 #define PGHDR_TO_EXTRA(G,P) ((void*)&((G)[1]))
20567 #define PGHDR_TO_HIST(P,PGR)  \
20568             ((PgHistory*)&((char*)(&(P)[1]))[(PGR)->nExtra])
20569
20570 /*
20571 ** A open page cache is an instance of the following structure.
20572 **
20573 ** Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
20574 ** or SQLITE_FULL. Once one of the first three errors occurs, it persists
20575 ** and is returned as the result of every major pager API call.  The
20576 ** SQLITE_FULL return code is slightly different. It persists only until the
20577 ** next successful rollback is performed on the pager cache. Also,
20578 ** SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
20579 ** APIs, they may still be used successfully.
20580 */
20581 struct Pager {
20582   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
20583   u8 journalOpen;             /* True if journal file descriptors is valid */
20584   u8 journalStarted;          /* True if header of journal is synced */
20585   u8 useJournal;              /* Use a rollback journal on this file */
20586   u8 noReadlock;              /* Do not bother to obtain readlocks */
20587   u8 stmtOpen;                /* True if the statement subjournal is open */
20588   u8 stmtInUse;               /* True we are in a statement subtransaction */
20589   u8 stmtAutoopen;            /* Open stmt journal when main journal is opened*/
20590   u8 noSync;                  /* Do not sync the journal if true */
20591   u8 fullSync;                /* Do extra syncs of the journal for robustness */
20592   u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
20593   u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
20594   u8 tempFile;                /* zFilename is a temporary file */
20595   u8 readOnly;                /* True for a read-only database */
20596   u8 needSync;                /* True if an fsync() is needed on the journal */
20597   u8 dirtyCache;              /* True if cached pages have changed */
20598   u8 alwaysRollback;          /* Disable DontRollback() for all pages */
20599   u8 memDb;                   /* True to inhibit all file I/O */
20600   u8 setMaster;               /* True if a m-j name has been written to jrnl */
20601   u8 doNotSync;               /* Boolean. While true, do not spill the cache */
20602   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
20603   u8 changeCountDone;         /* Set after incrementing the change-counter */
20604   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
20605   int errCode;                /* One of several kinds of errors */
20606   int dbSize;                 /* Number of pages in the file */
20607   int origDbSize;             /* dbSize before the current change */
20608   int stmtSize;               /* Size of database (in pages) at stmt_begin() */
20609   int nRec;                   /* Number of pages written to the journal */
20610   u32 cksumInit;              /* Quasi-random value added to every checksum */
20611   int stmtNRec;               /* Number of records in stmt subjournal */
20612   int nExtra;                 /* Add this many bytes to each in-memory page */
20613   int pageSize;               /* Number of bytes in a page */
20614   int nPage;                  /* Total number of in-memory pages */
20615   int nRef;                   /* Number of in-memory pages with PgHdr.nRef>0 */
20616   int mxPage;                 /* Maximum number of pages to hold in cache */
20617   Pgno mxPgno;                /* Maximum allowed size of the database */
20618   u8 *aInJournal;             /* One bit for each page in the database file */
20619   u8 *aInStmt;                /* One bit for each page in the database */
20620   char *zFilename;            /* Name of the database file */
20621   char *zJournal;             /* Name of the journal file */
20622   char *zDirectory;           /* Directory hold database and journal files */
20623   char *zStmtJrnl;            /* Name of the statement journal file */
20624   sqlite3_file *fd, *jfd;     /* File descriptors for database and journal */
20625   sqlite3_file *stfd;         /* File descriptor for the statement subjournal*/
20626   BusyHandler *pBusyHandler;  /* Pointer to sqlite.busyHandler */
20627   PagerLruList lru;           /* LRU list of free pages */
20628   PgHdr *pAll;                /* List of all pages */
20629   PgHdr *pStmt;               /* List of pages in the statement subjournal */
20630   PgHdr *pDirty;              /* List of all dirty pages */
20631   i64 journalOff;             /* Current byte offset in the journal file */
20632   i64 journalHdr;             /* Byte offset to previous journal header */
20633   i64 stmtHdrOff;             /* First journal header written this statement */
20634   i64 stmtCksum;              /* cksumInit when statement was started */
20635   i64 stmtJSize;              /* Size of journal at stmt_begin() */
20636   int sectorSize;             /* Assumed sector size during rollback */
20637 #ifdef SQLITE_TEST
20638   int nHit, nMiss;            /* Cache hits and missing */
20639   int nRead, nWrite;          /* Database pages read/written */
20640 #endif
20641   void (*xDestructor)(DbPage*,int); /* Call this routine when freeing pages */
20642   void (*xReiniter)(DbPage*,int);   /* Call this routine when reloading pages */
20643 #ifdef SQLITE_HAS_CODEC
20644   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
20645   void *pCodecArg;            /* First argument to xCodec() */
20646 #endif
20647   int nHash;                  /* Size of the pager hash table */
20648   PgHdr **aHash;              /* Hash table to map page number to PgHdr */
20649 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
20650   Pager *pNext;               /* Doubly linked list of pagers on which */
20651   Pager *pPrev;               /* sqlite3_release_memory() will work */
20652   int iInUseMM;               /* Non-zero if unavailable to MM */
20653   int iInUseDB;               /* Non-zero if in sqlite3_release_memory() */
20654 #endif
20655   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
20656   char dbFileVers[16];        /* Changes whenever database file changes */
20657 };
20658
20659 /*
20660 ** The following global variables hold counters used for
20661 ** testing purposes only.  These variables do not exist in
20662 ** a non-testing build.  These variables are not thread-safe.
20663 */
20664 #ifdef SQLITE_TEST
20665 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
20666 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
20667 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
20668 SQLITE_API int sqlite3_pager_pgfree_count = 0;    /* Number of cache pages freed */
20669 # define PAGER_INCR(v)  v++
20670 #else
20671 # define PAGER_INCR(v)
20672 #endif
20673
20674 /*
20675 ** The following variable points to the head of a double-linked list
20676 ** of all pagers that are eligible for page stealing by the
20677 ** sqlite3_release_memory() interface.  Access to this list is
20678 ** protected by the SQLITE_MUTEX_STATIC_MEM2 mutex.
20679 */
20680 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
20681 static Pager *sqlite3PagerList = 0;
20682 static PagerLruList sqlite3LruPageList = {0, 0, 0};
20683 #endif
20684
20685
20686 /*
20687 ** Journal files begin with the following magic string.  The data
20688 ** was obtained from /dev/random.  It is used only as a sanity check.
20689 **
20690 ** Since version 2.8.0, the journal format contains additional sanity
20691 ** checking information.  If the power fails while the journal is begin
20692 ** written, semi-random garbage data might appear in the journal
20693 ** file after power is restored.  If an attempt is then made
20694 ** to roll the journal back, the database could be corrupted.  The additional
20695 ** sanity checking data is an attempt to discover the garbage in the
20696 ** journal and ignore it.
20697 **
20698 ** The sanity checking information for the new journal format consists
20699 ** of a 32-bit checksum on each page of data.  The checksum covers both
20700 ** the page number and the pPager->pageSize bytes of data for the page.
20701 ** This cksum is initialized to a 32-bit random value that appears in the
20702 ** journal file right after the header.  The random initializer is important,
20703 ** because garbage data that appears at the end of a journal is likely
20704 ** data that was once in other files that have now been deleted.  If the
20705 ** garbage data came from an obsolete journal file, the checksums might
20706 ** be correct.  But by initializing the checksum to random value which
20707 ** is different for every journal, we minimize that risk.
20708 */
20709 static const unsigned char aJournalMagic[] = {
20710   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
20711 };
20712
20713 /*
20714 ** The size of the header and of each page in the journal is determined
20715 ** by the following macros.
20716 */
20717 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
20718
20719 /*
20720 ** The journal header size for this pager. In the future, this could be
20721 ** set to some value read from the disk controller. The important
20722 ** characteristic is that it is the same size as a disk sector.
20723 */
20724 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
20725
20726 /*
20727 ** The macro MEMDB is true if we are dealing with an in-memory database.
20728 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
20729 ** the value of MEMDB will be a constant and the compiler will optimize
20730 ** out code that would never execute.
20731 */
20732 #ifdef SQLITE_OMIT_MEMORYDB
20733 # define MEMDB 0
20734 #else
20735 # define MEMDB pPager->memDb
20736 #endif
20737
20738 /*
20739 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
20740 ** reserved for working around a windows/posix incompatibility). It is
20741 ** used in the journal to signify that the remainder of the journal file 
20742 ** is devoted to storing a master journal name - there are no more pages to
20743 ** roll back. See comments for function writeMasterJournal() for details.
20744 */
20745 /* #define PAGER_MJ_PGNO(x) (PENDING_BYTE/((x)->pageSize)) */
20746 #define PAGER_MJ_PGNO(x) ((PENDING_BYTE/((x)->pageSize))+1)
20747
20748 /*
20749 ** The maximum legal page number is (2^31 - 1).
20750 */
20751 #define PAGER_MAX_PGNO 2147483647
20752
20753 /*
20754 ** The pagerEnter() and pagerLeave() routines acquire and release
20755 ** a mutex on each pager.  The mutex is recursive.
20756 **
20757 ** This is a special-purpose mutex.  It only provides mutual exclusion
20758 ** between the Btree and the Memory Management sqlite3_release_memory()
20759 ** function.  It does not prevent, for example, two Btrees from accessing
20760 ** the same pager at the same time.  Other general-purpose mutexes in
20761 ** the btree layer handle that chore.
20762 */
20763 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
20764   static void pagerEnter(Pager *p){
20765     p->iInUseDB++;
20766     if( p->iInUseMM && p->iInUseDB==1 ){
20767       sqlite3_mutex *mutex;
20768       mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM2);
20769       p->iInUseDB = 0;
20770       sqlite3_mutex_enter(mutex);
20771       p->iInUseDB = 1;
20772       sqlite3_mutex_leave(mutex);
20773     }
20774     assert( p->iInUseMM==0 );
20775   }
20776   static void pagerLeave(Pager *p){
20777     p->iInUseDB--;
20778     assert( p->iInUseDB>=0 );
20779   }
20780 #else
20781 # define pagerEnter(X)
20782 # define pagerLeave(X)
20783 #endif
20784
20785 /*
20786 ** Enable reference count tracking (for debugging) here:
20787 */
20788 #ifdef SQLITE_DEBUG
20789   int pager3_refinfo_enable = 0;
20790   static void pager_refinfo(PgHdr *p){
20791     static int cnt = 0;
20792     if( !pager3_refinfo_enable ) return;
20793     sqlite3DebugPrintf(
20794        "REFCNT: %4d addr=%p nRef=%-3d total=%d\n",
20795        p->pgno, PGHDR_TO_DATA(p), p->nRef, p->pPager->nRef
20796     );
20797     cnt++;   /* Something to set a breakpoint on */
20798   }
20799 # define REFINFO(X)  pager_refinfo(X)
20800 #else
20801 # define REFINFO(X)
20802 #endif
20803
20804 /*
20805 ** Add page pPg to the end of the linked list managed by structure
20806 ** pList (pPg becomes the last entry in the list - the most recently 
20807 ** used). Argument pLink should point to either pPg->free or pPg->gfree,
20808 ** depending on whether pPg is being added to the pager-specific or
20809 ** global LRU list.
20810 */
20811 static void listAdd(PagerLruList *pList, PagerLruLink *pLink, PgHdr *pPg){
20812   pLink->pNext = 0;
20813   pLink->pPrev = pList->pLast;
20814
20815 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
20816   assert(pLink==&pPg->free || pLink==&pPg->gfree);
20817   assert(pLink==&pPg->gfree || pList!=&sqlite3LruPageList);
20818 #endif
20819
20820   if( pList->pLast ){
20821     int iOff = (char *)pLink - (char *)pPg;
20822     PagerLruLink *pLastLink = (PagerLruLink *)(&((u8 *)pList->pLast)[iOff]);
20823     pLastLink->pNext = pPg;
20824   }else{
20825     assert(!pList->pFirst);
20826     pList->pFirst = pPg;
20827   }
20828
20829   pList->pLast = pPg;
20830   if( !pList->pFirstSynced && pPg->needSync==0 ){
20831     pList->pFirstSynced = pPg;
20832   }
20833 }
20834
20835 /*
20836 ** Remove pPg from the list managed by the structure pointed to by pList.
20837 **
20838 ** Argument pLink should point to either pPg->free or pPg->gfree, depending 
20839 ** on whether pPg is being added to the pager-specific or global LRU list.
20840 */
20841 static void listRemove(PagerLruList *pList, PagerLruLink *pLink, PgHdr *pPg){
20842   int iOff = (char *)pLink - (char *)pPg;
20843
20844 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
20845   assert(pLink==&pPg->free || pLink==&pPg->gfree);
20846   assert(pLink==&pPg->gfree || pList!=&sqlite3LruPageList);
20847 #endif
20848
20849   if( pPg==pList->pFirst ){
20850     pList->pFirst = pLink->pNext;
20851   }
20852   if( pPg==pList->pLast ){
20853     pList->pLast = pLink->pPrev;
20854   }
20855   if( pLink->pPrev ){
20856     PagerLruLink *pPrevLink = (PagerLruLink *)(&((u8 *)pLink->pPrev)[iOff]);
20857     pPrevLink->pNext = pLink->pNext;
20858   }
20859   if( pLink->pNext ){
20860     PagerLruLink *pNextLink = (PagerLruLink *)(&((u8 *)pLink->pNext)[iOff]);
20861     pNextLink->pPrev = pLink->pPrev;
20862   }
20863   if( pPg==pList->pFirstSynced ){
20864     PgHdr *p = pLink->pNext;
20865     while( p && p->needSync ){
20866       PagerLruLink *pL = (PagerLruLink *)(&((u8 *)p)[iOff]);
20867       p = pL->pNext;
20868     }
20869     pList->pFirstSynced = p;
20870   }
20871
20872   pLink->pNext = pLink->pPrev = 0;
20873 }
20874
20875 /* 
20876 ** Add page pPg to the list of free pages for the pager. If 
20877 ** memory-management is enabled, also add the page to the global 
20878 ** list of free pages.
20879 */
20880 static void lruListAdd(PgHdr *pPg){
20881   listAdd(&pPg->pPager->lru, &pPg->free, pPg);
20882 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
20883   if( !pPg->pPager->memDb ){
20884     sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
20885     listAdd(&sqlite3LruPageList, &pPg->gfree, pPg);
20886     sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
20887   }
20888 #endif
20889 }
20890
20891 /* 
20892 ** Remove page pPg from the list of free pages for the associated pager.
20893 ** If memory-management is enabled, also remove pPg from the global list
20894 ** of free pages.
20895 */
20896 static void lruListRemove(PgHdr *pPg){
20897   listRemove(&pPg->pPager->lru, &pPg->free, pPg);
20898 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
20899   if( !pPg->pPager->memDb ){
20900     sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
20901     listRemove(&sqlite3LruPageList, &pPg->gfree, pPg);
20902     sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
20903   }
20904 #endif
20905 }
20906
20907 /* 
20908 ** This function is called just after the needSync flag has been cleared
20909 ** from all pages managed by pPager (usually because the journal file
20910 ** has just been synced). It updates the pPager->lru.pFirstSynced variable
20911 ** and, if memory-management is enabled, the sqlite3LruPageList.pFirstSynced
20912 ** variable also.
20913 */
20914 static void lruListSetFirstSynced(Pager *pPager){
20915   pPager->lru.pFirstSynced = pPager->lru.pFirst;
20916 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
20917   if( !pPager->memDb ){
20918     PgHdr *p;
20919     sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
20920     for(p=sqlite3LruPageList.pFirst; p && p->needSync; p=p->gfree.pNext);
20921     assert(p==pPager->lru.pFirstSynced || p==sqlite3LruPageList.pFirstSynced);
20922     sqlite3LruPageList.pFirstSynced = p;
20923     sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
20924   }
20925 #endif
20926 }
20927
20928 /*
20929 ** Return true if page *pPg has already been written to the statement
20930 ** journal (or statement snapshot has been created, if *pPg is part
20931 ** of an in-memory database).
20932 */
20933 static int pageInStatement(PgHdr *pPg){
20934   Pager *pPager = pPg->pPager;
20935   if( MEMDB ){
20936     return PGHDR_TO_HIST(pPg, pPager)->inStmt;
20937   }else{
20938     Pgno pgno = pPg->pgno;
20939     u8 *a = pPager->aInStmt;
20940     return (a && (int)pgno<=pPager->stmtSize && (a[pgno/8] & (1<<(pgno&7))));
20941   }
20942 }
20943
20944 /*
20945 ** Change the size of the pager hash table to N.  N must be a power
20946 ** of two.
20947 */
20948 static void pager_resize_hash_table(Pager *pPager, int N){
20949   PgHdr **aHash, *pPg;
20950   assert( N>0 && (N&(N-1))==0 );
20951   pagerLeave(pPager);
20952   sqlite3MallocBenignFailure((int)pPager->aHash);
20953   aHash = sqlite3MallocZero( sizeof(aHash[0])*N );
20954   pagerEnter(pPager);
20955   if( aHash==0 ){
20956     /* Failure to rehash is not an error.  It is only a performance hit. */
20957     return;
20958   }
20959   sqlite3_free(pPager->aHash);
20960   pPager->nHash = N;
20961   pPager->aHash = aHash;
20962   for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
20963     int h;
20964     if( pPg->pgno==0 ){
20965       assert( pPg->pNextHash==0 && pPg->pPrevHash==0 );
20966       continue;
20967     }
20968     h = pPg->pgno & (N-1);
20969     pPg->pNextHash = aHash[h];
20970     if( aHash[h] ){
20971       aHash[h]->pPrevHash = pPg;
20972     }
20973     aHash[h] = pPg;
20974     pPg->pPrevHash = 0;
20975   }
20976 }
20977
20978 /*
20979 ** Read a 32-bit integer from the given file descriptor.  Store the integer
20980 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
20981 ** error code is something goes wrong.
20982 **
20983 ** All values are stored on disk as big-endian.
20984 */
20985 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
20986   unsigned char ac[4];
20987   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
20988   if( rc==SQLITE_OK ){
20989     *pRes = sqlite3Get4byte(ac);
20990   }
20991   return rc;
20992 }
20993
20994 /*
20995 ** Write a 32-bit integer into a string buffer in big-endian byte order.
20996 */
20997 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
20998
20999 /*
21000 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
21001 ** on success or an error code is something goes wrong.
21002 */
21003 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
21004   char ac[4];
21005   put32bits(ac, val);
21006   return sqlite3OsWrite(fd, ac, 4, offset);
21007 }
21008
21009 /*
21010 ** If file pFd is open, call sqlite3OsUnlock() on it.
21011 */
21012 static int osUnlock(sqlite3_file *pFd, int eLock){
21013   if( !pFd->pMethods ){
21014     return SQLITE_OK;
21015   }
21016   return sqlite3OsUnlock(pFd, eLock);
21017 }
21018
21019 /*
21020 ** This function determines whether or not the atomic-write optimization
21021 ** can be used with this pager. The optimization can be used if:
21022 **
21023 **  (a) the value returned by OsDeviceCharacteristics() indicates that
21024 **      a database page may be written atomically, and
21025 **  (b) the value returned by OsSectorSize() is less than or equal
21026 **      to the page size.
21027 **
21028 ** If the optimization cannot be used, 0 is returned. If it can be used,
21029 ** then the value returned is the size of the journal file when it
21030 ** contains rollback data for exactly one page.
21031 */
21032 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
21033 static int jrnlBufferSize(Pager *pPager){
21034   int dc;           /* Device characteristics */
21035   int nSector;      /* Sector size */
21036   int nPage;        /* Page size */
21037   sqlite3_file *fd = pPager->fd;
21038
21039   if( fd->pMethods ){
21040     dc = sqlite3OsDeviceCharacteristics(fd);
21041     nSector = sqlite3OsSectorSize(fd);
21042     nPage = pPager->pageSize;
21043   }
21044
21045   assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
21046   assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
21047
21048   if( !fd->pMethods || (dc&(SQLITE_IOCAP_ATOMIC|(nPage>>8))&&nSector<=nPage) ){
21049     return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
21050   }
21051   return 0;
21052 }
21053 #endif
21054
21055 /*
21056 ** This function should be called when an error occurs within the pager
21057 ** code. The first argument is a pointer to the pager structure, the
21058 ** second the error-code about to be returned by a pager API function. 
21059 ** The value returned is a copy of the second argument to this function. 
21060 **
21061 ** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
21062 ** the error becomes persistent. Until the persisten error is cleared,
21063 ** subsequent API calls on this Pager will immediately return the same 
21064 ** error code.
21065 **
21066 ** A persistent error indicates that the contents of the pager-cache 
21067 ** cannot be trusted. This state can be cleared by completely discarding 
21068 ** the contents of the pager-cache. If a transaction was active when
21069 ** the persistent error occured, then the rollback journal may need
21070 ** to be replayed.
21071 */
21072 static void pager_unlock(Pager *pPager);
21073 static int pager_error(Pager *pPager, int rc){
21074   int rc2 = rc & 0xff;
21075   assert(
21076        pPager->errCode==SQLITE_FULL ||
21077        pPager->errCode==SQLITE_OK ||
21078        (pPager->errCode & 0xff)==SQLITE_IOERR
21079   );
21080   if(
21081     rc2==SQLITE_FULL ||
21082     rc2==SQLITE_IOERR ||
21083     rc2==SQLITE_CORRUPT
21084   ){
21085     pPager->errCode = rc;
21086     if( pPager->state==PAGER_UNLOCK && pPager->nRef==0 ){
21087       /* If the pager is already unlocked, call pager_unlock() now to
21088       ** clear the error state and ensure that the pager-cache is 
21089       ** completely empty.
21090       */
21091       pager_unlock(pPager);
21092     }
21093   }
21094   return rc;
21095 }
21096
21097 /*
21098 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
21099 ** on the cache using a hash function.  This is used for testing
21100 ** and debugging only.
21101 */
21102 #ifdef SQLITE_CHECK_PAGES
21103 /*
21104 ** Return a 32-bit hash of the page data for pPage.
21105 */
21106 static u32 pager_datahash(int nByte, unsigned char *pData){
21107   u32 hash = 0;
21108   int i;
21109   for(i=0; i<nByte; i++){
21110     hash = (hash*1039) + pData[i];
21111   }
21112   return hash;
21113 }
21114 static u32 pager_pagehash(PgHdr *pPage){
21115   return pager_datahash(pPage->pPager->pageSize, 
21116                         (unsigned char *)PGHDR_TO_DATA(pPage));
21117 }
21118
21119 /*
21120 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
21121 ** is defined, and NDEBUG is not defined, an assert() statement checks
21122 ** that the page is either dirty or still matches the calculated page-hash.
21123 */
21124 #define CHECK_PAGE(x) checkPage(x)
21125 static void checkPage(PgHdr *pPg){
21126   Pager *pPager = pPg->pPager;
21127   assert( !pPg->pageHash || pPager->errCode || MEMDB || pPg->dirty || 
21128       pPg->pageHash==pager_pagehash(pPg) );
21129 }
21130
21131 #else
21132 #define pager_datahash(X,Y)  0
21133 #define pager_pagehash(X)  0
21134 #define CHECK_PAGE(x)
21135 #endif
21136
21137 /*
21138 ** When this is called the journal file for pager pPager must be open.
21139 ** The master journal file name is read from the end of the file and 
21140 ** written into memory supplied by the caller. 
21141 **
21142 ** zMaster must point to a buffer of at least nMaster bytes allocated by
21143 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
21144 ** enough space to write the master journal name). If the master journal
21145 ** name in the journal is longer than nMaster bytes (including a
21146 ** nul-terminator), then this is handled as if no master journal name
21147 ** were present in the journal.
21148 **
21149 ** If no master journal file name is present zMaster[0] is set to 0 and
21150 ** SQLITE_OK returned.
21151 */
21152 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, int nMaster){
21153   int rc;
21154   u32 len;
21155   i64 szJ;
21156   u32 cksum;
21157   int i;
21158   unsigned char aMagic[8]; /* A buffer to hold the magic header */
21159
21160   zMaster[0] = '\0';
21161
21162   rc = sqlite3OsFileSize(pJrnl, &szJ);
21163   if( rc!=SQLITE_OK || szJ<16 ) return rc;
21164
21165   rc = read32bits(pJrnl, szJ-16, &len);
21166   if( rc!=SQLITE_OK ) return rc;
21167
21168   if( len>=nMaster ){
21169     return SQLITE_OK;
21170   }
21171
21172   rc = read32bits(pJrnl, szJ-12, &cksum);
21173   if( rc!=SQLITE_OK ) return rc;
21174
21175   rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8);
21176   if( rc!=SQLITE_OK || memcmp(aMagic, aJournalMagic, 8) ) return rc;
21177
21178   rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len);
21179   if( rc!=SQLITE_OK ){
21180     return rc;
21181   }
21182   zMaster[len] = '\0';
21183
21184   /* See if the checksum matches the master journal name */
21185   for(i=0; i<len; i++){
21186     cksum -= zMaster[i];
21187    }
21188   if( cksum ){
21189     /* If the checksum doesn't add up, then one or more of the disk sectors
21190     ** containing the master journal filename is corrupted. This means
21191     ** definitely roll back, so just return SQLITE_OK and report a (nul)
21192     ** master-journal filename.
21193     */
21194     zMaster[0] = '\0';
21195   }
21196    
21197   return SQLITE_OK;
21198 }
21199
21200 /*
21201 ** Seek the journal file descriptor to the next sector boundary where a
21202 ** journal header may be read or written. Pager.journalOff is updated with
21203 ** the new seek offset.
21204 **
21205 ** i.e for a sector size of 512:
21206 **
21207 ** Input Offset              Output Offset
21208 ** ---------------------------------------
21209 ** 0                         0
21210 ** 512                       512
21211 ** 100                       512
21212 ** 2000                      2048
21213 ** 
21214 */
21215 static void seekJournalHdr(Pager *pPager){
21216   i64 offset = 0;
21217   i64 c = pPager->journalOff;
21218   if( c ){
21219     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
21220   }
21221   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
21222   assert( offset>=c );
21223   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
21224   pPager->journalOff = offset;
21225 }
21226
21227 /*
21228 ** The journal file must be open when this routine is called. A journal
21229 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
21230 ** current location.
21231 **
21232 ** The format for the journal header is as follows:
21233 ** - 8 bytes: Magic identifying journal format.
21234 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
21235 ** - 4 bytes: Random number used for page hash.
21236 ** - 4 bytes: Initial database page count.
21237 ** - 4 bytes: Sector size used by the process that wrote this journal.
21238 ** 
21239 ** Followed by (JOURNAL_HDR_SZ - 24) bytes of unused space.
21240 */
21241 static int writeJournalHdr(Pager *pPager){
21242   char zHeader[sizeof(aJournalMagic)+16];
21243   int rc;
21244
21245   if( pPager->stmtHdrOff==0 ){
21246     pPager->stmtHdrOff = pPager->journalOff;
21247   }
21248
21249   seekJournalHdr(pPager);
21250   pPager->journalHdr = pPager->journalOff;
21251
21252   memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
21253
21254   /* 
21255   ** Write the nRec Field - the number of page records that follow this
21256   ** journal header. Normally, zero is written to this value at this time.
21257   ** After the records are added to the journal (and the journal synced, 
21258   ** if in full-sync mode), the zero is overwritten with the true number
21259   ** of records (see syncJournal()).
21260   **
21261   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
21262   ** reading the journal this value tells SQLite to assume that the
21263   ** rest of the journal file contains valid page records. This assumption
21264   ** is dangerous, as if a failure occured whilst writing to the journal
21265   ** file it may contain some garbage data. There are two scenarios
21266   ** where this risk can be ignored:
21267   **
21268   **   * When the pager is in no-sync mode. Corruption can follow a
21269   **     power failure in this case anyway.
21270   **
21271   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
21272   **     that garbage data is never appended to the journal file.
21273   */
21274   assert(pPager->fd->pMethods||pPager->noSync);
21275   if( (pPager->noSync) 
21276    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
21277   ){
21278     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
21279   }else{
21280     put32bits(&zHeader[sizeof(aJournalMagic)], 0);
21281   }
21282
21283   /* The random check-hash initialiser */ 
21284   sqlite3Randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
21285   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
21286   /* The initial database size */
21287   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbSize);
21288   /* The assumed sector size for this process */
21289   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
21290   IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, sizeof(zHeader)))
21291   rc = sqlite3OsWrite(pPager->jfd, zHeader, sizeof(zHeader),pPager->journalOff);
21292   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
21293
21294   /* The journal header has been written successfully. Seek the journal
21295   ** file descriptor to the end of the journal header sector.
21296   */
21297   if( rc==SQLITE_OK ){
21298     IOTRACE(("JTAIL %p %lld\n", pPager, pPager->journalOff-1))
21299     rc = sqlite3OsWrite(pPager->jfd, "\000", 1, pPager->journalOff-1);
21300   }
21301   return rc;
21302 }
21303
21304 /*
21305 ** The journal file must be open when this is called. A journal header file
21306 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
21307 ** file. See comments above function writeJournalHdr() for a description of
21308 ** the journal header format.
21309 **
21310 ** If the header is read successfully, *nRec is set to the number of
21311 ** page records following this header and *dbSize is set to the size of the
21312 ** database before the transaction began, in pages. Also, pPager->cksumInit
21313 ** is set to the value read from the journal header. SQLITE_OK is returned
21314 ** in this case.
21315 **
21316 ** If the journal header file appears to be corrupted, SQLITE_DONE is
21317 ** returned and *nRec and *dbSize are not set.  If JOURNAL_HDR_SZ bytes
21318 ** cannot be read from the journal file an error code is returned.
21319 */
21320 static int readJournalHdr(
21321   Pager *pPager, 
21322   i64 journalSize,
21323   u32 *pNRec, 
21324   u32 *pDbSize
21325 ){
21326   int rc;
21327   unsigned char aMagic[8]; /* A buffer to hold the magic header */
21328   i64 jrnlOff;
21329
21330   seekJournalHdr(pPager);
21331   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
21332     return SQLITE_DONE;
21333   }
21334   jrnlOff = pPager->journalOff;
21335
21336   rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), jrnlOff);
21337   if( rc ) return rc;
21338   jrnlOff += sizeof(aMagic);
21339
21340   if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
21341     return SQLITE_DONE;
21342   }
21343
21344   rc = read32bits(pPager->jfd, jrnlOff, pNRec);
21345   if( rc ) return rc;
21346
21347   rc = read32bits(pPager->jfd, jrnlOff+4, &pPager->cksumInit);
21348   if( rc ) return rc;
21349
21350   rc = read32bits(pPager->jfd, jrnlOff+8, pDbSize);
21351   if( rc ) return rc;
21352
21353   /* Update the assumed sector-size to match the value used by 
21354   ** the process that created this journal. If this journal was
21355   ** created by a process other than this one, then this routine
21356   ** is being called from within pager_playback(). The local value
21357   ** of Pager.sectorSize is restored at the end of that routine.
21358   */
21359   rc = read32bits(pPager->jfd, jrnlOff+12, (u32 *)&pPager->sectorSize);
21360   if( rc ) return rc;
21361
21362   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
21363   return SQLITE_OK;
21364 }
21365
21366
21367 /*
21368 ** Write the supplied master journal name into the journal file for pager
21369 ** pPager at the current location. The master journal name must be the last
21370 ** thing written to a journal file. If the pager is in full-sync mode, the
21371 ** journal file descriptor is advanced to the next sector boundary before
21372 ** anything is written. The format is:
21373 **
21374 ** + 4 bytes: PAGER_MJ_PGNO.
21375 ** + N bytes: length of master journal name.
21376 ** + 4 bytes: N
21377 ** + 4 bytes: Master journal name checksum.
21378 ** + 8 bytes: aJournalMagic[].
21379 **
21380 ** The master journal page checksum is the sum of the bytes in the master
21381 ** journal name.
21382 **
21383 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
21384 ** this call is a no-op.
21385 */
21386 static int writeMasterJournal(Pager *pPager, const char *zMaster){
21387   int rc;
21388   int len; 
21389   int i; 
21390   i64 jrnlOff;
21391   u32 cksum = 0;
21392   char zBuf[sizeof(aJournalMagic)+2*4];
21393
21394   if( !zMaster || pPager->setMaster) return SQLITE_OK;
21395   pPager->setMaster = 1;
21396
21397   len = strlen(zMaster);
21398   for(i=0; i<len; i++){
21399     cksum += zMaster[i];
21400   }
21401
21402   /* If in full-sync mode, advance to the next disk sector before writing
21403   ** the master journal name. This is in case the previous page written to
21404   ** the journal has already been synced.
21405   */
21406   if( pPager->fullSync ){
21407     seekJournalHdr(pPager);
21408   }
21409   jrnlOff = pPager->journalOff;
21410   pPager->journalOff += (len+20);
21411
21412   rc = write32bits(pPager->jfd, jrnlOff, PAGER_MJ_PGNO(pPager));
21413   if( rc!=SQLITE_OK ) return rc;
21414   jrnlOff += 4;
21415
21416   rc = sqlite3OsWrite(pPager->jfd, zMaster, len, jrnlOff);
21417   if( rc!=SQLITE_OK ) return rc;
21418   jrnlOff += len;
21419
21420   put32bits(zBuf, len);
21421   put32bits(&zBuf[4], cksum);
21422   memcpy(&zBuf[8], aJournalMagic, sizeof(aJournalMagic));
21423   rc = sqlite3OsWrite(pPager->jfd, zBuf, 8+sizeof(aJournalMagic), jrnlOff);
21424   pPager->needSync = !pPager->noSync;
21425   return rc;
21426 }
21427
21428 /*
21429 ** Add or remove a page from the list of all pages that are in the
21430 ** statement journal.
21431 **
21432 ** The Pager keeps a separate list of pages that are currently in
21433 ** the statement journal.  This helps the sqlite3PagerStmtCommit()
21434 ** routine run MUCH faster for the common case where there are many
21435 ** pages in memory but only a few are in the statement journal.
21436 */
21437 static void page_add_to_stmt_list(PgHdr *pPg){
21438   Pager *pPager = pPg->pPager;
21439   PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
21440   assert( MEMDB );
21441   if( !pHist->inStmt ){
21442     assert( pHist->pPrevStmt==0 && pHist->pNextStmt==0 );
21443     if( pPager->pStmt ){
21444       PGHDR_TO_HIST(pPager->pStmt, pPager)->pPrevStmt = pPg;
21445     }
21446     pHist->pNextStmt = pPager->pStmt;
21447     pPager->pStmt = pPg;
21448     pHist->inStmt = 1;
21449   }
21450 }
21451
21452 /*
21453 ** Find a page in the hash table given its page number.  Return
21454 ** a pointer to the page or NULL if not found.
21455 */
21456 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
21457   PgHdr *p;
21458   if( pPager->aHash==0 ) return 0;
21459   p = pPager->aHash[pgno & (pPager->nHash-1)];
21460   while( p && p->pgno!=pgno ){
21461     p = p->pNextHash;
21462   }
21463   return p;
21464 }
21465
21466 /*
21467 ** Clear the in-memory cache.  This routine
21468 ** sets the state of the pager back to what it was when it was first
21469 ** opened.  Any outstanding pages are invalidated and subsequent attempts
21470 ** to access those pages will likely result in a coredump.
21471 */
21472 static void pager_reset(Pager *pPager){
21473   PgHdr *pPg, *pNext;
21474   if( pPager->errCode ) return;
21475   for(pPg=pPager->pAll; pPg; pPg=pNext){
21476     IOTRACE(("PGFREE %p %d\n", pPager, pPg->pgno));
21477     PAGER_INCR(sqlite3_pager_pgfree_count);
21478     pNext = pPg->pNextAll;
21479     lruListRemove(pPg);
21480     sqlite3_free(pPg);
21481   }
21482   assert(pPager->lru.pFirst==0);
21483   assert(pPager->lru.pFirstSynced==0);
21484   assert(pPager->lru.pLast==0);
21485   pPager->pStmt = 0;
21486   pPager->pAll = 0;
21487   pPager->pDirty = 0;
21488   pPager->nHash = 0;
21489   sqlite3_free(pPager->aHash);
21490   pPager->nPage = 0;
21491   pPager->aHash = 0;
21492   pPager->nRef = 0;
21493 }
21494
21495 /*
21496 ** Unlock the database file. 
21497 **
21498 ** If the pager is currently in error state, discard the contents of 
21499 ** the cache and reset the Pager structure internal state. If there is
21500 ** an open journal-file, then the next time a shared-lock is obtained
21501 ** on the pager file (by this or any other process), it will be
21502 ** treated as a hot-journal and rolled back.
21503 */
21504 static void pager_unlock(Pager *pPager){
21505   if( !pPager->exclusiveMode ){
21506     if( !MEMDB ){
21507       if( pPager->fd->pMethods ){
21508         osUnlock(pPager->fd, NO_LOCK);
21509       }
21510       pPager->dbSize = -1;
21511       IOTRACE(("UNLOCK %p\n", pPager))
21512
21513       /* If Pager.errCode is set, the contents of the pager cache cannot be
21514       ** trusted. Now that the pager file is unlocked, the contents of the
21515       ** cache can be discarded and the error code safely cleared.
21516       */
21517       if( pPager->errCode ){
21518         pPager->errCode = SQLITE_OK;
21519         pager_reset(pPager);
21520         if( pPager->stmtOpen ){
21521           sqlite3OsClose(pPager->stfd);
21522           sqlite3_free(pPager->aInStmt);
21523           pPager->aInStmt = 0;
21524         }
21525         if( pPager->journalOpen ){
21526           sqlite3OsClose(pPager->jfd);
21527           pPager->journalOpen = 0;
21528           sqlite3_free(pPager->aInJournal);
21529           pPager->aInJournal = 0;
21530         }
21531         pPager->stmtOpen = 0;
21532         pPager->stmtInUse = 0;
21533         pPager->journalOff = 0;
21534         pPager->journalStarted = 0;
21535         pPager->stmtAutoopen = 0;
21536         pPager->origDbSize = 0;
21537       }
21538     }
21539
21540     if( !MEMDB || pPager->errCode==SQLITE_OK ){
21541       pPager->state = PAGER_UNLOCK;
21542       pPager->changeCountDone = 0;
21543     }
21544   }
21545 }
21546
21547 /*
21548 ** Execute a rollback if a transaction is active and unlock the 
21549 ** database file. If the pager has already entered the error state, 
21550 ** do not attempt the rollback.
21551 */
21552 static void pagerUnlockAndRollback(Pager *p){
21553   assert( p->state>=PAGER_RESERVED || p->journalOpen==0 );
21554   if( p->errCode==SQLITE_OK && p->state>=PAGER_RESERVED ){
21555     sqlite3PagerRollback(p);
21556   }
21557   pager_unlock(p);
21558   assert( p->errCode || !p->journalOpen || (p->exclusiveMode&&!p->journalOff) );
21559   assert( p->errCode || !p->stmtOpen || p->exclusiveMode );
21560 }
21561
21562 /*
21563 ** This routine ends a transaction.  A transaction is ended by either
21564 ** a COMMIT or a ROLLBACK.
21565 **
21566 ** When this routine is called, the pager has the journal file open and
21567 ** a RESERVED or EXCLUSIVE lock on the database.  This routine will release
21568 ** the database lock and acquires a SHARED lock in its place if that is
21569 ** the appropriate thing to do.  Release locks usually is appropriate,
21570 ** unless we are in exclusive access mode or unless this is a 
21571 ** COMMIT AND BEGIN or ROLLBACK AND BEGIN operation.
21572 **
21573 ** The journal file is either deleted or truncated.
21574 **
21575 ** TODO: Consider keeping the journal file open for temporary databases.
21576 ** This might give a performance improvement on windows where opening
21577 ** a file is an expensive operation.
21578 */
21579 static int pager_end_transaction(Pager *pPager){
21580   PgHdr *pPg;
21581   int rc = SQLITE_OK;
21582   int rc2 = SQLITE_OK;
21583   assert( !MEMDB );
21584   if( pPager->state<PAGER_RESERVED ){
21585     return SQLITE_OK;
21586   }
21587   sqlite3PagerStmtCommit(pPager);
21588   if( pPager->stmtOpen && !pPager->exclusiveMode ){
21589     sqlite3OsClose(pPager->stfd);
21590     pPager->stmtOpen = 0;
21591   }
21592   if( pPager->journalOpen ){
21593     if( pPager->exclusiveMode 
21594           && (rc = sqlite3OsTruncate(pPager->jfd, 0))==SQLITE_OK ){;
21595       pPager->journalOff = 0;
21596       pPager->journalStarted = 0;
21597     }else{
21598       sqlite3OsClose(pPager->jfd);
21599       pPager->journalOpen = 0;
21600       if( rc==SQLITE_OK ){
21601         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
21602       }
21603     }
21604     sqlite3_free( pPager->aInJournal );
21605     pPager->aInJournal = 0;
21606     for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
21607       pPg->inJournal = 0;
21608       pPg->dirty = 0;
21609       pPg->needSync = 0;
21610       pPg->alwaysRollback = 0;
21611 #ifdef SQLITE_CHECK_PAGES
21612       pPg->pageHash = pager_pagehash(pPg);
21613 #endif
21614     }
21615     pPager->pDirty = 0;
21616     pPager->dirtyCache = 0;
21617     pPager->nRec = 0;
21618   }else{
21619     assert( pPager->aInJournal==0 );
21620     assert( pPager->dirtyCache==0 || pPager->useJournal==0 );
21621   }
21622
21623   if( !pPager->exclusiveMode ){
21624     rc2 = osUnlock(pPager->fd, SHARED_LOCK);
21625     pPager->state = PAGER_SHARED;
21626   }else if( pPager->state==PAGER_SYNCED ){
21627     pPager->state = PAGER_EXCLUSIVE;
21628   }
21629   pPager->origDbSize = 0;
21630   pPager->setMaster = 0;
21631   pPager->needSync = 0;
21632   lruListSetFirstSynced(pPager);
21633   pPager->dbSize = -1;
21634
21635   return (rc==SQLITE_OK?rc2:rc);
21636 }
21637
21638 /*
21639 ** Compute and return a checksum for the page of data.
21640 **
21641 ** This is not a real checksum.  It is really just the sum of the 
21642 ** random initial value and the page number.  We experimented with
21643 ** a checksum of the entire data, but that was found to be too slow.
21644 **
21645 ** Note that the page number is stored at the beginning of data and
21646 ** the checksum is stored at the end.  This is important.  If journal
21647 ** corruption occurs due to a power failure, the most likely scenario
21648 ** is that one end or the other of the record will be changed.  It is
21649 ** much less likely that the two ends of the journal record will be
21650 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
21651 ** though fast and simple, catches the mostly likely kind of corruption.
21652 **
21653 ** FIX ME:  Consider adding every 200th (or so) byte of the data to the
21654 ** checksum.  That way if a single page spans 3 or more disk sectors and
21655 ** only the middle sector is corrupt, we will still have a reasonable
21656 ** chance of failing the checksum and thus detecting the problem.
21657 */
21658 static u32 pager_cksum(Pager *pPager, const u8 *aData){
21659   u32 cksum = pPager->cksumInit;
21660   int i = pPager->pageSize-200;
21661   while( i>0 ){
21662     cksum += aData[i];
21663     i -= 200;
21664   }
21665   return cksum;
21666 }
21667
21668 /* Forward declaration */
21669 static void makeClean(PgHdr*);
21670
21671 /*
21672 ** Read a single page from the journal file opened on file descriptor
21673 ** jfd.  Playback this one page.
21674 **
21675 ** If useCksum==0 it means this journal does not use checksums.  Checksums
21676 ** are not used in statement journals because statement journals do not
21677 ** need to survive power failures.
21678 */
21679 static int pager_playback_one_page(
21680   Pager *pPager, 
21681   sqlite3_file *jfd,
21682   i64 offset,
21683   int useCksum
21684 ){
21685   int rc;
21686   PgHdr *pPg;                   /* An existing page in the cache */
21687   Pgno pgno;                    /* The page number of a page in journal */
21688   u32 cksum;                    /* Checksum used for sanity checking */
21689   u8 *aData = (u8 *)pPager->pTmpSpace;   /* Temp storage for a page */
21690
21691   /* useCksum should be true for the main journal and false for
21692   ** statement journals.  Verify that this is always the case
21693   */
21694   assert( jfd == (useCksum ? pPager->jfd : pPager->stfd) );
21695   assert( aData );
21696
21697   rc = read32bits(jfd, offset, &pgno);
21698   if( rc!=SQLITE_OK ) return rc;
21699   rc = sqlite3OsRead(jfd, aData, pPager->pageSize, offset+4);
21700   if( rc!=SQLITE_OK ) return rc;
21701   pPager->journalOff += pPager->pageSize + 4;
21702
21703   /* Sanity checking on the page.  This is more important that I originally
21704   ** thought.  If a power failure occurs while the journal is being written,
21705   ** it could cause invalid data to be written into the journal.  We need to
21706   ** detect this invalid data (with high probability) and ignore it.
21707   */
21708   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
21709     return SQLITE_DONE;
21710   }
21711   if( pgno>(unsigned)pPager->dbSize ){
21712     return SQLITE_OK;
21713   }
21714   if( useCksum ){
21715     rc = read32bits(jfd, offset+pPager->pageSize+4, &cksum);
21716     if( rc ) return rc;
21717     pPager->journalOff += 4;
21718     if( pager_cksum(pPager, aData)!=cksum ){
21719       return SQLITE_DONE;
21720     }
21721   }
21722
21723   assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
21724
21725   /* If the pager is in RESERVED state, then there must be a copy of this
21726   ** page in the pager cache. In this case just update the pager cache,
21727   ** not the database file. The page is left marked dirty in this case.
21728   **
21729   ** An exception to the above rule: If the database is in no-sync mode
21730   ** and a page is moved during an incremental vacuum then the page may
21731   ** not be in the pager cache. Later: if a malloc() or IO error occurs
21732   ** during a Movepage() call, then the page may not be in the cache
21733   ** either. So the condition described in the above paragraph is not
21734   ** assert()able.
21735   **
21736   ** If in EXCLUSIVE state, then we update the pager cache if it exists
21737   ** and the main file. The page is then marked not dirty.
21738   **
21739   ** Ticket #1171:  The statement journal might contain page content that is
21740   ** different from the page content at the start of the transaction.
21741   ** This occurs when a page is changed prior to the start of a statement
21742   ** then changed again within the statement.  When rolling back such a
21743   ** statement we must not write to the original database unless we know
21744   ** for certain that original page contents are synced into the main rollback
21745   ** journal.  Otherwise, a power loss might leave modified data in the
21746   ** database file without an entry in the rollback journal that can
21747   ** restore the database to its original form.  Two conditions must be
21748   ** met before writing to the database files. (1) the database must be
21749   ** locked.  (2) we know that the original page content is fully synced
21750   ** in the main journal either because the page is not in cache or else
21751   ** the page is marked as needSync==0.
21752   */
21753   pPg = pager_lookup(pPager, pgno);
21754   PAGERTRACE4("PLAYBACK %d page %d hash(%08x)\n",
21755                PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, aData));
21756   if( pPager->state>=PAGER_EXCLUSIVE && (pPg==0 || pPg->needSync==0) ){
21757     i64 offset = (pgno-1)*(i64)pPager->pageSize;
21758     rc = sqlite3OsWrite(pPager->fd, aData, pPager->pageSize, offset);
21759     if( pPg ){
21760       makeClean(pPg);
21761     }
21762   }
21763   if( pPg ){
21764     /* No page should ever be explicitly rolled back that is in use, except
21765     ** for page 1 which is held in use in order to keep the lock on the
21766     ** database active. However such a page may be rolled back as a result
21767     ** of an internal error resulting in an automatic call to
21768     ** sqlite3PagerRollback().
21769     */
21770     void *pData;
21771     /* assert( pPg->nRef==0 || pPg->pgno==1 ); */
21772     pData = PGHDR_TO_DATA(pPg);
21773     memcpy(pData, aData, pPager->pageSize);
21774     if( pPager->xReiniter ){
21775       pPager->xReiniter(pPg, pPager->pageSize);
21776     }
21777 #ifdef SQLITE_CHECK_PAGES
21778     pPg->pageHash = pager_pagehash(pPg);
21779 #endif
21780     /* If this was page 1, then restore the value of Pager.dbFileVers.
21781     ** Do this before any decoding. */
21782     if( pgno==1 ){
21783       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
21784     }
21785
21786     /* Decode the page just read from disk */
21787     CODEC1(pPager, pData, pPg->pgno, 3);
21788   }
21789   return rc;
21790 }
21791
21792 /*
21793 ** Parameter zMaster is the name of a master journal file. A single journal
21794 ** file that referred to the master journal file has just been rolled back.
21795 ** This routine checks if it is possible to delete the master journal file,
21796 ** and does so if it is.
21797 **
21798 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
21799 ** available for use within this function.
21800 **
21801 **
21802 ** The master journal file contains the names of all child journals.
21803 ** To tell if a master journal can be deleted, check to each of the
21804 ** children.  If all children are either missing or do not refer to
21805 ** a different master journal, then this master journal can be deleted.
21806 */
21807 static int pager_delmaster(Pager *pPager, const char *zMaster){
21808   sqlite3_vfs *pVfs = pPager->pVfs;
21809   int rc;
21810   int master_open = 0;
21811   sqlite3_file *pMaster;
21812   sqlite3_file *pJournal;
21813   char *zMasterJournal = 0; /* Contents of master journal file */
21814   i64 nMasterJournal;       /* Size of master journal file */
21815
21816   /* Open the master journal file exclusively in case some other process
21817   ** is running this routine also. Not that it makes too much difference.
21818   */
21819   pMaster = (sqlite3_file *)sqlite3_malloc(pVfs->szOsFile * 2);
21820   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
21821   if( !pMaster ){
21822     rc = SQLITE_NOMEM;
21823   }else{
21824     int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
21825     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
21826   }
21827   if( rc!=SQLITE_OK ) goto delmaster_out;
21828   master_open = 1;
21829
21830   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
21831   if( rc!=SQLITE_OK ) goto delmaster_out;
21832
21833   if( nMasterJournal>0 ){
21834     char *zJournal;
21835     char *zMasterPtr = 0;
21836     int nMasterPtr = pPager->pVfs->mxPathname+1;
21837
21838     /* Load the entire master journal file into space obtained from
21839     ** sqlite3_malloc() and pointed to by zMasterJournal. 
21840     */
21841     zMasterJournal = (char *)sqlite3_malloc(nMasterJournal + nMasterPtr);
21842     if( !zMasterJournal ){
21843       rc = SQLITE_NOMEM;
21844       goto delmaster_out;
21845     }
21846     zMasterPtr = &zMasterJournal[nMasterJournal];
21847     rc = sqlite3OsRead(pMaster, zMasterJournal, nMasterJournal, 0);
21848     if( rc!=SQLITE_OK ) goto delmaster_out;
21849
21850     zJournal = zMasterJournal;
21851     while( (zJournal-zMasterJournal)<nMasterJournal ){
21852       if( sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS) ){
21853         /* One of the journals pointed to by the master journal exists.
21854         ** Open it and check if it points at the master journal. If
21855         ** so, return without deleting the master journal file.
21856         */
21857         int c;
21858         int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
21859         rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
21860         if( rc!=SQLITE_OK ){
21861           goto delmaster_out;
21862         }
21863
21864         rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
21865         sqlite3OsClose(pJournal);
21866         if( rc!=SQLITE_OK ){
21867           goto delmaster_out;
21868         }
21869
21870         c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
21871         if( c ){
21872           /* We have a match. Do not delete the master journal file. */
21873           goto delmaster_out;
21874         }
21875       }
21876       zJournal += (strlen(zJournal)+1);
21877     }
21878   }
21879   
21880   rc = sqlite3OsDelete(pVfs, zMaster, 0);
21881
21882 delmaster_out:
21883   if( zMasterJournal ){
21884     sqlite3_free(zMasterJournal);
21885   }  
21886   if( master_open ){
21887     sqlite3OsClose(pMaster);
21888   }
21889   sqlite3_free(pMaster);
21890   return rc;
21891 }
21892
21893
21894 static void pager_truncate_cache(Pager *pPager);
21895
21896 /*
21897 ** Truncate the main file of the given pager to the number of pages
21898 ** indicated. Also truncate the cached representation of the file.
21899 **
21900 ** Might might be the case that the file on disk is smaller than nPage.
21901 ** This can happen, for example, if we are in the middle of a transaction
21902 ** which has extended the file size and the new pages are still all held
21903 ** in cache, then an INSERT or UPDATE does a statement rollback.  Some
21904 ** operating system implementations can get confused if you try to
21905 ** truncate a file to some size that is larger than it currently is,
21906 ** so detect this case and do not do the truncation.
21907 */
21908 static int pager_truncate(Pager *pPager, int nPage){
21909   int rc = SQLITE_OK;
21910   if( pPager->state>=PAGER_EXCLUSIVE && pPager->fd->pMethods ){
21911     i64 currentSize, newSize;
21912     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
21913     newSize = pPager->pageSize*(i64)nPage;
21914     if( rc==SQLITE_OK && currentSize>newSize ){
21915       rc = sqlite3OsTruncate(pPager->fd, newSize);
21916     }
21917   }
21918   if( rc==SQLITE_OK ){
21919     pPager->dbSize = nPage;
21920     pager_truncate_cache(pPager);
21921   }
21922   return rc;
21923 }
21924
21925 /*
21926 ** Set the sectorSize for the given pager.
21927 **
21928 ** The sector size is the larger of the sector size reported
21929 ** by sqlite3OsSectorSize() and the pageSize.
21930 */
21931 static void setSectorSize(Pager *pPager){
21932   assert(pPager->fd->pMethods||pPager->tempFile);
21933   if( !pPager->tempFile ){
21934     /* Sector size doesn't matter for temporary files. Also, the file
21935     ** may not have been opened yet, in whcih case the OsSectorSize()
21936     ** call will segfault.
21937     */
21938     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
21939   }
21940   if( pPager->sectorSize<pPager->pageSize ){
21941     pPager->sectorSize = pPager->pageSize;
21942   }
21943 }
21944
21945 /*
21946 ** Playback the journal and thus restore the database file to
21947 ** the state it was in before we started making changes.  
21948 **
21949 ** The journal file format is as follows: 
21950 **
21951 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
21952 **  (2)  4 byte big-endian integer which is the number of valid page records
21953 **       in the journal.  If this value is 0xffffffff, then compute the
21954 **       number of page records from the journal size.
21955 **  (3)  4 byte big-endian integer which is the initial value for the 
21956 **       sanity checksum.
21957 **  (4)  4 byte integer which is the number of pages to truncate the
21958 **       database to during a rollback.
21959 **  (5)  4 byte integer which is the number of bytes in the master journal
21960 **       name.  The value may be zero (indicate that there is no master
21961 **       journal.)
21962 **  (6)  N bytes of the master journal name.  The name will be nul-terminated
21963 **       and might be shorter than the value read from (5).  If the first byte
21964 **       of the name is \000 then there is no master journal.  The master
21965 **       journal name is stored in UTF-8.
21966 **  (7)  Zero or more pages instances, each as follows:
21967 **        +  4 byte page number.
21968 **        +  pPager->pageSize bytes of data.
21969 **        +  4 byte checksum
21970 **
21971 ** When we speak of the journal header, we mean the first 6 items above.
21972 ** Each entry in the journal is an instance of the 7th item.
21973 **
21974 ** Call the value from the second bullet "nRec".  nRec is the number of
21975 ** valid page entries in the journal.  In most cases, you can compute the
21976 ** value of nRec from the size of the journal file.  But if a power
21977 ** failure occurred while the journal was being written, it could be the
21978 ** case that the size of the journal file had already been increased but
21979 ** the extra entries had not yet made it safely to disk.  In such a case,
21980 ** the value of nRec computed from the file size would be too large.  For
21981 ** that reason, we always use the nRec value in the header.
21982 **
21983 ** If the nRec value is 0xffffffff it means that nRec should be computed
21984 ** from the file size.  This value is used when the user selects the
21985 ** no-sync option for the journal.  A power failure could lead to corruption
21986 ** in this case.  But for things like temporary table (which will be
21987 ** deleted when the power is restored) we don't care.  
21988 **
21989 ** If the file opened as the journal file is not a well-formed
21990 ** journal file then all pages up to the first corrupted page are rolled
21991 ** back (or no pages if the journal header is corrupted). The journal file
21992 ** is then deleted and SQLITE_OK returned, just as if no corruption had
21993 ** been encountered.
21994 **
21995 ** If an I/O or malloc() error occurs, the journal-file is not deleted
21996 ** and an error code is returned.
21997 */
21998 static int pager_playback(Pager *pPager, int isHot){
21999   sqlite3_vfs *pVfs = pPager->pVfs;
22000   i64 szJ;                 /* Size of the journal file in bytes */
22001   u32 nRec;                /* Number of Records in the journal */
22002   int i;                   /* Loop counter */
22003   Pgno mxPg = 0;           /* Size of the original file in pages */
22004   int rc;                  /* Result code of a subroutine */
22005   char *zMaster = 0;       /* Name of master journal file if any */
22006
22007   /* Figure out how many records are in the journal.  Abort early if
22008   ** the journal is empty.
22009   */
22010   assert( pPager->journalOpen );
22011   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
22012   if( rc!=SQLITE_OK || szJ==0 ){
22013     goto end_playback;
22014   }
22015
22016   /* Read the master journal name from the journal, if it is present.
22017   ** If a master journal file name is specified, but the file is not
22018   ** present on disk, then the journal is not hot and does not need to be
22019   ** played back.
22020   */
22021   zMaster = pPager->pTmpSpace;
22022   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
22023   assert( rc!=SQLITE_DONE );
22024   if( rc!=SQLITE_OK 
22025    || (zMaster[0] && !sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS)) 
22026   ){
22027     zMaster = 0;
22028     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
22029     goto end_playback;
22030   }
22031   pPager->journalOff = 0;
22032   zMaster = 0;
22033
22034   /* This loop terminates either when the readJournalHdr() call returns
22035   ** SQLITE_DONE or an IO error occurs. */
22036   while( 1 ){
22037
22038     /* Read the next journal header from the journal file.  If there are
22039     ** not enough bytes left in the journal file for a complete header, or
22040     ** it is corrupted, then a process must of failed while writing it.
22041     ** This indicates nothing more needs to be rolled back.
22042     */
22043     rc = readJournalHdr(pPager, szJ, &nRec, &mxPg);
22044     if( rc!=SQLITE_OK ){ 
22045       if( rc==SQLITE_DONE ){
22046         rc = SQLITE_OK;
22047       }
22048       goto end_playback;
22049     }
22050
22051     /* If nRec is 0xffffffff, then this journal was created by a process
22052     ** working in no-sync mode. This means that the rest of the journal
22053     ** file consists of pages, there are no more journal headers. Compute
22054     ** the value of nRec based on this assumption.
22055     */
22056     if( nRec==0xffffffff ){
22057       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
22058       nRec = (szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager);
22059     }
22060
22061     /* If nRec is 0 and this rollback is of a transaction created by this
22062     ** process and if this is the final header in the journal, then it means
22063     ** that this part of the journal was being filled but has not yet been
22064     ** synced to disk.  Compute the number of pages based on the remaining
22065     ** size of the file.
22066     **
22067     ** The third term of the test was added to fix ticket #2565.
22068     */
22069     if( nRec==0 && !isHot &&
22070         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
22071       nRec = (szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager);
22072     }
22073
22074     /* If this is the first header read from the journal, truncate the
22075     ** database file back to its original size.
22076     */
22077     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
22078       rc = pager_truncate(pPager, mxPg);
22079       if( rc!=SQLITE_OK ){
22080         goto end_playback;
22081       }
22082     }
22083
22084     /* Copy original pages out of the journal and back into the database file.
22085     */
22086     for(i=0; i<nRec; i++){
22087       rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
22088       if( rc!=SQLITE_OK ){
22089         if( rc==SQLITE_DONE ){
22090           rc = SQLITE_OK;
22091           pPager->journalOff = szJ;
22092           break;
22093         }else{
22094           goto end_playback;
22095         }
22096       }
22097     }
22098   }
22099   /*NOTREACHED*/
22100   assert( 0 );
22101
22102 end_playback:
22103   if( rc==SQLITE_OK ){
22104     zMaster = pPager->pTmpSpace;
22105     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
22106   }
22107   if( rc==SQLITE_OK ){
22108     rc = pager_end_transaction(pPager);
22109   }
22110   if( rc==SQLITE_OK && zMaster[0] ){
22111     /* If there was a master journal and this routine will return success,
22112     ** see if it is possible to delete the master journal.
22113     */
22114     rc = pager_delmaster(pPager, zMaster);
22115   }
22116
22117   /* The Pager.sectorSize variable may have been updated while rolling
22118   ** back a journal created by a process with a different sector size
22119   ** value. Reset it to the correct value for this process.
22120   */
22121   setSectorSize(pPager);
22122   return rc;
22123 }
22124
22125 /*
22126 ** Playback the statement journal.
22127 **
22128 ** This is similar to playing back the transaction journal but with
22129 ** a few extra twists.
22130 **
22131 **    (1)  The number of pages in the database file at the start of
22132 **         the statement is stored in pPager->stmtSize, not in the
22133 **         journal file itself.
22134 **
22135 **    (2)  In addition to playing back the statement journal, also
22136 **         playback all pages of the transaction journal beginning
22137 **         at offset pPager->stmtJSize.
22138 */
22139 static int pager_stmt_playback(Pager *pPager){
22140   i64 szJ;                 /* Size of the full journal */
22141   i64 hdrOff;
22142   int nRec;                /* Number of Records */
22143   int i;                   /* Loop counter */
22144   int rc;
22145
22146   szJ = pPager->journalOff;
22147 #ifndef NDEBUG 
22148   {
22149     i64 os_szJ;
22150     rc = sqlite3OsFileSize(pPager->jfd, &os_szJ);
22151     if( rc!=SQLITE_OK ) return rc;
22152     assert( szJ==os_szJ );
22153   }
22154 #endif
22155
22156   /* Set hdrOff to be the offset just after the end of the last journal
22157   ** page written before the first journal-header for this statement
22158   ** transaction was written, or the end of the file if no journal
22159   ** header was written.
22160   */
22161   hdrOff = pPager->stmtHdrOff;
22162   assert( pPager->fullSync || !hdrOff );
22163   if( !hdrOff ){
22164     hdrOff = szJ;
22165   }
22166   
22167   /* Truncate the database back to its original size.
22168   */
22169   rc = pager_truncate(pPager, pPager->stmtSize);
22170   assert( pPager->state>=PAGER_SHARED );
22171
22172   /* Figure out how many records are in the statement journal.
22173   */
22174   assert( pPager->stmtInUse && pPager->journalOpen );
22175   nRec = pPager->stmtNRec;
22176   
22177   /* Copy original pages out of the statement journal and back into the
22178   ** database file.  Note that the statement journal omits checksums from
22179   ** each record since power-failure recovery is not important to statement
22180   ** journals.
22181   */
22182   for(i=0; i<nRec; i++){
22183     i64 offset = i*(4+pPager->pageSize);
22184     rc = pager_playback_one_page(pPager, pPager->stfd, offset, 0);
22185     assert( rc!=SQLITE_DONE );
22186     if( rc!=SQLITE_OK ) goto end_stmt_playback;
22187   }
22188
22189   /* Now roll some pages back from the transaction journal. Pager.stmtJSize
22190   ** was the size of the journal file when this statement was started, so
22191   ** everything after that needs to be rolled back, either into the
22192   ** database, the memory cache, or both.
22193   **
22194   ** If it is not zero, then Pager.stmtHdrOff is the offset to the start
22195   ** of the first journal header written during this statement transaction.
22196   */
22197   pPager->journalOff = pPager->stmtJSize;
22198   pPager->cksumInit = pPager->stmtCksum;
22199   while( pPager->journalOff < hdrOff ){
22200     rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
22201     assert( rc!=SQLITE_DONE );
22202     if( rc!=SQLITE_OK ) goto end_stmt_playback;
22203   }
22204
22205   while( pPager->journalOff < szJ ){
22206     u32 nJRec;         /* Number of Journal Records */
22207     u32 dummy;
22208     rc = readJournalHdr(pPager, szJ, &nJRec, &dummy);
22209     if( rc!=SQLITE_OK ){
22210       assert( rc!=SQLITE_DONE );
22211       goto end_stmt_playback;
22212     }
22213     if( nJRec==0 ){
22214       nJRec = (szJ - pPager->journalOff) / (pPager->pageSize+8);
22215     }
22216     for(i=nJRec-1; i>=0 && pPager->journalOff < szJ; i--){
22217       rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
22218       assert( rc!=SQLITE_DONE );
22219       if( rc!=SQLITE_OK ) goto end_stmt_playback;
22220     }
22221   }
22222
22223   pPager->journalOff = szJ;
22224   
22225 end_stmt_playback:
22226   if( rc==SQLITE_OK) {
22227     pPager->journalOff = szJ;
22228     /* pager_reload_cache(pPager); */
22229   }
22230   return rc;
22231 }
22232
22233 /*
22234 ** Change the maximum number of in-memory pages that are allowed.
22235 */
22236 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
22237   if( mxPage>10 ){
22238     pPager->mxPage = mxPage;
22239   }else{
22240     pPager->mxPage = 10;
22241   }
22242 }
22243
22244 /*
22245 ** Adjust the robustness of the database to damage due to OS crashes
22246 ** or power failures by changing the number of syncs()s when writing
22247 ** the rollback journal.  There are three levels:
22248 **
22249 **    OFF       sqlite3OsSync() is never called.  This is the default
22250 **              for temporary and transient files.
22251 **
22252 **    NORMAL    The journal is synced once before writes begin on the
22253 **              database.  This is normally adequate protection, but
22254 **              it is theoretically possible, though very unlikely,
22255 **              that an inopertune power failure could leave the journal
22256 **              in a state which would cause damage to the database
22257 **              when it is rolled back.
22258 **
22259 **    FULL      The journal is synced twice before writes begin on the
22260 **              database (with some additional information - the nRec field
22261 **              of the journal header - being written in between the two
22262 **              syncs).  If we assume that writing a
22263 **              single disk sector is atomic, then this mode provides
22264 **              assurance that the journal will not be corrupted to the
22265 **              point of causing damage to the database during rollback.
22266 **
22267 ** Numeric values associated with these states are OFF==1, NORMAL=2,
22268 ** and FULL=3.
22269 */
22270 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
22271 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int full_fsync){
22272   pPager->noSync =  level==1 || pPager->tempFile;
22273   pPager->fullSync = level==3 && !pPager->tempFile;
22274   pPager->sync_flags = (full_fsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
22275   if( pPager->noSync ) pPager->needSync = 0;
22276 }
22277 #endif
22278
22279 /*
22280 ** The following global variable is incremented whenever the library
22281 ** attempts to open a temporary file.  This information is used for
22282 ** testing and analysis only.  
22283 */
22284 #ifdef SQLITE_TEST
22285 SQLITE_API int sqlite3_opentemp_count = 0;
22286 #endif
22287
22288 /*
22289 ** Open a temporary file. 
22290 **
22291 ** Write the file descriptor into *fd.  Return SQLITE_OK on success or some
22292 ** other error code if we fail. The OS will automatically delete the temporary
22293 ** file when it is closed.
22294 */
22295 static int sqlite3PagerOpentemp(
22296   sqlite3_vfs *pVfs,    /* The virtual file system layer */
22297   sqlite3_file *pFile,  /* Write the file descriptor here */
22298   char *zFilename,      /* Name of the file.  Might be NULL */
22299   int vfsFlags          /* Flags passed through to the VFS */
22300 ){
22301   int rc;
22302   assert( zFilename!=0 );
22303
22304 #ifdef SQLITE_TEST
22305   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
22306 #endif
22307
22308   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
22309             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
22310   rc = sqlite3OsOpen(pVfs, zFilename, pFile, vfsFlags, 0);
22311   assert( rc!=SQLITE_OK || pFile->pMethods );
22312   return rc;
22313 }
22314
22315 /*
22316 ** Create a new page cache and put a pointer to the page cache in *ppPager.
22317 ** The file to be cached need not exist.  The file is not locked until
22318 ** the first call to sqlite3PagerGet() and is only held open until the
22319 ** last page is released using sqlite3PagerUnref().
22320 **
22321 ** If zFilename is NULL then a randomly-named temporary file is created
22322 ** and used as the file to be cached.  The file will be deleted
22323 ** automatically when it is closed.
22324 **
22325 ** If zFilename is ":memory:" then all information is held in cache.
22326 ** It is never written to disk.  This can be used to implement an
22327 ** in-memory database.
22328 */
22329 SQLITE_PRIVATE int sqlite3PagerOpen(
22330   sqlite3_vfs *pVfs,       /* The virtual file system to use */
22331   Pager **ppPager,         /* Return the Pager structure here */
22332   const char *zFilename,   /* Name of the database file to open */
22333   int nExtra,              /* Extra bytes append to each in-memory page */
22334   int flags,               /* flags controlling this file */
22335   int vfsFlags             /* flags passed through to sqlite3_vfs.xOpen() */
22336 ){
22337   u8 *pPtr;
22338   Pager *pPager = 0;
22339   int rc = SQLITE_OK;
22340   int i;
22341   int tempFile = 0;
22342   int memDb = 0;
22343   int readOnly = 0;
22344   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0;
22345   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;
22346   int journalFileSize = sqlite3JournalSize(pVfs);
22347   int nDefaultPage = SQLITE_DEFAULT_PAGE_SIZE;
22348   char *zPathname;
22349   int nPathname;
22350
22351   /* The default return is a NULL pointer */
22352   *ppPager = 0;
22353
22354   /* Compute the full pathname */
22355   nPathname = pVfs->mxPathname+1;
22356   zPathname = sqlite3_malloc(nPathname);
22357   if( zPathname==0 ){
22358     return SQLITE_NOMEM;
22359   }
22360   if( zFilename && zFilename[0] ){
22361 #ifndef SQLITE_OMIT_MEMORYDB
22362     if( strcmp(zFilename,":memory:")==0 ){
22363       memDb = 1;
22364       zPathname[0] = 0;
22365     }else
22366 #endif
22367     {
22368       rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
22369     }
22370   }else{
22371     rc = sqlite3OsGetTempname(pVfs, nPathname, zPathname);
22372   }
22373   if( rc!=SQLITE_OK ){
22374     sqlite3_free(zPathname);
22375     return rc;
22376   }
22377   nPathname = strlen(zPathname);
22378
22379   /* Allocate memory for the pager structure */
22380   pPager = sqlite3MallocZero(
22381     sizeof(*pPager) +           /* Pager structure */
22382     journalFileSize +           /* The journal file structure */ 
22383     pVfs->szOsFile * 2 +        /* The db and stmt journal files */ 
22384     4*nPathname + 40            /* zFilename, zDirectory, zJournal, zStmtJrnl */
22385   );
22386   if( !pPager ){
22387     sqlite3_free(zPathname);
22388     return SQLITE_NOMEM;
22389   }
22390   pPtr = (u8 *)&pPager[1];
22391   pPager->vfsFlags = vfsFlags;
22392   pPager->fd = (sqlite3_file*)&pPtr[pVfs->szOsFile*0];
22393   pPager->stfd = (sqlite3_file*)&pPtr[pVfs->szOsFile*1];
22394   pPager->jfd = (sqlite3_file*)&pPtr[pVfs->szOsFile*2];
22395   pPager->zFilename = (char*)&pPtr[pVfs->szOsFile*2+journalFileSize];
22396   pPager->zDirectory = &pPager->zFilename[nPathname+1];
22397   pPager->zJournal = &pPager->zDirectory[nPathname+1];
22398   pPager->zStmtJrnl = &pPager->zJournal[nPathname+10];
22399   pPager->pVfs = pVfs;
22400   memcpy(pPager->zFilename, zPathname, nPathname+1);
22401   sqlite3_free(zPathname);
22402
22403   /* Open the pager file.
22404   */
22405   if( zFilename && zFilename[0] && !memDb ){
22406     if( nPathname>(pVfs->mxPathname - sizeof("-journal")) ){
22407       rc = SQLITE_CANTOPEN;
22408     }else{
22409       int fout = 0;
22410       rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd,
22411                          pPager->vfsFlags, &fout);
22412       readOnly = (fout&SQLITE_OPEN_READONLY);
22413
22414       /* If the file was successfully opened for read/write access,
22415       ** choose a default page size in case we have to create the
22416       ** database file. The default page size is the maximum of:
22417       **
22418       **    + SQLITE_DEFAULT_PAGE_SIZE,
22419       **    + The value returned by sqlite3OsSectorSize()
22420       **    + The largest page size that can be written atomically.
22421       */
22422       if( rc==SQLITE_OK && !readOnly ){
22423         int iSectorSize = sqlite3OsSectorSize(pPager->fd);
22424         if( nDefaultPage<iSectorSize ){
22425           nDefaultPage = iSectorSize;
22426         }
22427 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
22428         {
22429           int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
22430           int ii;
22431           assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
22432           assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
22433           assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
22434           for(ii=nDefaultPage; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
22435             if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ) nDefaultPage = ii;
22436           }
22437         }
22438 #endif
22439         if( nDefaultPage>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
22440           nDefaultPage = SQLITE_MAX_DEFAULT_PAGE_SIZE;
22441         }
22442       }
22443     }
22444   }else if( !memDb ){
22445     /* If a temporary file is requested, it is not opened immediately.
22446     ** In this case we accept the default page size and delay actually
22447     ** opening the file until the first call to OsWrite().
22448     */ 
22449     tempFile = 1;
22450     pPager->state = PAGER_EXCLUSIVE;
22451   }
22452
22453   if( pPager && rc==SQLITE_OK ){
22454     pPager->pTmpSpace = (char *)sqlite3_malloc(nDefaultPage);
22455   }
22456
22457   /* If an error occured in either of the blocks above.
22458   ** Free the Pager structure and close the file.
22459   ** Since the pager is not allocated there is no need to set 
22460   ** any Pager.errMask variables.
22461   */
22462   if( !pPager || !pPager->pTmpSpace ){
22463     sqlite3OsClose(pPager->fd);
22464     sqlite3_free(pPager);
22465     return ((rc==SQLITE_OK)?SQLITE_NOMEM:rc);
22466   }
22467
22468   PAGERTRACE3("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename);
22469   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
22470
22471   /* Fill in Pager.zDirectory[] */
22472   memcpy(pPager->zDirectory, pPager->zFilename, nPathname+1);
22473   for(i=strlen(pPager->zDirectory); i>0 && pPager->zDirectory[i-1]!='/'; i--){}
22474   if( i>0 ) pPager->zDirectory[i-1] = 0;
22475
22476   /* Fill in Pager.zJournal[] and Pager.zStmtJrnl[] */
22477   memcpy(pPager->zJournal, pPager->zFilename, nPathname);
22478   memcpy(&pPager->zJournal[nPathname], "-journal", 9);
22479   memcpy(pPager->zStmtJrnl, pPager->zFilename, nPathname);
22480   memcpy(&pPager->zStmtJrnl[nPathname], "-stmtjrnl", 10);
22481
22482   /* pPager->journalOpen = 0; */
22483   pPager->useJournal = useJournal && !memDb;
22484   pPager->noReadlock = noReadlock && readOnly;
22485   /* pPager->stmtOpen = 0; */
22486   /* pPager->stmtInUse = 0; */
22487   /* pPager->nRef = 0; */
22488   pPager->dbSize = memDb-1;
22489   pPager->pageSize = nDefaultPage;
22490   /* pPager->stmtSize = 0; */
22491   /* pPager->stmtJSize = 0; */
22492   /* pPager->nPage = 0; */
22493   pPager->mxPage = 100;
22494   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
22495   /* pPager->state = PAGER_UNLOCK; */
22496   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
22497   /* pPager->errMask = 0; */
22498   pPager->tempFile = tempFile;
22499   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
22500           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
22501   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
22502   pPager->exclusiveMode = tempFile; 
22503   pPager->memDb = memDb;
22504   pPager->readOnly = readOnly;
22505   /* pPager->needSync = 0; */
22506   pPager->noSync = pPager->tempFile || !useJournal;
22507   pPager->fullSync = (pPager->noSync?0:1);
22508   pPager->sync_flags = SQLITE_SYNC_NORMAL;
22509   /* pPager->pFirst = 0; */
22510   /* pPager->pFirstSynced = 0; */
22511   /* pPager->pLast = 0; */
22512   pPager->nExtra = FORCE_ALIGNMENT(nExtra);
22513   assert(pPager->fd->pMethods||memDb||tempFile);
22514   if( !memDb ){
22515     setSectorSize(pPager);
22516   }
22517   /* pPager->pBusyHandler = 0; */
22518   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
22519   *ppPager = pPager;
22520 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
22521   pPager->iInUseMM = 0;
22522   pPager->iInUseDB = 0;
22523   if( !memDb ){
22524     sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM2);
22525     sqlite3_mutex_enter(mutex);
22526     pPager->pNext = sqlite3PagerList;
22527     if( sqlite3PagerList ){
22528       assert( sqlite3PagerList->pPrev==0 );
22529       sqlite3PagerList->pPrev = pPager;
22530     }
22531     pPager->pPrev = 0;
22532     sqlite3PagerList = pPager;
22533     sqlite3_mutex_leave(mutex);
22534   }
22535 #endif
22536   return SQLITE_OK;
22537 }
22538
22539 /*
22540 ** Set the busy handler function.
22541 */
22542 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager *pPager, BusyHandler *pBusyHandler){
22543   pPager->pBusyHandler = pBusyHandler;
22544 }
22545
22546 /*
22547 ** Set the destructor for this pager.  If not NULL, the destructor is called
22548 ** when the reference count on each page reaches zero.  The destructor can
22549 ** be used to clean up information in the extra segment appended to each page.
22550 **
22551 ** The destructor is not called as a result sqlite3PagerClose().  
22552 ** Destructors are only called by sqlite3PagerUnref().
22553 */
22554 SQLITE_PRIVATE void sqlite3PagerSetDestructor(Pager *pPager, void (*xDesc)(DbPage*,int)){
22555   pPager->xDestructor = xDesc;
22556 }
22557
22558 /*
22559 ** Set the reinitializer for this pager.  If not NULL, the reinitializer
22560 ** is called when the content of a page in cache is restored to its original
22561 ** value as a result of a rollback.  The callback gives higher-level code
22562 ** an opportunity to restore the EXTRA section to agree with the restored
22563 ** page data.
22564 */
22565 SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager *pPager, void (*xReinit)(DbPage*,int)){
22566   pPager->xReiniter = xReinit;
22567 }
22568
22569 /*
22570 ** Set the page size to *pPageSize. If the suggest new page size is
22571 ** inappropriate, then an alternative page size is set to that
22572 ** value before returning.
22573 */
22574 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize){
22575   int rc = SQLITE_OK;
22576   u16 pageSize = *pPageSize;
22577   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
22578   if( pageSize && pageSize!=pPager->pageSize 
22579    && !pPager->memDb && pPager->nRef==0 
22580   ){
22581     char *pNew = (char *)sqlite3_malloc(pageSize);
22582     if( !pNew ){
22583       rc = SQLITE_NOMEM;
22584     }else{
22585       pagerEnter(pPager);
22586       pager_reset(pPager);
22587       pPager->pageSize = pageSize;
22588       setSectorSize(pPager);
22589       sqlite3_free(pPager->pTmpSpace);
22590       pPager->pTmpSpace = pNew;
22591       pagerLeave(pPager);
22592     }
22593   }
22594   *pPageSize = pPager->pageSize;
22595   return rc;
22596 }
22597
22598 /*
22599 ** Return a pointer to the "temporary page" buffer held internally
22600 ** by the pager.  This is a buffer that is big enough to hold the
22601 ** entire content of a database page.  This buffer is used internally
22602 ** during rollback and will be overwritten whenever a rollback
22603 ** occurs.  But other modules are free to use it too, as long as
22604 ** no rollbacks are happening.
22605 */
22606 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
22607   return pPager->pTmpSpace;
22608 }
22609
22610 /*
22611 ** Attempt to set the maximum database page count if mxPage is positive. 
22612 ** Make no changes if mxPage is zero or negative.  And never reduce the
22613 ** maximum page count below the current size of the database.
22614 **
22615 ** Regardless of mxPage, return the current maximum page count.
22616 */
22617 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
22618   if( mxPage>0 ){
22619     pPager->mxPgno = mxPage;
22620   }
22621   sqlite3PagerPagecount(pPager);
22622   return pPager->mxPgno;
22623 }
22624
22625 /*
22626 ** The following set of routines are used to disable the simulated
22627 ** I/O error mechanism.  These routines are used to avoid simulated
22628 ** errors in places where we do not care about errors.
22629 **
22630 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
22631 ** and generate no code.
22632 */
22633 #ifdef SQLITE_TEST
22634 SQLITE_API extern int sqlite3_io_error_pending;
22635 SQLITE_API extern int sqlite3_io_error_hit;
22636 static int saved_cnt;
22637 void disable_simulated_io_errors(void){
22638   saved_cnt = sqlite3_io_error_pending;
22639   sqlite3_io_error_pending = -1;
22640 }
22641 void enable_simulated_io_errors(void){
22642   sqlite3_io_error_pending = saved_cnt;
22643 }
22644 #else
22645 # define disable_simulated_io_errors()
22646 # define enable_simulated_io_errors()
22647 #endif
22648
22649 /*
22650 ** Read the first N bytes from the beginning of the file into memory
22651 ** that pDest points to. 
22652 **
22653 ** No error checking is done. The rational for this is that this function 
22654 ** may be called even if the file does not exist or contain a header. In 
22655 ** these cases sqlite3OsRead() will return an error, to which the correct 
22656 ** response is to zero the memory at pDest and continue.  A real IO error 
22657 ** will presumably recur and be picked up later (Todo: Think about this).
22658 */
22659 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
22660   int rc = SQLITE_OK;
22661   memset(pDest, 0, N);
22662   assert(MEMDB||pPager->fd->pMethods||pPager->tempFile);
22663   if( pPager->fd->pMethods ){
22664     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
22665     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
22666     if( rc==SQLITE_IOERR_SHORT_READ ){
22667       rc = SQLITE_OK;
22668     }
22669   }
22670   return rc;
22671 }
22672
22673 /*
22674 ** Return the total number of pages in the disk file associated with
22675 ** pPager. 
22676 **
22677 ** If the PENDING_BYTE lies on the page directly after the end of the
22678 ** file, then consider this page part of the file too. For example, if
22679 ** PENDING_BYTE is byte 4096 (the first byte of page 5) and the size of the
22680 ** file is 4096 bytes, 5 is returned instead of 4.
22681 */
22682 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager){
22683   i64 n = 0;
22684   int rc;
22685   assert( pPager!=0 );
22686   if( pPager->errCode ){
22687     return 0;
22688   }
22689   if( pPager->dbSize>=0 ){
22690     n = pPager->dbSize;
22691   } else {
22692     assert(pPager->fd->pMethods||pPager->tempFile);
22693     if( (pPager->fd->pMethods)
22694      && (rc = sqlite3OsFileSize(pPager->fd, &n))!=SQLITE_OK ){
22695       pPager->nRef++;
22696       pager_error(pPager, rc);
22697       pPager->nRef--;
22698       return 0;
22699     }
22700     if( n>0 && n<pPager->pageSize ){
22701       n = 1;
22702     }else{
22703       n /= pPager->pageSize;
22704     }
22705     if( pPager->state!=PAGER_UNLOCK ){
22706       pPager->dbSize = n;
22707     }
22708   }
22709   if( n==(PENDING_BYTE/pPager->pageSize) ){
22710     n++;
22711   }
22712   if( n>pPager->mxPgno ){
22713     pPager->mxPgno = n;
22714   }
22715   return n;
22716 }
22717
22718
22719 #ifndef SQLITE_OMIT_MEMORYDB
22720 /*
22721 ** Clear a PgHistory block
22722 */
22723 static void clearHistory(PgHistory *pHist){
22724   sqlite3_free(pHist->pOrig);
22725   sqlite3_free(pHist->pStmt);
22726   pHist->pOrig = 0;
22727   pHist->pStmt = 0;
22728 }
22729 #else
22730 #define clearHistory(x)
22731 #endif
22732
22733 /*
22734 ** Forward declaration
22735 */
22736 static int syncJournal(Pager*);
22737
22738 /*
22739 ** Unlink pPg from its hash chain. Also set the page number to 0 to indicate
22740 ** that the page is not part of any hash chain. This is required because the
22741 ** sqlite3PagerMovepage() routine can leave a page in the 
22742 ** pNextFree/pPrevFree list that is not a part of any hash-chain.
22743 */
22744 static void unlinkHashChain(Pager *pPager, PgHdr *pPg){
22745   if( pPg->pgno==0 ){
22746     assert( pPg->pNextHash==0 && pPg->pPrevHash==0 );
22747     return;
22748   }
22749   if( pPg->pNextHash ){
22750     pPg->pNextHash->pPrevHash = pPg->pPrevHash;
22751   }
22752   if( pPg->pPrevHash ){
22753     assert( pPager->aHash[pPg->pgno & (pPager->nHash-1)]!=pPg );
22754     pPg->pPrevHash->pNextHash = pPg->pNextHash;
22755   }else{
22756     int h = pPg->pgno & (pPager->nHash-1);
22757     pPager->aHash[h] = pPg->pNextHash;
22758   }
22759   if( MEMDB ){
22760     clearHistory(PGHDR_TO_HIST(pPg, pPager));
22761   }
22762   pPg->pgno = 0;
22763   pPg->pNextHash = pPg->pPrevHash = 0;
22764 }
22765
22766 /*
22767 ** Unlink a page from the free list (the list of all pages where nRef==0)
22768 ** and from its hash collision chain.
22769 */
22770 static void unlinkPage(PgHdr *pPg){
22771   Pager *pPager = pPg->pPager;
22772
22773   /* Unlink from free page list */
22774   lruListRemove(pPg);
22775
22776   /* Unlink from the pgno hash table */
22777   unlinkHashChain(pPager, pPg);
22778 }
22779
22780 /*
22781 ** This routine is used to truncate the cache when a database
22782 ** is truncated.  Drop from the cache all pages whose pgno is
22783 ** larger than pPager->dbSize and is unreferenced.
22784 **
22785 ** Referenced pages larger than pPager->dbSize are zeroed.
22786 **
22787 ** Actually, at the point this routine is called, it would be
22788 ** an error to have a referenced page.  But rather than delete
22789 ** that page and guarantee a subsequent segfault, it seems better
22790 ** to zero it and hope that we error out sanely.
22791 */
22792 static void pager_truncate_cache(Pager *pPager){
22793   PgHdr *pPg;
22794   PgHdr **ppPg;
22795   int dbSize = pPager->dbSize;
22796
22797   ppPg = &pPager->pAll;
22798   while( (pPg = *ppPg)!=0 ){
22799     if( pPg->pgno<=dbSize ){
22800       ppPg = &pPg->pNextAll;
22801     }else if( pPg->nRef>0 ){
22802       memset(PGHDR_TO_DATA(pPg), 0, pPager->pageSize);
22803       ppPg = &pPg->pNextAll;
22804     }else{
22805       *ppPg = pPg->pNextAll;
22806       IOTRACE(("PGFREE %p %d\n", pPager, pPg->pgno));
22807       PAGER_INCR(sqlite3_pager_pgfree_count);
22808       unlinkPage(pPg);
22809       makeClean(pPg);
22810       sqlite3_free(pPg);
22811       pPager->nPage--;
22812     }
22813   }
22814 }
22815
22816 /*
22817 ** Try to obtain a lock on a file.  Invoke the busy callback if the lock
22818 ** is currently not available.  Repeat until the busy callback returns
22819 ** false or until the lock succeeds.
22820 **
22821 ** Return SQLITE_OK on success and an error code if we cannot obtain
22822 ** the lock.
22823 */
22824 static int pager_wait_on_lock(Pager *pPager, int locktype){
22825   int rc;
22826
22827   /* The OS lock values must be the same as the Pager lock values */
22828   assert( PAGER_SHARED==SHARED_LOCK );
22829   assert( PAGER_RESERVED==RESERVED_LOCK );
22830   assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
22831
22832   /* If the file is currently unlocked then the size must be unknown */
22833   assert( pPager->state>=PAGER_SHARED || pPager->dbSize<0 || MEMDB );
22834
22835   if( pPager->state>=locktype ){
22836     rc = SQLITE_OK;
22837   }else{
22838     do {
22839       rc = sqlite3OsLock(pPager->fd, locktype);
22840     }while( rc==SQLITE_BUSY && sqlite3InvokeBusyHandler(pPager->pBusyHandler) );
22841     if( rc==SQLITE_OK ){
22842       pPager->state = locktype;
22843       IOTRACE(("LOCK %p %d\n", pPager, locktype))
22844     }
22845   }
22846   return rc;
22847 }
22848
22849 /*
22850 ** Truncate the file to the number of pages specified.
22851 */
22852 SQLITE_PRIVATE int sqlite3PagerTruncate(Pager *pPager, Pgno nPage){
22853   int rc;
22854   assert( pPager->state>=PAGER_SHARED || MEMDB );
22855   sqlite3PagerPagecount(pPager);
22856   if( pPager->errCode ){
22857     rc = pPager->errCode;
22858     return rc;
22859   }
22860   if( nPage>=(unsigned)pPager->dbSize ){
22861     return SQLITE_OK;
22862   }
22863   if( MEMDB ){
22864     pPager->dbSize = nPage;
22865     pager_truncate_cache(pPager);
22866     return SQLITE_OK;
22867   }
22868   pagerEnter(pPager);
22869   rc = syncJournal(pPager);
22870   pagerLeave(pPager);
22871   if( rc!=SQLITE_OK ){
22872     return rc;
22873   }
22874
22875   /* Get an exclusive lock on the database before truncating. */
22876   pagerEnter(pPager);
22877   rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
22878   pagerLeave(pPager);
22879   if( rc!=SQLITE_OK ){
22880     return rc;
22881   }
22882
22883   rc = pager_truncate(pPager, nPage);
22884   return rc;
22885 }
22886
22887 /*
22888 ** Shutdown the page cache.  Free all memory and close all files.
22889 **
22890 ** If a transaction was in progress when this routine is called, that
22891 ** transaction is rolled back.  All outstanding pages are invalidated
22892 ** and their memory is freed.  Any attempt to use a page associated
22893 ** with this page cache after this function returns will likely
22894 ** result in a coredump.
22895 **
22896 ** This function always succeeds. If a transaction is active an attempt
22897 ** is made to roll it back. If an error occurs during the rollback 
22898 ** a hot journal may be left in the filesystem but no error is returned
22899 ** to the caller.
22900 */
22901 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
22902 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
22903   if( !MEMDB ){
22904     sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM2);
22905     sqlite3_mutex_enter(mutex);
22906     if( pPager->pPrev ){
22907       pPager->pPrev->pNext = pPager->pNext;
22908     }else{
22909       sqlite3PagerList = pPager->pNext;
22910     }
22911     if( pPager->pNext ){
22912       pPager->pNext->pPrev = pPager->pPrev;
22913     }
22914     sqlite3_mutex_leave(mutex);
22915   }
22916 #endif
22917
22918   disable_simulated_io_errors();
22919   pPager->errCode = 0;
22920   pPager->exclusiveMode = 0;
22921   pager_reset(pPager);
22922   pagerUnlockAndRollback(pPager);
22923   enable_simulated_io_errors();
22924   PAGERTRACE2("CLOSE %d\n", PAGERID(pPager));
22925   IOTRACE(("CLOSE %p\n", pPager))
22926   assert( pPager->errCode || (pPager->journalOpen==0 && pPager->stmtOpen==0) );
22927   if( pPager->journalOpen ){
22928     sqlite3OsClose(pPager->jfd);
22929   }
22930   sqlite3_free(pPager->aInJournal);
22931   if( pPager->stmtOpen ){
22932     sqlite3OsClose(pPager->stfd);
22933   }
22934   sqlite3OsClose(pPager->fd);
22935   /* Temp files are automatically deleted by the OS
22936   ** if( pPager->tempFile ){
22937   **   sqlite3OsDelete(pPager->zFilename);
22938   ** }
22939   */
22940
22941   sqlite3_free(pPager->aHash);
22942   sqlite3_free(pPager->pTmpSpace);
22943   sqlite3_free(pPager);
22944   return SQLITE_OK;
22945 }
22946
22947 #if !defined(NDEBUG) || defined(SQLITE_TEST)
22948 /*
22949 ** Return the page number for the given page data.
22950 */
22951 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *p){
22952   return p->pgno;
22953 }
22954 #endif
22955
22956 /*
22957 ** The page_ref() function increments the reference count for a page.
22958 ** If the page is currently on the freelist (the reference count is zero) then
22959 ** remove it from the freelist.
22960 **
22961 ** For non-test systems, page_ref() is a macro that calls _page_ref()
22962 ** online of the reference count is zero.  For test systems, page_ref()
22963 ** is a real function so that we can set breakpoints and trace it.
22964 */
22965 static void _page_ref(PgHdr *pPg){
22966   if( pPg->nRef==0 ){
22967     /* The page is currently on the freelist.  Remove it. */
22968     lruListRemove(pPg);
22969     pPg->pPager->nRef++;
22970   }
22971   pPg->nRef++;
22972   REFINFO(pPg);
22973 }
22974 #ifdef SQLITE_DEBUG
22975   static void page_ref(PgHdr *pPg){
22976     if( pPg->nRef==0 ){
22977       _page_ref(pPg);
22978     }else{
22979       pPg->nRef++;
22980       REFINFO(pPg);
22981     }
22982   }
22983 #else
22984 # define page_ref(P)   ((P)->nRef==0?_page_ref(P):(void)(P)->nRef++)
22985 #endif
22986
22987 /*
22988 ** Increment the reference count for a page.  The input pointer is
22989 ** a reference to the page data.
22990 */
22991 SQLITE_PRIVATE int sqlite3PagerRef(DbPage *pPg){
22992   pagerEnter(pPg->pPager);
22993   page_ref(pPg);
22994   pagerLeave(pPg->pPager);
22995   return SQLITE_OK;
22996 }
22997
22998 /*
22999 ** Sync the journal.  In other words, make sure all the pages that have
23000 ** been written to the journal have actually reached the surface of the
23001 ** disk.  It is not safe to modify the original database file until after
23002 ** the journal has been synced.  If the original database is modified before
23003 ** the journal is synced and a power failure occurs, the unsynced journal
23004 ** data would be lost and we would be unable to completely rollback the
23005 ** database changes.  Database corruption would occur.
23006 ** 
23007 ** This routine also updates the nRec field in the header of the journal.
23008 ** (See comments on the pager_playback() routine for additional information.)
23009 ** If the sync mode is FULL, two syncs will occur.  First the whole journal
23010 ** is synced, then the nRec field is updated, then a second sync occurs.
23011 **
23012 ** For temporary databases, we do not care if we are able to rollback
23013 ** after a power failure, so no sync occurs.
23014 **
23015 ** If the IOCAP_SEQUENTIAL flag is set for the persistent media on which
23016 ** the database is stored, then OsSync() is never called on the journal
23017 ** file. In this case all that is required is to update the nRec field in
23018 ** the journal header.
23019 **
23020 ** This routine clears the needSync field of every page current held in
23021 ** memory.
23022 */
23023 static int syncJournal(Pager *pPager){
23024   PgHdr *pPg;
23025   int rc = SQLITE_OK;
23026
23027
23028   /* Sync the journal before modifying the main database
23029   ** (assuming there is a journal and it needs to be synced.)
23030   */
23031   if( pPager->needSync ){
23032     if( !pPager->tempFile ){
23033       int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
23034       assert( pPager->journalOpen );
23035
23036       /* assert( !pPager->noSync ); // noSync might be set if synchronous
23037       ** was turned off after the transaction was started.  Ticket #615 */
23038 #ifndef NDEBUG
23039       {
23040         /* Make sure the pPager->nRec counter we are keeping agrees
23041         ** with the nRec computed from the size of the journal file.
23042         */
23043         i64 jSz;
23044         rc = sqlite3OsFileSize(pPager->jfd, &jSz);
23045         if( rc!=0 ) return rc;
23046         assert( pPager->journalOff==jSz );
23047       }
23048 #endif
23049       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
23050         /* Write the nRec value into the journal file header. If in
23051         ** full-synchronous mode, sync the journal first. This ensures that
23052         ** all data has really hit the disk before nRec is updated to mark
23053         ** it as a candidate for rollback.
23054         **
23055         ** This is not required if the persistent media supports the
23056         ** SAFE_APPEND property. Because in this case it is not possible 
23057         ** for garbage data to be appended to the file, the nRec field
23058         ** is populated with 0xFFFFFFFF when the journal header is written
23059         ** and never needs to be updated.
23060         */
23061         i64 jrnlOff;
23062         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
23063           PAGERTRACE2("SYNC journal of %d\n", PAGERID(pPager));
23064           IOTRACE(("JSYNC %p\n", pPager))
23065           rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
23066           if( rc!=0 ) return rc;
23067         }
23068
23069         jrnlOff = pPager->journalHdr + sizeof(aJournalMagic);
23070         IOTRACE(("JHDR %p %lld %d\n", pPager, jrnlOff, 4));
23071         rc = write32bits(pPager->jfd, jrnlOff, pPager->nRec);
23072         if( rc ) return rc;
23073       }
23074       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
23075         PAGERTRACE2("SYNC journal of %d\n", PAGERID(pPager));
23076         IOTRACE(("JSYNC %p\n", pPager))
23077         rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags| 
23078           (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
23079         );
23080         if( rc!=0 ) return rc;
23081       }
23082       pPager->journalStarted = 1;
23083     }
23084     pPager->needSync = 0;
23085
23086     /* Erase the needSync flag from every page.
23087     */
23088     for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
23089       pPg->needSync = 0;
23090     }
23091     lruListSetFirstSynced(pPager);
23092   }
23093
23094 #ifndef NDEBUG
23095   /* If the Pager.needSync flag is clear then the PgHdr.needSync
23096   ** flag must also be clear for all pages.  Verify that this
23097   ** invariant is true.
23098   */
23099   else{
23100     for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
23101       assert( pPg->needSync==0 );
23102     }
23103     assert( pPager->lru.pFirstSynced==pPager->lru.pFirst );
23104   }
23105 #endif
23106
23107   return rc;
23108 }
23109
23110 /*
23111 ** Merge two lists of pages connected by pDirty and in pgno order.
23112 ** Do not both fixing the pPrevDirty pointers.
23113 */
23114 static PgHdr *merge_pagelist(PgHdr *pA, PgHdr *pB){
23115   PgHdr result, *pTail;
23116   pTail = &result;
23117   while( pA && pB ){
23118     if( pA->pgno<pB->pgno ){
23119       pTail->pDirty = pA;
23120       pTail = pA;
23121       pA = pA->pDirty;
23122     }else{
23123       pTail->pDirty = pB;
23124       pTail = pB;
23125       pB = pB->pDirty;
23126     }
23127   }
23128   if( pA ){
23129     pTail->pDirty = pA;
23130   }else if( pB ){
23131     pTail->pDirty = pB;
23132   }else{
23133     pTail->pDirty = 0;
23134   }
23135   return result.pDirty;
23136 }
23137
23138 /*
23139 ** Sort the list of pages in accending order by pgno.  Pages are
23140 ** connected by pDirty pointers.  The pPrevDirty pointers are
23141 ** corrupted by this sort.
23142 */
23143 #define N_SORT_BUCKET_ALLOC 25
23144 #define N_SORT_BUCKET       25
23145 #ifdef SQLITE_TEST
23146   int sqlite3_pager_n_sort_bucket = 0;
23147   #undef N_SORT_BUCKET
23148   #define N_SORT_BUCKET \
23149    (sqlite3_pager_n_sort_bucket?sqlite3_pager_n_sort_bucket:N_SORT_BUCKET_ALLOC)
23150 #endif
23151 static PgHdr *sort_pagelist(PgHdr *pIn){
23152   PgHdr *a[N_SORT_BUCKET_ALLOC], *p;
23153   int i;
23154   memset(a, 0, sizeof(a));
23155   while( pIn ){
23156     p = pIn;
23157     pIn = p->pDirty;
23158     p->pDirty = 0;
23159     for(i=0; i<N_SORT_BUCKET-1; i++){
23160       if( a[i]==0 ){
23161         a[i] = p;
23162         break;
23163       }else{
23164         p = merge_pagelist(a[i], p);
23165         a[i] = 0;
23166       }
23167     }
23168     if( i==N_SORT_BUCKET-1 ){
23169       /* Coverage: To get here, there need to be 2^(N_SORT_BUCKET) 
23170       ** elements in the input list. This is possible, but impractical.
23171       ** Testing this line is the point of global variable
23172       ** sqlite3_pager_n_sort_bucket.
23173       */
23174       a[i] = merge_pagelist(a[i], p);
23175     }
23176   }
23177   p = a[0];
23178   for(i=1; i<N_SORT_BUCKET; i++){
23179     p = merge_pagelist(p, a[i]);
23180   }
23181   return p;
23182 }
23183
23184 /*
23185 ** Given a list of pages (connected by the PgHdr.pDirty pointer) write
23186 ** every one of those pages out to the database file and mark them all
23187 ** as clean.
23188 */
23189 static int pager_write_pagelist(PgHdr *pList){
23190   Pager *pPager;
23191   PgHdr *p;
23192   int rc;
23193
23194   if( pList==0 ) return SQLITE_OK;
23195   pPager = pList->pPager;
23196
23197   /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
23198   ** database file. If there is already an EXCLUSIVE lock, the following
23199   ** calls to sqlite3OsLock() are no-ops.
23200   **
23201   ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
23202   ** through an intermediate state PENDING.   A PENDING lock prevents new
23203   ** readers from attaching to the database but is unsufficient for us to
23204   ** write.  The idea of a PENDING lock is to prevent new readers from
23205   ** coming in while we wait for existing readers to clear.
23206   **
23207   ** While the pager is in the RESERVED state, the original database file
23208   ** is unchanged and we can rollback without having to playback the
23209   ** journal into the original database file.  Once we transition to
23210   ** EXCLUSIVE, it means the database file has been changed and any rollback
23211   ** will require a journal playback.
23212   */
23213   rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
23214   if( rc!=SQLITE_OK ){
23215     return rc;
23216   }
23217
23218   pList = sort_pagelist(pList);
23219   for(p=pList; p; p=p->pDirty){
23220     assert( p->dirty );
23221     p->dirty = 0;
23222   }
23223   while( pList ){
23224
23225     /* If the file has not yet been opened, open it now. */
23226     if( !pPager->fd->pMethods ){
23227       assert(pPager->tempFile);
23228       rc = sqlite3PagerOpentemp(pPager->pVfs, pPager->fd, pPager->zFilename,
23229                                 pPager->vfsFlags);
23230       if( rc ) return rc;
23231     }
23232
23233     /* If there are dirty pages in the page cache with page numbers greater
23234     ** than Pager.dbSize, this means sqlite3PagerTruncate() was called to
23235     ** make the file smaller (presumably by auto-vacuum code). Do not write
23236     ** any such pages to the file.
23237     */
23238     if( pList->pgno<=pPager->dbSize ){
23239       i64 offset = (pList->pgno-1)*(i64)pPager->pageSize;
23240       char *pData = CODEC2(pPager, PGHDR_TO_DATA(pList), pList->pgno, 6);
23241       PAGERTRACE4("STORE %d page %d hash(%08x)\n",
23242                    PAGERID(pPager), pList->pgno, pager_pagehash(pList));
23243       IOTRACE(("PGOUT %p %d\n", pPager, pList->pgno));
23244       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
23245       PAGER_INCR(sqlite3_pager_writedb_count);
23246       PAGER_INCR(pPager->nWrite);
23247       if( pList->pgno==1 ){
23248         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
23249       }
23250     }
23251 #ifndef NDEBUG
23252     else{
23253       PAGERTRACE3("NOSTORE %d page %d\n", PAGERID(pPager), pList->pgno);
23254     }
23255 #endif
23256     if( rc ) return rc;
23257 #ifdef SQLITE_CHECK_PAGES
23258     pList->pageHash = pager_pagehash(pList);
23259 #endif
23260     pList = pList->pDirty;
23261   }
23262   return SQLITE_OK;
23263 }
23264
23265 /*
23266 ** Collect every dirty page into a dirty list and
23267 ** return a pointer to the head of that list.  All pages are
23268 ** collected even if they are still in use.
23269 */
23270 static PgHdr *pager_get_all_dirty_pages(Pager *pPager){
23271   return pPager->pDirty;
23272 }
23273
23274 /*
23275 ** Return TRUE if there is a hot journal on the given pager.
23276 ** A hot journal is one that needs to be played back.
23277 **
23278 ** If the current size of the database file is 0 but a journal file
23279 ** exists, that is probably an old journal left over from a prior
23280 ** database with the same name.  Just delete the journal.
23281 */
23282 static int hasHotJournal(Pager *pPager){
23283   sqlite3_vfs *pVfs = pPager->pVfs;
23284   if( !pPager->useJournal ) return 0;
23285   if( !pPager->fd->pMethods ) return 0;
23286   if( !sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS) ){
23287     return 0;
23288   }
23289   if( sqlite3OsCheckReservedLock(pPager->fd) ){
23290     return 0;
23291   }
23292   if( sqlite3PagerPagecount(pPager)==0 ){
23293     sqlite3OsDelete(pVfs, pPager->zJournal, 0);
23294     return 0;
23295   }else{
23296     return 1;
23297   }
23298 }
23299
23300 /*
23301 ** Try to find a page in the cache that can be recycled. 
23302 **
23303 ** This routine may return SQLITE_IOERR, SQLITE_FULL or SQLITE_OK. It 
23304 ** does not set the pPager->errCode variable.
23305 */
23306 static int pager_recycle(Pager *pPager, PgHdr **ppPg){
23307   PgHdr *pPg;
23308   *ppPg = 0;
23309
23310   /* It is illegal to call this function unless the pager object
23311   ** pointed to by pPager has at least one free page (page with nRef==0).
23312   */ 
23313   assert(!MEMDB);
23314   assert(pPager->lru.pFirst);
23315
23316   /* Find a page to recycle.  Try to locate a page that does not
23317   ** require us to do an fsync() on the journal.
23318   */
23319   pPg = pPager->lru.pFirstSynced;
23320
23321   /* If we could not find a page that does not require an fsync()
23322   ** on the journal file then fsync the journal file.  This is a
23323   ** very slow operation, so we work hard to avoid it.  But sometimes
23324   ** it can't be helped.
23325   */
23326   if( pPg==0 && pPager->lru.pFirst){
23327     int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
23328     int rc = syncJournal(pPager);
23329     if( rc!=0 ){
23330       return rc;
23331     }
23332     if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
23333       /* If in full-sync mode, write a new journal header into the
23334       ** journal file. This is done to avoid ever modifying a journal
23335       ** header that is involved in the rollback of pages that have
23336       ** already been written to the database (in case the header is
23337       ** trashed when the nRec field is updated).
23338       */
23339       pPager->nRec = 0;
23340       assert( pPager->journalOff > 0 );
23341       assert( pPager->doNotSync==0 );
23342       rc = writeJournalHdr(pPager);
23343       if( rc!=0 ){
23344         return rc;
23345       }
23346     }
23347     pPg = pPager->lru.pFirst;
23348   }
23349
23350   assert( pPg->nRef==0 );
23351
23352   /* Write the page to the database file if it is dirty.
23353   */
23354   if( pPg->dirty ){
23355     int rc;
23356     assert( pPg->needSync==0 );
23357     makeClean(pPg);
23358     pPg->dirty = 1;
23359     pPg->pDirty = 0;
23360     rc = pager_write_pagelist( pPg );
23361     pPg->dirty = 0;
23362     if( rc!=SQLITE_OK ){
23363       return rc;
23364     }
23365   }
23366   assert( pPg->dirty==0 );
23367
23368   /* If the page we are recycling is marked as alwaysRollback, then
23369   ** set the global alwaysRollback flag, thus disabling the
23370   ** sqlite3PagerDontRollback() optimization for the rest of this transaction.
23371   ** It is necessary to do this because the page marked alwaysRollback
23372   ** might be reloaded at a later time but at that point we won't remember
23373   ** that is was marked alwaysRollback.  This means that all pages must
23374   ** be marked as alwaysRollback from here on out.
23375   */
23376   if( pPg->alwaysRollback ){
23377     IOTRACE(("ALWAYS_ROLLBACK %p\n", pPager))
23378     pPager->alwaysRollback = 1;
23379   }
23380
23381   /* Unlink the old page from the free list and the hash table
23382   */
23383   unlinkPage(pPg);
23384   assert( pPg->pgno==0 );
23385
23386   *ppPg = pPg;
23387   return SQLITE_OK;
23388 }
23389
23390 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
23391 /*
23392 ** This function is called to free superfluous dynamically allocated memory
23393 ** held by the pager system. Memory in use by any SQLite pager allocated
23394 ** by the current thread may be sqlite3_free()ed.
23395 **
23396 ** nReq is the number of bytes of memory required. Once this much has
23397 ** been released, the function returns. The return value is the total number 
23398 ** of bytes of memory released.
23399 */
23400 SQLITE_PRIVATE int sqlite3PagerReleaseMemory(int nReq){
23401   int nReleased = 0;          /* Bytes of memory released so far */
23402   sqlite3_mutex *mutex;       /* The MEM2 mutex */
23403   Pager *pPager;              /* For looping over pagers */
23404   BusyHandler *savedBusy;     /* Saved copy of the busy handler */
23405   int rc = SQLITE_OK;
23406
23407   /* Acquire the memory-management mutex
23408   */
23409   mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM2);
23410   sqlite3_mutex_enter(mutex);
23411
23412   /* Signal all database connections that memory management wants
23413   ** to have access to the pagers.
23414   */
23415   for(pPager=sqlite3PagerList; pPager; pPager=pPager->pNext){
23416      pPager->iInUseMM = 1;
23417   }
23418
23419   while( rc==SQLITE_OK && (nReq<0 || nReleased<nReq) ){
23420     PgHdr *pPg;
23421     PgHdr *pRecycled;
23422  
23423     /* Try to find a page to recycle that does not require a sync(). If
23424     ** this is not possible, find one that does require a sync().
23425     */
23426     sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
23427     pPg = sqlite3LruPageList.pFirstSynced;
23428     while( pPg && (pPg->needSync || pPg->pPager->iInUseDB) ){
23429       pPg = pPg->gfree.pNext;
23430     }
23431     if( !pPg ){
23432       pPg = sqlite3LruPageList.pFirst;
23433       while( pPg && pPg->pPager->iInUseDB ){
23434         pPg = pPg->gfree.pNext;
23435       }
23436     }
23437     sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
23438
23439     /* If pPg==0, then the block above has failed to find a page to
23440     ** recycle. In this case return early - no further memory will
23441     ** be released.
23442     */
23443     if( !pPg ) break;
23444
23445     pPager = pPg->pPager;
23446     assert(!pPg->needSync || pPg==pPager->lru.pFirst);
23447     assert(pPg->needSync || pPg==pPager->lru.pFirstSynced);
23448   
23449     savedBusy = pPager->pBusyHandler;
23450     pPager->pBusyHandler = 0;
23451     rc = pager_recycle(pPager, &pRecycled);
23452     pPager->pBusyHandler = savedBusy;
23453     assert(pRecycled==pPg || rc!=SQLITE_OK);
23454     if( rc==SQLITE_OK ){
23455       /* We've found a page to free. At this point the page has been 
23456       ** removed from the page hash-table, free-list and synced-list 
23457       ** (pFirstSynced). It is still in the all pages (pAll) list. 
23458       ** Remove it from this list before freeing.
23459       **
23460       ** Todo: Check the Pager.pStmt list to make sure this is Ok. It 
23461       ** probably is though.
23462       */
23463       PgHdr *pTmp;
23464       assert( pPg );
23465       if( pPg==pPager->pAll ){
23466          pPager->pAll = pPg->pNextAll;
23467       }else{
23468         for( pTmp=pPager->pAll; pTmp->pNextAll!=pPg; pTmp=pTmp->pNextAll ){}
23469         pTmp->pNextAll = pPg->pNextAll;
23470       }
23471       nReleased += (
23472           sizeof(*pPg) + pPager->pageSize
23473           + sizeof(u32) + pPager->nExtra
23474           + MEMDB*sizeof(PgHistory) 
23475       );
23476       IOTRACE(("PGFREE %p %d *\n", pPager, pPg->pgno));
23477       PAGER_INCR(sqlite3_pager_pgfree_count);
23478       sqlite3_free(pPg);
23479       pPager->nPage--;
23480     }else{
23481       /* An error occured whilst writing to the database file or 
23482       ** journal in pager_recycle(). The error is not returned to the 
23483       ** caller of this function. Instead, set the Pager.errCode variable.
23484       ** The error will be returned to the user (or users, in the case 
23485       ** of a shared pager cache) of the pager for which the error occured.
23486       */
23487       assert(
23488           (rc&0xff)==SQLITE_IOERR ||
23489           rc==SQLITE_FULL ||
23490           rc==SQLITE_BUSY
23491       );
23492       assert( pPager->state>=PAGER_RESERVED );
23493       pager_error(pPager, rc);
23494     }
23495   }
23496
23497   /* Clear the memory management flags and release the mutex
23498   */
23499   for(pPager=sqlite3PagerList; pPager; pPager=pPager->pNext){
23500      pPager->iInUseMM = 0;
23501   }
23502   sqlite3_mutex_leave(mutex);
23503
23504   /* Return the number of bytes released
23505   */
23506   return nReleased;
23507 }
23508 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
23509
23510 /*
23511 ** Read the content of page pPg out of the database file.
23512 */
23513 static int readDbPage(Pager *pPager, PgHdr *pPg, Pgno pgno){
23514   int rc;
23515   i64 offset;
23516   assert( MEMDB==0 );
23517   assert(pPager->fd->pMethods||pPager->tempFile);
23518   if( !pPager->fd->pMethods ){
23519     return SQLITE_IOERR_SHORT_READ;
23520   }
23521   offset = (pgno-1)*(i64)pPager->pageSize;
23522   rc = sqlite3OsRead(pPager->fd, PGHDR_TO_DATA(pPg), pPager->pageSize, offset);
23523   PAGER_INCR(sqlite3_pager_readdb_count);
23524   PAGER_INCR(pPager->nRead);
23525   IOTRACE(("PGIN %p %d\n", pPager, pgno));
23526   if( pgno==1 ){
23527     memcpy(&pPager->dbFileVers, &((u8*)PGHDR_TO_DATA(pPg))[24],
23528                                               sizeof(pPager->dbFileVers));
23529   }
23530   CODEC1(pPager, PGHDR_TO_DATA(pPg), pPg->pgno, 3);
23531   PAGERTRACE4("FETCH %d page %d hash(%08x)\n",
23532                PAGERID(pPager), pPg->pgno, pager_pagehash(pPg));
23533   return rc;
23534 }
23535
23536
23537 /*
23538 ** This function is called to obtain the shared lock required before
23539 ** data may be read from the pager cache. If the shared lock has already
23540 ** been obtained, this function is a no-op.
23541 **
23542 ** Immediately after obtaining the shared lock (if required), this function
23543 ** checks for a hot-journal file. If one is found, an emergency rollback
23544 ** is performed immediately.
23545 */
23546 static int pagerSharedLock(Pager *pPager){
23547   int rc = SQLITE_OK;
23548   int isHot = 0;
23549
23550   /* If this database is opened for exclusive access, has no outstanding 
23551   ** page references and is in an error-state, now is the chance to clear
23552   ** the error. Discard the contents of the pager-cache and treat any
23553   ** open journal file as a hot-journal.
23554   */
23555   if( !MEMDB && pPager->exclusiveMode && pPager->nRef==0 && pPager->errCode ){
23556     if( pPager->journalOpen ){
23557       isHot = 1;
23558     }
23559     pager_reset(pPager);
23560     pPager->errCode = SQLITE_OK;
23561   }
23562
23563   /* If the pager is still in an error state, do not proceed. The error 
23564   ** state will be cleared at some point in the future when all page 
23565   ** references are dropped and the cache can be discarded.
23566   */
23567   if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
23568     return pPager->errCode;
23569   }
23570
23571   if( pPager->state==PAGER_UNLOCK || isHot ){
23572     sqlite3_vfs *pVfs = pPager->pVfs;
23573     if( !MEMDB ){
23574       assert( pPager->nRef==0 );
23575       if( !pPager->noReadlock ){
23576         rc = pager_wait_on_lock(pPager, SHARED_LOCK);
23577         if( rc!=SQLITE_OK ){
23578           return pager_error(pPager, rc);
23579         }
23580         assert( pPager->state>=SHARED_LOCK );
23581       }
23582   
23583       /* If a journal file exists, and there is no RESERVED lock on the
23584       ** database file, then it either needs to be played back or deleted.
23585       */
23586       if( hasHotJournal(pPager) || isHot ){
23587         /* Get an EXCLUSIVE lock on the database file. At this point it is
23588         ** important that a RESERVED lock is not obtained on the way to the
23589         ** EXCLUSIVE lock. If it were, another process might open the
23590         ** database file, detect the RESERVED lock, and conclude that the
23591         ** database is safe to read while this process is still rolling it 
23592         ** back.
23593         ** 
23594         ** Because the intermediate RESERVED lock is not requested, the
23595         ** second process will get to this point in the code and fail to
23596         ** obtain its own EXCLUSIVE lock on the database file.
23597         */
23598         if( pPager->state<EXCLUSIVE_LOCK ){
23599           rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
23600           if( rc!=SQLITE_OK ){
23601             pager_unlock(pPager);
23602             return pager_error(pPager, rc);
23603           }
23604           pPager->state = PAGER_EXCLUSIVE;
23605         }
23606  
23607         /* Open the journal for reading only.  Return SQLITE_BUSY if
23608         ** we are unable to open the journal file. 
23609         **
23610         ** The journal file does not need to be locked itself.  The
23611         ** journal file is never open unless the main database file holds
23612         ** a write lock, so there is never any chance of two or more
23613         ** processes opening the journal at the same time.
23614         **
23615         ** Open the journal for read/write access. This is because in 
23616         ** exclusive-access mode the file descriptor will be kept open and
23617         ** possibly used for a transaction later on. On some systems, the
23618         ** OsTruncate() call used in exclusive-access mode also requires
23619         ** a read/write file handle.
23620         */
23621         if( !isHot ){
23622           rc = SQLITE_BUSY;
23623           if( sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS) ){
23624             int fout = 0;
23625             int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
23626             assert( !pPager->tempFile );
23627             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
23628             assert( rc!=SQLITE_OK || pPager->jfd->pMethods );
23629             if( fout&SQLITE_OPEN_READONLY ){
23630               rc = SQLITE_BUSY;
23631               sqlite3OsClose(pPager->jfd);
23632             }
23633           }
23634         }
23635         if( rc!=SQLITE_OK ){
23636           pager_unlock(pPager);
23637           return ((rc==SQLITE_NOMEM||rc==SQLITE_IOERR_NOMEM)?rc:SQLITE_BUSY);
23638         }
23639         pPager->journalOpen = 1;
23640         pPager->journalStarted = 0;
23641         pPager->journalOff = 0;
23642         pPager->setMaster = 0;
23643         pPager->journalHdr = 0;
23644  
23645         /* Playback and delete the journal.  Drop the database write
23646         ** lock and reacquire the read lock.
23647         */
23648         rc = pager_playback(pPager, 1);
23649         if( rc!=SQLITE_OK ){
23650           return pager_error(pPager, rc);
23651         }
23652         assert(pPager->state==PAGER_SHARED || 
23653             (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
23654         );
23655       }
23656
23657       if( pPager->pAll ){
23658         /* The shared-lock has just been acquired on the database file
23659         ** and there are already pages in the cache (from a previous
23660         ** read or write transaction).  Check to see if the database
23661         ** has been modified.  If the database has changed, flush the
23662         ** cache.
23663         **
23664         ** Database changes is detected by looking at 15 bytes beginning
23665         ** at offset 24 into the file.  The first 4 of these 16 bytes are
23666         ** a 32-bit counter that is incremented with each change.  The
23667         ** other bytes change randomly with each file change when
23668         ** a codec is in use.
23669         ** 
23670         ** There is a vanishingly small chance that a change will not be 
23671         ** detected.  The chance of an undetected change is so small that
23672         ** it can be neglected.
23673         */
23674         char dbFileVers[sizeof(pPager->dbFileVers)];
23675         sqlite3PagerPagecount(pPager);
23676
23677         if( pPager->errCode ){
23678           return pPager->errCode;
23679         }
23680
23681         if( pPager->dbSize>0 ){
23682           IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
23683           rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
23684           if( rc!=SQLITE_OK ){
23685             return rc;
23686           }
23687         }else{
23688           memset(dbFileVers, 0, sizeof(dbFileVers));
23689         }
23690
23691         if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
23692           pager_reset(pPager);
23693         }
23694       }
23695     }
23696     assert( pPager->exclusiveMode || pPager->state<=PAGER_SHARED );
23697     if( pPager->state==PAGER_UNLOCK ){
23698       pPager->state = PAGER_SHARED;
23699     }
23700   }
23701
23702   return rc;
23703 }
23704
23705 /*
23706 ** Allocate a PgHdr object.   Either create a new one or reuse
23707 ** an existing one that is not otherwise in use.
23708 **
23709 ** A new PgHdr structure is created if any of the following are
23710 ** true:
23711 **
23712 **     (1)  We have not exceeded our maximum allocated cache size
23713 **          as set by the "PRAGMA cache_size" command.
23714 **
23715 **     (2)  There are no unused PgHdr objects available at this time.
23716 **
23717 **     (3)  This is an in-memory database.
23718 **
23719 **     (4)  There are no PgHdr objects that do not require a journal
23720 **          file sync and a sync of the journal file is currently
23721 **          prohibited.
23722 **
23723 ** Otherwise, reuse an existing PgHdr.  In other words, reuse an
23724 ** existing PgHdr if all of the following are true:
23725 **
23726 **     (1)  We have reached or exceeded the maximum cache size
23727 **          allowed by "PRAGMA cache_size".
23728 **
23729 **     (2)  There is a PgHdr available with PgHdr->nRef==0
23730 **
23731 **     (3)  We are not in an in-memory database
23732 **
23733 **     (4)  Either there is an available PgHdr that does not need
23734 **          to be synced to disk or else disk syncing is currently
23735 **          allowed.
23736 */
23737 static int pagerAllocatePage(Pager *pPager, PgHdr **ppPg){
23738   int rc = SQLITE_OK;
23739   PgHdr *pPg;
23740   int nByteHdr;
23741
23742   /* Create a new PgHdr if any of the four conditions defined 
23743   ** above are met: */
23744   if( pPager->nPage<pPager->mxPage
23745    || pPager->lru.pFirst==0 
23746    || MEMDB
23747    || (pPager->lru.pFirstSynced==0 && pPager->doNotSync)
23748   ){
23749     if( pPager->nPage>=pPager->nHash ){
23750       pager_resize_hash_table(pPager,
23751          pPager->nHash<256 ? 256 : pPager->nHash*2);
23752       if( pPager->nHash==0 ){
23753         rc = SQLITE_NOMEM;
23754         goto pager_allocate_out;
23755       }
23756     }
23757     pagerLeave(pPager);
23758     nByteHdr = sizeof(*pPg) + sizeof(u32) + pPager->nExtra
23759               + MEMDB*sizeof(PgHistory);
23760     pPg = sqlite3_malloc( nByteHdr + pPager->pageSize );
23761     pagerEnter(pPager);
23762     if( pPg==0 ){
23763       rc = SQLITE_NOMEM;
23764       goto pager_allocate_out;
23765     }
23766     memset(pPg, 0, nByteHdr);
23767     pPg->pData = (void*)(nByteHdr + (char*)pPg);
23768     pPg->pPager = pPager;
23769     pPg->pNextAll = pPager->pAll;
23770     pPager->pAll = pPg;
23771     pPager->nPage++;
23772   }else{
23773     /* Recycle an existing page with a zero ref-count. */
23774     rc = pager_recycle(pPager, &pPg);
23775     if( rc==SQLITE_BUSY ){
23776       rc = SQLITE_IOERR_BLOCKED;
23777     }
23778     if( rc!=SQLITE_OK ){
23779       goto pager_allocate_out;
23780     }
23781     assert( pPager->state>=SHARED_LOCK );
23782     assert(pPg);
23783   }
23784   *ppPg = pPg;
23785
23786 pager_allocate_out:
23787   return rc;
23788 }
23789
23790 /*
23791 ** Make sure we have the content for a page.  If the page was
23792 ** previously acquired with noContent==1, then the content was
23793 ** just initialized to zeros instead of being read from disk.
23794 ** But now we need the real data off of disk.  So make sure we
23795 ** have it.  Read it in if we do not have it already.
23796 */
23797 static int pager_get_content(PgHdr *pPg){
23798   if( pPg->needRead ){
23799     int rc = readDbPage(pPg->pPager, pPg, pPg->pgno);
23800     if( rc==SQLITE_OK ){
23801       pPg->needRead = 0;
23802     }else{
23803       return rc;
23804     }
23805   }
23806   return SQLITE_OK;
23807 }
23808
23809 /*
23810 ** Acquire a page.
23811 **
23812 ** A read lock on the disk file is obtained when the first page is acquired. 
23813 ** This read lock is dropped when the last page is released.
23814 **
23815 ** This routine works for any page number greater than 0.  If the database
23816 ** file is smaller than the requested page, then no actual disk
23817 ** read occurs and the memory image of the page is initialized to
23818 ** all zeros.  The extra data appended to a page is always initialized
23819 ** to zeros the first time a page is loaded into memory.
23820 **
23821 ** The acquisition might fail for several reasons.  In all cases,
23822 ** an appropriate error code is returned and *ppPage is set to NULL.
23823 **
23824 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
23825 ** to find a page in the in-memory cache first.  If the page is not already
23826 ** in memory, this routine goes to disk to read it in whereas Lookup()
23827 ** just returns 0.  This routine acquires a read-lock the first time it
23828 ** has to go to disk, and could also playback an old journal if necessary.
23829 ** Since Lookup() never goes to disk, it never has to deal with locks
23830 ** or journal files.
23831 **
23832 ** If noContent is false, the page contents are actually read from disk.
23833 ** If noContent is true, it means that we do not care about the contents
23834 ** of the page at this time, so do not do a disk read.  Just fill in the
23835 ** page content with zeros.  But mark the fact that we have not read the
23836 ** content by setting the PgHdr.needRead flag.  Later on, if 
23837 ** sqlite3PagerWrite() is called on this page or if this routine is
23838 ** called again with noContent==0, that means that the content is needed
23839 ** and the disk read should occur at that point.
23840 */
23841 static int pagerAcquire(
23842   Pager *pPager,      /* The pager open on the database file */
23843   Pgno pgno,          /* Page number to fetch */
23844   DbPage **ppPage,    /* Write a pointer to the page here */
23845   int noContent       /* Do not bother reading content from disk if true */
23846 ){
23847   PgHdr *pPg;
23848   int rc;
23849
23850   assert( pPager->state==PAGER_UNLOCK || pPager->nRef>0 || pgno==1 );
23851
23852   /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
23853   ** number greater than this, or zero, is requested.
23854   */
23855   if( pgno>PAGER_MAX_PGNO || pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
23856     return SQLITE_CORRUPT_BKPT;
23857   }
23858
23859   /* Make sure we have not hit any critical errors.
23860   */ 
23861   assert( pPager!=0 );
23862   *ppPage = 0;
23863
23864   /* If this is the first page accessed, then get a SHARED lock
23865   ** on the database file. pagerSharedLock() is a no-op if 
23866   ** a database lock is already held.
23867   */
23868   rc = pagerSharedLock(pPager);
23869   if( rc!=SQLITE_OK ){
23870     return rc;
23871   }
23872   assert( pPager->state!=PAGER_UNLOCK );
23873
23874   pPg = pager_lookup(pPager, pgno);
23875   if( pPg==0 ){
23876     /* The requested page is not in the page cache. */
23877     int nMax;
23878     int h;
23879     PAGER_INCR(pPager->nMiss);
23880     rc = pagerAllocatePage(pPager, &pPg);
23881     if( rc!=SQLITE_OK ){
23882       return rc;
23883     }
23884
23885     pPg->pgno = pgno;
23886     assert( !MEMDB || pgno>pPager->stmtSize );
23887     if( pPager->aInJournal && (int)pgno<=pPager->origDbSize ){
23888 #if 0
23889       sqlite3CheckMemory(pPager->aInJournal, pgno/8);
23890 #endif
23891       assert( pPager->journalOpen );
23892       pPg->inJournal = (pPager->aInJournal[pgno/8] & (1<<(pgno&7)))!=0;
23893       pPg->needSync = 0;
23894     }else{
23895       pPg->inJournal = 0;
23896       pPg->needSync = 0;
23897     }
23898
23899     makeClean(pPg);
23900     pPg->nRef = 1;
23901     REFINFO(pPg);
23902
23903     pPager->nRef++;
23904     if( pPager->nExtra>0 ){
23905       memset(PGHDR_TO_EXTRA(pPg, pPager), 0, pPager->nExtra);
23906     }
23907     nMax = sqlite3PagerPagecount(pPager);
23908     if( pPager->errCode ){
23909       rc = pPager->errCode;
23910       sqlite3PagerUnref(pPg);
23911       return rc;
23912     }
23913
23914     /* Populate the page with data, either by reading from the database
23915     ** file, or by setting the entire page to zero.
23916     */
23917     if( nMax<(int)pgno || MEMDB || (noContent && !pPager->alwaysRollback) ){
23918       if( pgno>pPager->mxPgno ){
23919         sqlite3PagerUnref(pPg);
23920         return SQLITE_FULL;
23921       }
23922       memset(PGHDR_TO_DATA(pPg), 0, pPager->pageSize);
23923       pPg->needRead = noContent && !pPager->alwaysRollback;
23924       IOTRACE(("ZERO %p %d\n", pPager, pgno));
23925     }else{
23926       rc = readDbPage(pPager, pPg, pgno);
23927       if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
23928         pPg->pgno = 0;
23929         sqlite3PagerUnref(pPg);
23930         return rc;
23931       }
23932       pPg->needRead = 0;
23933     }
23934
23935     /* Link the page into the page hash table */
23936     h = pgno & (pPager->nHash-1);
23937     assert( pgno!=0 );
23938     pPg->pNextHash = pPager->aHash[h];
23939     pPager->aHash[h] = pPg;
23940     if( pPg->pNextHash ){
23941       assert( pPg->pNextHash->pPrevHash==0 );
23942       pPg->pNextHash->pPrevHash = pPg;
23943     }
23944
23945 #ifdef SQLITE_CHECK_PAGES
23946     pPg->pageHash = pager_pagehash(pPg);
23947 #endif
23948   }else{
23949     /* The requested page is in the page cache. */
23950     assert(pPager->nRef>0 || pgno==1);
23951     PAGER_INCR(pPager->nHit);
23952     if( !noContent ){
23953       rc = pager_get_content(pPg);
23954       if( rc ){
23955         return rc;
23956       }
23957     }
23958     page_ref(pPg);
23959   }
23960   *ppPage = pPg;
23961   return SQLITE_OK;
23962 }
23963 SQLITE_PRIVATE int sqlite3PagerAcquire(
23964   Pager *pPager,      /* The pager open on the database file */
23965   Pgno pgno,          /* Page number to fetch */
23966   DbPage **ppPage,    /* Write a pointer to the page here */
23967   int noContent       /* Do not bother reading content from disk if true */
23968 ){
23969   int rc;
23970   pagerEnter(pPager);
23971   rc = pagerAcquire(pPager, pgno, ppPage, noContent);
23972   pagerLeave(pPager);
23973   return rc;
23974 }
23975
23976
23977 /*
23978 ** Acquire a page if it is already in the in-memory cache.  Do
23979 ** not read the page from disk.  Return a pointer to the page,
23980 ** or 0 if the page is not in cache.
23981 **
23982 ** See also sqlite3PagerGet().  The difference between this routine
23983 ** and sqlite3PagerGet() is that _get() will go to the disk and read
23984 ** in the page if the page is not already in cache.  This routine
23985 ** returns NULL if the page is not in cache or if a disk I/O error 
23986 ** has ever happened.
23987 */
23988 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
23989   PgHdr *pPg = 0;
23990
23991   assert( pPager!=0 );
23992   assert( pgno!=0 );
23993
23994   pagerEnter(pPager);
23995   if( pPager->state==PAGER_UNLOCK ){
23996     assert( !pPager->pAll || pPager->exclusiveMode );
23997   }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
23998     /* Do nothing */
23999   }else if( (pPg = pager_lookup(pPager, pgno))!=0 ){
24000     page_ref(pPg);
24001   }
24002   pagerLeave(pPager);
24003   return pPg;
24004 }
24005
24006 /*
24007 ** Release a page.
24008 **
24009 ** If the number of references to the page drop to zero, then the
24010 ** page is added to the LRU list.  When all references to all pages
24011 ** are released, a rollback occurs and the lock on the database is
24012 ** removed.
24013 */
24014 SQLITE_PRIVATE int sqlite3PagerUnref(DbPage *pPg){
24015   Pager *pPager = pPg->pPager;
24016
24017   /* Decrement the reference count for this page
24018   */
24019   assert( pPg->nRef>0 );
24020   pagerEnter(pPg->pPager);
24021   pPg->nRef--;
24022   REFINFO(pPg);
24023
24024   CHECK_PAGE(pPg);
24025
24026   /* When the number of references to a page reach 0, call the
24027   ** destructor and add the page to the freelist.
24028   */
24029   if( pPg->nRef==0 ){
24030
24031     lruListAdd(pPg);
24032     if( pPager->xDestructor ){
24033       pPager->xDestructor(pPg, pPager->pageSize);
24034     }
24035   
24036     /* When all pages reach the freelist, drop the read lock from
24037     ** the database file.
24038     */
24039     pPager->nRef--;
24040     assert( pPager->nRef>=0 );
24041     if( pPager->nRef==0 && (!pPager->exclusiveMode || pPager->journalOff>0) ){
24042       pagerUnlockAndRollback(pPager);
24043     }
24044   }
24045   pagerLeave(pPager);
24046   return SQLITE_OK;
24047 }
24048
24049 /*
24050 ** Create a journal file for pPager.  There should already be a RESERVED
24051 ** or EXCLUSIVE lock on the database file when this routine is called.
24052 **
24053 ** Return SQLITE_OK if everything.  Return an error code and release the
24054 ** write lock if anything goes wrong.
24055 */
24056 static int pager_open_journal(Pager *pPager){
24057   sqlite3_vfs *pVfs = pPager->pVfs;
24058   int flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_CREATE);
24059
24060   int rc;
24061   assert( !MEMDB );
24062   assert( pPager->state>=PAGER_RESERVED );
24063   assert( pPager->journalOpen==0 );
24064   assert( pPager->useJournal );
24065   assert( pPager->aInJournal==0 );
24066   sqlite3PagerPagecount(pPager);
24067   pagerLeave(pPager);
24068   pPager->aInJournal = sqlite3MallocZero( pPager->dbSize/8 + 1 );
24069   pagerEnter(pPager);
24070   if( pPager->aInJournal==0 ){
24071     rc = SQLITE_NOMEM;
24072     goto failed_to_open_journal;
24073   }
24074
24075   if( pPager->tempFile ){
24076     flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
24077   }else{
24078     flags |= (SQLITE_OPEN_MAIN_JOURNAL);
24079   }
24080 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
24081   rc = sqlite3JournalOpen(
24082       pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
24083   );
24084 #else
24085   rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
24086 #endif
24087   assert( rc!=SQLITE_OK || pPager->jfd->pMethods );
24088   pPager->journalOff = 0;
24089   pPager->setMaster = 0;
24090   pPager->journalHdr = 0;
24091   if( rc!=SQLITE_OK ){
24092     if( rc==SQLITE_NOMEM ){
24093       sqlite3OsDelete(pVfs, pPager->zJournal, 0);
24094     }
24095     goto failed_to_open_journal;
24096   }
24097   pPager->journalOpen = 1;
24098   pPager->journalStarted = 0;
24099   pPager->needSync = 0;
24100   pPager->alwaysRollback = 0;
24101   pPager->nRec = 0;
24102   if( pPager->errCode ){
24103     rc = pPager->errCode;
24104     goto failed_to_open_journal;
24105   }
24106   pPager->origDbSize = pPager->dbSize;
24107
24108   rc = writeJournalHdr(pPager);
24109
24110   if( pPager->stmtAutoopen && rc==SQLITE_OK ){
24111     rc = sqlite3PagerStmtBegin(pPager);
24112   }
24113   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && rc!=SQLITE_IOERR_NOMEM ){
24114     rc = pager_end_transaction(pPager);
24115     if( rc==SQLITE_OK ){
24116       rc = SQLITE_FULL;
24117     }
24118   }
24119   return rc;
24120
24121 failed_to_open_journal:
24122   sqlite3_free(pPager->aInJournal);
24123   pPager->aInJournal = 0;
24124   return rc;
24125 }
24126
24127 /*
24128 ** Acquire a write-lock on the database.  The lock is removed when
24129 ** the any of the following happen:
24130 **
24131 **   *  sqlite3PagerCommitPhaseTwo() is called.
24132 **   *  sqlite3PagerRollback() is called.
24133 **   *  sqlite3PagerClose() is called.
24134 **   *  sqlite3PagerUnref() is called to on every outstanding page.
24135 **
24136 ** The first parameter to this routine is a pointer to any open page of the
24137 ** database file.  Nothing changes about the page - it is used merely to
24138 ** acquire a pointer to the Pager structure and as proof that there is
24139 ** already a read-lock on the database.
24140 **
24141 ** The second parameter indicates how much space in bytes to reserve for a
24142 ** master journal file-name at the start of the journal when it is created.
24143 **
24144 ** A journal file is opened if this is not a temporary file.  For temporary
24145 ** files, the opening of the journal file is deferred until there is an
24146 ** actual need to write to the journal.
24147 **
24148 ** If the database is already reserved for writing, this routine is a no-op.
24149 **
24150 ** If exFlag is true, go ahead and get an EXCLUSIVE lock on the file
24151 ** immediately instead of waiting until we try to flush the cache.  The
24152 ** exFlag is ignored if a transaction is already active.
24153 */
24154 SQLITE_PRIVATE int sqlite3PagerBegin(DbPage *pPg, int exFlag){
24155   Pager *pPager = pPg->pPager;
24156   int rc = SQLITE_OK;
24157   pagerEnter(pPager);
24158   assert( pPg->nRef>0 );
24159   assert( pPager->state!=PAGER_UNLOCK );
24160   if( pPager->state==PAGER_SHARED ){
24161     assert( pPager->aInJournal==0 );
24162     if( MEMDB ){
24163       pPager->state = PAGER_EXCLUSIVE;
24164       pPager->origDbSize = pPager->dbSize;
24165     }else{
24166       rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
24167       if( rc==SQLITE_OK ){
24168         pPager->state = PAGER_RESERVED;
24169         if( exFlag ){
24170           rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
24171         }
24172       }
24173       if( rc!=SQLITE_OK ){
24174         pagerLeave(pPager);
24175         return rc;
24176       }
24177       pPager->dirtyCache = 0;
24178       PAGERTRACE2("TRANSACTION %d\n", PAGERID(pPager));
24179       if( pPager->useJournal && !pPager->tempFile ){
24180         rc = pager_open_journal(pPager);
24181       }
24182     }
24183   }else if( pPager->journalOpen && pPager->journalOff==0 ){
24184     /* This happens when the pager was in exclusive-access mode last
24185     ** time a (read or write) transaction was successfully concluded
24186     ** by this connection. Instead of deleting the journal file it was 
24187     ** kept open and truncated to 0 bytes.
24188     */
24189     assert( pPager->nRec==0 );
24190     assert( pPager->origDbSize==0 );
24191     assert( pPager->aInJournal==0 );
24192     sqlite3PagerPagecount(pPager);
24193     pagerLeave(pPager);
24194     pPager->aInJournal = sqlite3MallocZero( pPager->dbSize/8 + 1 );
24195     pagerEnter(pPager);
24196     if( !pPager->aInJournal ){
24197       rc = SQLITE_NOMEM;
24198     }else{
24199       pPager->origDbSize = pPager->dbSize;
24200       rc = writeJournalHdr(pPager);
24201     }
24202   }
24203   assert( !pPager->journalOpen || pPager->journalOff>0 || rc!=SQLITE_OK );
24204   pagerLeave(pPager);
24205   return rc;
24206 }
24207
24208 /*
24209 ** Make a page dirty.  Set its dirty flag and add it to the dirty
24210 ** page list.
24211 */
24212 static void makeDirty(PgHdr *pPg){
24213   if( pPg->dirty==0 ){
24214     Pager *pPager = pPg->pPager;
24215     pPg->dirty = 1;
24216     pPg->pDirty = pPager->pDirty;
24217     if( pPager->pDirty ){
24218       pPager->pDirty->pPrevDirty = pPg;
24219     }
24220     pPg->pPrevDirty = 0;
24221     pPager->pDirty = pPg;
24222   }
24223 }
24224
24225 /*
24226 ** Make a page clean.  Clear its dirty bit and remove it from the
24227 ** dirty page list.
24228 */
24229 static void makeClean(PgHdr *pPg){
24230   if( pPg->dirty ){
24231     pPg->dirty = 0;
24232     if( pPg->pDirty ){
24233       assert( pPg->pDirty->pPrevDirty==pPg );
24234       pPg->pDirty->pPrevDirty = pPg->pPrevDirty;
24235     }
24236     if( pPg->pPrevDirty ){
24237       assert( pPg->pPrevDirty->pDirty==pPg );
24238       pPg->pPrevDirty->pDirty = pPg->pDirty;
24239     }else{
24240       assert( pPg->pPager->pDirty==pPg );
24241       pPg->pPager->pDirty = pPg->pDirty;
24242     }
24243   }
24244 }
24245
24246
24247 /*
24248 ** Mark a data page as writeable.  The page is written into the journal 
24249 ** if it is not there already.  This routine must be called before making
24250 ** changes to a page.
24251 **
24252 ** The first time this routine is called, the pager creates a new
24253 ** journal and acquires a RESERVED lock on the database.  If the RESERVED
24254 ** lock could not be acquired, this routine returns SQLITE_BUSY.  The
24255 ** calling routine must check for that return value and be careful not to
24256 ** change any page data until this routine returns SQLITE_OK.
24257 **
24258 ** If the journal file could not be written because the disk is full,
24259 ** then this routine returns SQLITE_FULL and does an immediate rollback.
24260 ** All subsequent write attempts also return SQLITE_FULL until there
24261 ** is a call to sqlite3PagerCommit() or sqlite3PagerRollback() to
24262 ** reset.
24263 */
24264 static int pager_write(PgHdr *pPg){
24265   void *pData = PGHDR_TO_DATA(pPg);
24266   Pager *pPager = pPg->pPager;
24267   int rc = SQLITE_OK;
24268
24269   /* Check for errors
24270   */
24271   if( pPager->errCode ){ 
24272     return pPager->errCode;
24273   }
24274   if( pPager->readOnly ){
24275     return SQLITE_PERM;
24276   }
24277
24278   assert( !pPager->setMaster );
24279
24280   CHECK_PAGE(pPg);
24281
24282   /* If this page was previously acquired with noContent==1, that means
24283   ** we didn't really read in the content of the page.  This can happen
24284   ** (for example) when the page is being moved to the freelist.  But
24285   ** now we are (perhaps) moving the page off of the freelist for
24286   ** reuse and we need to know its original content so that content
24287   ** can be stored in the rollback journal.  So do the read at this
24288   ** time.
24289   */
24290   rc = pager_get_content(pPg);
24291   if( rc ){
24292     return rc;
24293   }
24294
24295   /* Mark the page as dirty.  If the page has already been written
24296   ** to the journal then we can return right away.
24297   */
24298   makeDirty(pPg);
24299   if( pPg->inJournal && (pageInStatement(pPg) || pPager->stmtInUse==0) ){
24300     pPager->dirtyCache = 1;
24301   }else{
24302
24303     /* If we get this far, it means that the page needs to be
24304     ** written to the transaction journal or the ckeckpoint journal
24305     ** or both.
24306     **
24307     ** First check to see that the transaction journal exists and
24308     ** create it if it does not.
24309     */
24310     assert( pPager->state!=PAGER_UNLOCK );
24311     rc = sqlite3PagerBegin(pPg, 0);
24312     if( rc!=SQLITE_OK ){
24313       return rc;
24314     }
24315     assert( pPager->state>=PAGER_RESERVED );
24316     if( !pPager->journalOpen && pPager->useJournal ){
24317       rc = pager_open_journal(pPager);
24318       if( rc!=SQLITE_OK ) return rc;
24319     }
24320     assert( pPager->journalOpen || !pPager->useJournal );
24321     pPager->dirtyCache = 1;
24322   
24323     /* The transaction journal now exists and we have a RESERVED or an
24324     ** EXCLUSIVE lock on the main database file.  Write the current page to
24325     ** the transaction journal if it is not there already.
24326     */
24327     if( !pPg->inJournal && (pPager->useJournal || MEMDB) ){
24328       if( (int)pPg->pgno <= pPager->origDbSize ){
24329         if( MEMDB ){
24330           PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
24331           PAGERTRACE3("JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
24332           assert( pHist->pOrig==0 );
24333           pHist->pOrig = sqlite3_malloc( pPager->pageSize );
24334           if( !pHist->pOrig ){
24335             return SQLITE_NOMEM;
24336           }
24337           memcpy(pHist->pOrig, PGHDR_TO_DATA(pPg), pPager->pageSize);
24338         }else{
24339           u32 cksum;
24340           char *pData2;
24341
24342           /* We should never write to the journal file the page that
24343           ** contains the database locks.  The following assert verifies
24344           ** that we do not. */
24345           assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
24346           pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
24347           cksum = pager_cksum(pPager, (u8*)pData2);
24348           rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
24349           if( rc==SQLITE_OK ){
24350             rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
24351                                 pPager->journalOff + 4);
24352             pPager->journalOff += pPager->pageSize+4;
24353           }
24354           if( rc==SQLITE_OK ){
24355             rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
24356             pPager->journalOff += 4;
24357           }
24358           IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
24359                    pPager->journalOff, pPager->pageSize));
24360           PAGER_INCR(sqlite3_pager_writej_count);
24361           PAGERTRACE5("JOURNAL %d page %d needSync=%d hash(%08x)\n",
24362                PAGERID(pPager), pPg->pgno, pPg->needSync, pager_pagehash(pPg));
24363
24364           /* An error has occured writing to the journal file. The 
24365           ** transaction will be rolled back by the layer above.
24366           */
24367           if( rc!=SQLITE_OK ){
24368             return rc;
24369           }
24370
24371           pPager->nRec++;
24372           assert( pPager->aInJournal!=0 );
24373           pPager->aInJournal[pPg->pgno/8] |= 1<<(pPg->pgno&7);
24374           pPg->needSync = !pPager->noSync;
24375           if( pPager->stmtInUse ){
24376             pPager->aInStmt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
24377           }
24378         }
24379       }else{
24380         pPg->needSync = !pPager->journalStarted && !pPager->noSync;
24381         PAGERTRACE4("APPEND %d page %d needSync=%d\n",
24382                 PAGERID(pPager), pPg->pgno, pPg->needSync);
24383       }
24384       if( pPg->needSync ){
24385         pPager->needSync = 1;
24386       }
24387       pPg->inJournal = 1;
24388     }
24389   
24390     /* If the statement journal is open and the page is not in it,
24391     ** then write the current page to the statement journal.  Note that
24392     ** the statement journal format differs from the standard journal format
24393     ** in that it omits the checksums and the header.
24394     */
24395     if( pPager->stmtInUse 
24396      && !pageInStatement(pPg) 
24397      && (int)pPg->pgno<=pPager->stmtSize 
24398     ){
24399       assert( pPg->inJournal || (int)pPg->pgno>pPager->origDbSize );
24400       if( MEMDB ){
24401         PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
24402         assert( pHist->pStmt==0 );
24403         pHist->pStmt = sqlite3_malloc( pPager->pageSize );
24404         if( pHist->pStmt ){
24405           memcpy(pHist->pStmt, PGHDR_TO_DATA(pPg), pPager->pageSize);
24406         }
24407         PAGERTRACE3("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
24408         page_add_to_stmt_list(pPg);
24409       }else{
24410         i64 offset = pPager->stmtNRec*(4+pPager->pageSize);
24411         char *pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
24412         rc = write32bits(pPager->stfd, offset, pPg->pgno);
24413         if( rc==SQLITE_OK ){
24414           rc = sqlite3OsWrite(pPager->stfd, pData2, pPager->pageSize, offset+4);
24415         }
24416         PAGERTRACE3("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
24417         if( rc!=SQLITE_OK ){
24418           return rc;
24419         }
24420         pPager->stmtNRec++;
24421         assert( pPager->aInStmt!=0 );
24422         pPager->aInStmt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
24423       }
24424     }
24425   }
24426
24427   /* Update the database size and return.
24428   */
24429   assert( pPager->state>=PAGER_SHARED );
24430   if( pPager->dbSize<(int)pPg->pgno ){
24431     pPager->dbSize = pPg->pgno;
24432     if( !MEMDB && pPager->dbSize==PENDING_BYTE/pPager->pageSize ){
24433       pPager->dbSize++;
24434     }
24435   }
24436   return rc;
24437 }
24438
24439 /*
24440 ** This function is used to mark a data-page as writable. It uses 
24441 ** pager_write() to open a journal file (if it is not already open)
24442 ** and write the page *pData to the journal.
24443 **
24444 ** The difference between this function and pager_write() is that this
24445 ** function also deals with the special case where 2 or more pages
24446 ** fit on a single disk sector. In this case all co-resident pages
24447 ** must have been written to the journal file before returning.
24448 */
24449 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
24450   int rc = SQLITE_OK;
24451
24452   PgHdr *pPg = pDbPage;
24453   Pager *pPager = pPg->pPager;
24454   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
24455
24456   pagerEnter(pPager);
24457   if( !MEMDB && nPagePerSector>1 ){
24458     Pgno nPageCount;          /* Total number of pages in database file */
24459     Pgno pg1;                 /* First page of the sector pPg is located on. */
24460     int nPage;                /* Number of pages starting at pg1 to journal */
24461     int ii;
24462     int needSync = 0;
24463
24464     /* Set the doNotSync flag to 1. This is because we cannot allow a journal
24465     ** header to be written between the pages journaled by this function.
24466     */
24467     assert( pPager->doNotSync==0 );
24468     pPager->doNotSync = 1;
24469
24470     /* This trick assumes that both the page-size and sector-size are
24471     ** an integer power of 2. It sets variable pg1 to the identifier
24472     ** of the first page of the sector pPg is located on.
24473     */
24474     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
24475
24476     nPageCount = sqlite3PagerPagecount(pPager);
24477     if( pPg->pgno>nPageCount ){
24478       nPage = (pPg->pgno - pg1)+1;
24479     }else if( (pg1+nPagePerSector-1)>nPageCount ){
24480       nPage = nPageCount+1-pg1;
24481     }else{
24482       nPage = nPagePerSector;
24483     }
24484     assert(nPage>0);
24485     assert(pg1<=pPg->pgno);
24486     assert((pg1+nPage)>pPg->pgno);
24487
24488     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
24489       Pgno pg = pg1+ii;
24490       PgHdr *pPage;
24491       if( !pPager->aInJournal || pg==pPg->pgno || 
24492           pg>pPager->origDbSize || !(pPager->aInJournal[pg/8]&(1<<(pg&7)))
24493       ) {
24494         if( pg!=PAGER_MJ_PGNO(pPager) ){
24495           rc = sqlite3PagerGet(pPager, pg, &pPage);
24496           if( rc==SQLITE_OK ){
24497             rc = pager_write(pPage);
24498             if( pPage->needSync ){
24499               needSync = 1;
24500             }
24501             sqlite3PagerUnref(pPage);
24502           }
24503         }
24504       }else if( (pPage = pager_lookup(pPager, pg)) ){
24505         if( pPage->needSync ){
24506           needSync = 1;
24507         }
24508       }
24509     }
24510
24511     /* If the PgHdr.needSync flag is set for any of the nPage pages 
24512     ** starting at pg1, then it needs to be set for all of them. Because
24513     ** writing to any of these nPage pages may damage the others, the
24514     ** journal file must contain sync()ed copies of all of them
24515     ** before any of them can be written out to the database file.
24516     */
24517     if( needSync ){
24518       for(ii=0; ii<nPage && needSync; ii++){
24519         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
24520         if( pPage ) pPage->needSync = 1;
24521       }
24522       assert(pPager->needSync);
24523     }
24524
24525     assert( pPager->doNotSync==1 );
24526     pPager->doNotSync = 0;
24527   }else{
24528     rc = pager_write(pDbPage);
24529   }
24530   pagerLeave(pPager);
24531   return rc;
24532 }
24533
24534 /*
24535 ** Return TRUE if the page given in the argument was previously passed
24536 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
24537 ** to change the content of the page.
24538 */
24539 #ifndef NDEBUG
24540 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
24541   return pPg->dirty;
24542 }
24543 #endif
24544
24545 #ifndef SQLITE_OMIT_VACUUM
24546 /*
24547 ** Replace the content of a single page with the information in the third
24548 ** argument.
24549 */
24550 SQLITE_PRIVATE int sqlite3PagerOverwrite(Pager *pPager, Pgno pgno, void *pData){
24551   PgHdr *pPg;
24552   int rc;
24553
24554   pagerEnter(pPager);
24555   rc = sqlite3PagerGet(pPager, pgno, &pPg);
24556   if( rc==SQLITE_OK ){
24557     rc = sqlite3PagerWrite(pPg);
24558     if( rc==SQLITE_OK ){
24559       memcpy(sqlite3PagerGetData(pPg), pData, pPager->pageSize);
24560     }
24561     sqlite3PagerUnref(pPg);
24562   }
24563   pagerLeave(pPager);
24564   return rc;
24565 }
24566 #endif
24567
24568 /*
24569 ** A call to this routine tells the pager that it is not necessary to
24570 ** write the information on page pPg back to the disk, even though
24571 ** that page might be marked as dirty.
24572 **
24573 ** The overlying software layer calls this routine when all of the data
24574 ** on the given page is unused.  The pager marks the page as clean so
24575 ** that it does not get written to disk.
24576 **
24577 ** Tests show that this optimization, together with the
24578 ** sqlite3PagerDontRollback() below, more than double the speed
24579 ** of large INSERT operations and quadruple the speed of large DELETEs.
24580 **
24581 ** When this routine is called, set the alwaysRollback flag to true.
24582 ** Subsequent calls to sqlite3PagerDontRollback() for the same page
24583 ** will thereafter be ignored.  This is necessary to avoid a problem
24584 ** where a page with data is added to the freelist during one part of
24585 ** a transaction then removed from the freelist during a later part
24586 ** of the same transaction and reused for some other purpose.  When it
24587 ** is first added to the freelist, this routine is called.  When reused,
24588 ** the sqlite3PagerDontRollback() routine is called.  But because the
24589 ** page contains critical data, we still need to be sure it gets
24590 ** rolled back in spite of the sqlite3PagerDontRollback() call.
24591 */
24592 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage *pDbPage){
24593   PgHdr *pPg = pDbPage;
24594   Pager *pPager = pPg->pPager;
24595
24596   if( MEMDB ) return;
24597   pagerEnter(pPager);
24598   pPg->alwaysRollback = 1;
24599   if( pPg->dirty && !pPager->stmtInUse ){
24600     assert( pPager->state>=PAGER_SHARED );
24601     if( pPager->dbSize==(int)pPg->pgno && pPager->origDbSize<pPager->dbSize ){
24602       /* If this pages is the last page in the file and the file has grown
24603       ** during the current transaction, then do NOT mark the page as clean.
24604       ** When the database file grows, we must make sure that the last page
24605       ** gets written at least once so that the disk file will be the correct
24606       ** size. If you do not write this page and the size of the file
24607       ** on the disk ends up being too small, that can lead to database
24608       ** corruption during the next transaction.
24609       */
24610     }else{
24611       PAGERTRACE3("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager));
24612       IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
24613       makeClean(pPg);
24614 #ifdef SQLITE_CHECK_PAGES
24615       pPg->pageHash = pager_pagehash(pPg);
24616 #endif
24617     }
24618   }
24619   pagerLeave(pPager);
24620 }
24621
24622 /*
24623 ** A call to this routine tells the pager that if a rollback occurs,
24624 ** it is not necessary to restore the data on the given page.  This
24625 ** means that the pager does not have to record the given page in the
24626 ** rollback journal.
24627 **
24628 ** If we have not yet actually read the content of this page (if
24629 ** the PgHdr.needRead flag is set) then this routine acts as a promise
24630 ** that we will never need to read the page content in the future.
24631 ** so the needRead flag can be cleared at this point.
24632 */
24633 SQLITE_PRIVATE void sqlite3PagerDontRollback(DbPage *pPg){
24634   Pager *pPager = pPg->pPager;
24635
24636   pagerEnter(pPager);
24637   assert( pPager->state>=PAGER_RESERVED );
24638   if( pPager->journalOpen==0 ) return;
24639   if( pPg->alwaysRollback || pPager->alwaysRollback || MEMDB ) return;
24640   if( !pPg->inJournal && (int)pPg->pgno <= pPager->origDbSize ){
24641     assert( pPager->aInJournal!=0 );
24642     pPager->aInJournal[pPg->pgno/8] |= 1<<(pPg->pgno&7);
24643     pPg->inJournal = 1;
24644     pPg->needRead = 0;
24645     if( pPager->stmtInUse ){
24646       pPager->aInStmt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
24647     }
24648     PAGERTRACE3("DONT_ROLLBACK page %d of %d\n", pPg->pgno, PAGERID(pPager));
24649     IOTRACE(("GARBAGE %p %d\n", pPager, pPg->pgno))
24650   }
24651   if( pPager->stmtInUse 
24652    && !pageInStatement(pPg) 
24653    && (int)pPg->pgno<=pPager->stmtSize 
24654   ){
24655     assert( pPg->inJournal || (int)pPg->pgno>pPager->origDbSize );
24656     assert( pPager->aInStmt!=0 );
24657     pPager->aInStmt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
24658   }
24659   pagerLeave(pPager);
24660 }
24661
24662
24663 /*
24664 ** This routine is called to increment the database file change-counter,
24665 ** stored at byte 24 of the pager file.
24666 */
24667 static int pager_incr_changecounter(Pager *pPager, int isDirect){
24668   PgHdr *pPgHdr;
24669   u32 change_counter;
24670   int rc = SQLITE_OK;
24671
24672   if( !pPager->changeCountDone ){
24673     /* Open page 1 of the file for writing. */
24674     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
24675     if( rc!=SQLITE_OK ) return rc;
24676
24677     if( !isDirect ){
24678       rc = sqlite3PagerWrite(pPgHdr);
24679       if( rc!=SQLITE_OK ){
24680         sqlite3PagerUnref(pPgHdr);
24681         return rc;
24682       }
24683     }
24684
24685     /* Increment the value just read and write it back to byte 24. */
24686     change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
24687     change_counter++;
24688     put32bits(((char*)PGHDR_TO_DATA(pPgHdr))+24, change_counter);
24689
24690     if( isDirect && pPager->fd->pMethods ){
24691       const void *zBuf = PGHDR_TO_DATA(pPgHdr);
24692       rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
24693     }
24694
24695     /* Release the page reference. */
24696     sqlite3PagerUnref(pPgHdr);
24697     pPager->changeCountDone = 1;
24698   }
24699   return rc;
24700 }
24701
24702 /*
24703 ** Sync the database file for the pager pPager. zMaster points to the name
24704 ** of a master journal file that should be written into the individual
24705 ** journal file. zMaster may be NULL, which is interpreted as no master
24706 ** journal (a single database transaction).
24707 **
24708 ** This routine ensures that the journal is synced, all dirty pages written
24709 ** to the database file and the database file synced. The only thing that
24710 ** remains to commit the transaction is to delete the journal file (or
24711 ** master journal file if specified).
24712 **
24713 ** Note that if zMaster==NULL, this does not overwrite a previous value
24714 ** passed to an sqlite3PagerCommitPhaseOne() call.
24715 **
24716 ** If parameter nTrunc is non-zero, then the pager file is truncated to
24717 ** nTrunc pages (this is used by auto-vacuum databases).
24718 */
24719 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager *pPager, const char *zMaster, Pgno nTrunc){
24720   int rc = SQLITE_OK;
24721
24722   PAGERTRACE4("DATABASE SYNC: File=%s zMaster=%s nTrunc=%d\n", 
24723       pPager->zFilename, zMaster, nTrunc);
24724   pagerEnter(pPager);
24725
24726   /* If this is an in-memory db, or no pages have been written to, or this
24727   ** function has already been called, it is a no-op.
24728   */
24729   if( pPager->state!=PAGER_SYNCED && !MEMDB && pPager->dirtyCache ){
24730     PgHdr *pPg;
24731
24732 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
24733     /* The atomic-write optimization can be used if all of the
24734     ** following are true:
24735     **
24736     **    + The file-system supports the atomic-write property for
24737     **      blocks of size page-size, and
24738     **    + This commit is not part of a multi-file transaction, and
24739     **    + Exactly one page has been modified and store in the journal file.
24740     **
24741     ** If the optimization can be used, then the journal file will never
24742     ** be created for this transaction.
24743     */
24744     int useAtomicWrite = (
24745         !zMaster && 
24746         pPager->journalOff==jrnlBufferSize(pPager) && 
24747         nTrunc==0 && 
24748         (0==pPager->pDirty || 0==pPager->pDirty->pDirty)
24749     );
24750     if( useAtomicWrite ){
24751       /* Update the nRec field in the journal file. */
24752       int offset = pPager->journalHdr + sizeof(aJournalMagic);
24753       assert(pPager->nRec==1);
24754       rc = write32bits(pPager->jfd, offset, pPager->nRec);
24755
24756       /* Update the db file change counter. The following call will modify
24757       ** the in-memory representation of page 1 to include the updated
24758       ** change counter and then write page 1 directly to the database
24759       ** file. Because of the atomic-write property of the host file-system, 
24760       ** this is safe.
24761       */
24762       if( rc==SQLITE_OK ){
24763         rc = pager_incr_changecounter(pPager, 1);
24764       }
24765     }else{
24766       rc = sqlite3JournalCreate(pPager->jfd);
24767     }
24768
24769     if( !useAtomicWrite && rc==SQLITE_OK )
24770 #endif
24771
24772     /* If a master journal file name has already been written to the
24773     ** journal file, then no sync is required. This happens when it is
24774     ** written, then the process fails to upgrade from a RESERVED to an
24775     ** EXCLUSIVE lock. The next time the process tries to commit the
24776     ** transaction the m-j name will have already been written.
24777     */
24778     if( !pPager->setMaster ){
24779       assert( pPager->journalOpen );
24780       rc = pager_incr_changecounter(pPager, 0);
24781       if( rc!=SQLITE_OK ) goto sync_exit;
24782 #ifndef SQLITE_OMIT_AUTOVACUUM
24783       if( nTrunc!=0 ){
24784         /* If this transaction has made the database smaller, then all pages
24785         ** being discarded by the truncation must be written to the journal
24786         ** file.
24787         */
24788         Pgno i;
24789         int iSkip = PAGER_MJ_PGNO(pPager);
24790         for( i=nTrunc+1; i<=pPager->origDbSize; i++ ){
24791           if( !(pPager->aInJournal[i/8] & (1<<(i&7))) && i!=iSkip ){
24792             rc = sqlite3PagerGet(pPager, i, &pPg);
24793             if( rc!=SQLITE_OK ) goto sync_exit;
24794             rc = sqlite3PagerWrite(pPg);
24795             sqlite3PagerUnref(pPg);
24796             if( rc!=SQLITE_OK ) goto sync_exit;
24797           }
24798         } 
24799       }
24800 #endif
24801       rc = writeMasterJournal(pPager, zMaster);
24802       if( rc!=SQLITE_OK ) goto sync_exit;
24803       rc = syncJournal(pPager);
24804     }
24805     if( rc!=SQLITE_OK ) goto sync_exit;
24806
24807 #ifndef SQLITE_OMIT_AUTOVACUUM
24808     if( nTrunc!=0 ){
24809       rc = sqlite3PagerTruncate(pPager, nTrunc);
24810       if( rc!=SQLITE_OK ) goto sync_exit;
24811     }
24812 #endif
24813
24814     /* Write all dirty pages to the database file */
24815     pPg = pager_get_all_dirty_pages(pPager);
24816     rc = pager_write_pagelist(pPg);
24817     if( rc!=SQLITE_OK ){
24818       while( pPg && !pPg->dirty ){ pPg = pPg->pDirty; }
24819       pPager->pDirty = pPg;
24820       goto sync_exit;
24821     }
24822     pPager->pDirty = 0;
24823
24824     /* Sync the database file. */
24825     if( !pPager->noSync ){
24826       rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
24827     }
24828     IOTRACE(("DBSYNC %p\n", pPager))
24829
24830     pPager->state = PAGER_SYNCED;
24831   }else if( MEMDB && nTrunc!=0 ){
24832     rc = sqlite3PagerTruncate(pPager, nTrunc);
24833   }
24834
24835 sync_exit:
24836   if( rc==SQLITE_IOERR_BLOCKED ){
24837     /* pager_incr_changecounter() may attempt to obtain an exclusive
24838      * lock to spill the cache and return IOERR_BLOCKED. But since 
24839      * there is no chance the cache is inconsistent, it is
24840      * better to return SQLITE_BUSY.
24841      */
24842     rc = SQLITE_BUSY;
24843   }
24844   pagerLeave(pPager);
24845   return rc;
24846 }
24847
24848
24849 /*
24850 ** Commit all changes to the database and release the write lock.
24851 **
24852 ** If the commit fails for any reason, a rollback attempt is made
24853 ** and an error code is returned.  If the commit worked, SQLITE_OK
24854 ** is returned.
24855 */
24856 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
24857   int rc;
24858   PgHdr *pPg;
24859
24860   if( pPager->errCode ){
24861     return pPager->errCode;
24862   }
24863   if( pPager->state<PAGER_RESERVED ){
24864     return SQLITE_ERROR;
24865   }
24866   pagerEnter(pPager);
24867   PAGERTRACE2("COMMIT %d\n", PAGERID(pPager));
24868   if( MEMDB ){
24869     pPg = pager_get_all_dirty_pages(pPager);
24870     while( pPg ){
24871       PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
24872       clearHistory(pHist);
24873       pPg->dirty = 0;
24874       pPg->inJournal = 0;
24875       pHist->inStmt = 0;
24876       pPg->needSync = 0;
24877       pHist->pPrevStmt = pHist->pNextStmt = 0;
24878       pPg = pPg->pDirty;
24879     }
24880     pPager->pDirty = 0;
24881 #ifndef NDEBUG
24882     for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
24883       PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
24884       assert( !pPg->alwaysRollback );
24885       assert( !pHist->pOrig );
24886       assert( !pHist->pStmt );
24887     }
24888 #endif
24889     pPager->pStmt = 0;
24890     pPager->state = PAGER_SHARED;
24891     return SQLITE_OK;
24892   }
24893   assert( pPager->journalOpen || !pPager->dirtyCache );
24894   assert( pPager->state==PAGER_SYNCED || !pPager->dirtyCache );
24895   rc = pager_end_transaction(pPager);
24896   rc = pager_error(pPager, rc);
24897   pagerLeave(pPager);
24898   return rc;
24899 }
24900
24901 /*
24902 ** Rollback all changes.  The database falls back to PAGER_SHARED mode.
24903 ** All in-memory cache pages revert to their original data contents.
24904 ** The journal is deleted.
24905 **
24906 ** This routine cannot fail unless some other process is not following
24907 ** the correct locking protocol or unless some other
24908 ** process is writing trash into the journal file (SQLITE_CORRUPT) or
24909 ** unless a prior malloc() failed (SQLITE_NOMEM).  Appropriate error
24910 ** codes are returned for all these occasions.  Otherwise,
24911 ** SQLITE_OK is returned.
24912 */
24913 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
24914   int rc;
24915   PAGERTRACE2("ROLLBACK %d\n", PAGERID(pPager));
24916   if( MEMDB ){
24917     PgHdr *p;
24918     for(p=pPager->pAll; p; p=p->pNextAll){
24919       PgHistory *pHist;
24920       assert( !p->alwaysRollback );
24921       if( !p->dirty ){
24922         assert( !((PgHistory *)PGHDR_TO_HIST(p, pPager))->pOrig );
24923         assert( !((PgHistory *)PGHDR_TO_HIST(p, pPager))->pStmt );
24924         continue;
24925       }
24926
24927       pHist = PGHDR_TO_HIST(p, pPager);
24928       if( pHist->pOrig ){
24929         memcpy(PGHDR_TO_DATA(p), pHist->pOrig, pPager->pageSize);
24930         PAGERTRACE3("ROLLBACK-PAGE %d of %d\n", p->pgno, PAGERID(pPager));
24931       }else{
24932         PAGERTRACE3("PAGE %d is clean on %d\n", p->pgno, PAGERID(pPager));
24933       }
24934       clearHistory(pHist);
24935       p->dirty = 0;
24936       p->inJournal = 0;
24937       pHist->inStmt = 0;
24938       pHist->pPrevStmt = pHist->pNextStmt = 0;
24939       if( pPager->xReiniter ){
24940         pPager->xReiniter(p, pPager->pageSize);
24941       }
24942     }
24943     pPager->pDirty = 0;
24944     pPager->pStmt = 0;
24945     pPager->dbSize = pPager->origDbSize;
24946     pager_truncate_cache(pPager);
24947     pPager->stmtInUse = 0;
24948     pPager->state = PAGER_SHARED;
24949     return SQLITE_OK;
24950   }
24951
24952   pagerEnter(pPager);
24953   if( !pPager->dirtyCache || !pPager->journalOpen ){
24954     rc = pager_end_transaction(pPager);
24955     pagerLeave(pPager);
24956     return rc;
24957   }
24958
24959   if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
24960     if( pPager->state>=PAGER_EXCLUSIVE ){
24961       pager_playback(pPager, 0);
24962     }
24963     pagerLeave(pPager);
24964     return pPager->errCode;
24965   }
24966   if( pPager->state==PAGER_RESERVED ){
24967     int rc2;
24968     rc = pager_playback(pPager, 0);
24969     rc2 = pager_end_transaction(pPager);
24970     if( rc==SQLITE_OK ){
24971       rc = rc2;
24972     }
24973   }else{
24974     rc = pager_playback(pPager, 0);
24975   }
24976   /* pager_reset(pPager); */
24977   pPager->dbSize = -1;
24978
24979   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
24980   ** cache. So call pager_error() on the way out to make any error 
24981   ** persistent.
24982   */
24983   rc = pager_error(pPager, rc);
24984   pagerLeave(pPager);
24985   return rc;
24986 }
24987
24988 /*
24989 ** Return TRUE if the database file is opened read-only.  Return FALSE
24990 ** if the database is (in theory) writable.
24991 */
24992 SQLITE_PRIVATE int sqlite3PagerIsreadonly(Pager *pPager){
24993   return pPager->readOnly;
24994 }
24995
24996 /*
24997 ** Return the number of references to the pager.
24998 */
24999 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
25000   return pPager->nRef;
25001 }
25002
25003 #ifdef SQLITE_TEST
25004 /*
25005 ** This routine is used for testing and analysis only.
25006 */
25007 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
25008   static int a[11];
25009   a[0] = pPager->nRef;
25010   a[1] = pPager->nPage;
25011   a[2] = pPager->mxPage;
25012   a[3] = pPager->dbSize;
25013   a[4] = pPager->state;
25014   a[5] = pPager->errCode;
25015   a[6] = pPager->nHit;
25016   a[7] = pPager->nMiss;
25017   a[8] = 0;  /* Used to be pPager->nOvfl */
25018   a[9] = pPager->nRead;
25019   a[10] = pPager->nWrite;
25020   return a;
25021 }
25022 #endif
25023
25024 /*
25025 ** Set the statement rollback point.
25026 **
25027 ** This routine should be called with the transaction journal already
25028 ** open.  A new statement journal is created that can be used to rollback
25029 ** changes of a single SQL command within a larger transaction.
25030 */
25031 static int pagerStmtBegin(Pager *pPager){
25032   int rc;
25033   assert( !pPager->stmtInUse );
25034   assert( pPager->state>=PAGER_SHARED );
25035   assert( pPager->dbSize>=0 );
25036   PAGERTRACE2("STMT-BEGIN %d\n", PAGERID(pPager));
25037   if( MEMDB ){
25038     pPager->stmtInUse = 1;
25039     pPager->stmtSize = pPager->dbSize;
25040     return SQLITE_OK;
25041   }
25042   if( !pPager->journalOpen ){
25043     pPager->stmtAutoopen = 1;
25044     return SQLITE_OK;
25045   }
25046   assert( pPager->journalOpen );
25047   pagerLeave(pPager);
25048   assert( pPager->aInStmt==0 );
25049   pPager->aInStmt = sqlite3MallocZero( pPager->dbSize/8 + 1 );
25050   pagerEnter(pPager);
25051   if( pPager->aInStmt==0 ){
25052     /* sqlite3OsLock(pPager->fd, SHARED_LOCK); */
25053     return SQLITE_NOMEM;
25054   }
25055 #ifndef NDEBUG
25056   rc = sqlite3OsFileSize(pPager->jfd, &pPager->stmtJSize);
25057   if( rc ) goto stmt_begin_failed;
25058   assert( pPager->stmtJSize == pPager->journalOff );
25059 #endif
25060   pPager->stmtJSize = pPager->journalOff;
25061   pPager->stmtSize = pPager->dbSize;
25062   pPager->stmtHdrOff = 0;
25063   pPager->stmtCksum = pPager->cksumInit;
25064   if( !pPager->stmtOpen ){
25065     rc = sqlite3PagerOpentemp(pPager->pVfs, pPager->stfd, pPager->zStmtJrnl,
25066                               SQLITE_OPEN_SUBJOURNAL);
25067     if( rc ){
25068       goto stmt_begin_failed;
25069     }
25070     pPager->stmtOpen = 1;
25071     pPager->stmtNRec = 0;
25072   }
25073   pPager->stmtInUse = 1;
25074   return SQLITE_OK;
25075  
25076 stmt_begin_failed:
25077   if( pPager->aInStmt ){
25078     sqlite3_free(pPager->aInStmt);
25079     pPager->aInStmt = 0;
25080   }
25081   return rc;
25082 }
25083 SQLITE_PRIVATE int sqlite3PagerStmtBegin(Pager *pPager){
25084   int rc;
25085   pagerEnter(pPager);
25086   rc = pagerStmtBegin(pPager);
25087   pagerLeave(pPager);
25088   return rc;
25089 }
25090
25091 /*
25092 ** Commit a statement.
25093 */
25094 SQLITE_PRIVATE int sqlite3PagerStmtCommit(Pager *pPager){
25095   pagerEnter(pPager);
25096   if( pPager->stmtInUse ){
25097     PgHdr *pPg, *pNext;
25098     PAGERTRACE2("STMT-COMMIT %d\n", PAGERID(pPager));
25099     if( !MEMDB ){
25100       /* sqlite3OsTruncate(pPager->stfd, 0); */
25101       sqlite3_free( pPager->aInStmt );
25102       pPager->aInStmt = 0;
25103     }else{
25104       for(pPg=pPager->pStmt; pPg; pPg=pNext){
25105         PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
25106         pNext = pHist->pNextStmt;
25107         assert( pHist->inStmt );
25108         pHist->inStmt = 0;
25109         pHist->pPrevStmt = pHist->pNextStmt = 0;
25110         sqlite3_free(pHist->pStmt);
25111         pHist->pStmt = 0;
25112       }
25113     }
25114     pPager->stmtNRec = 0;
25115     pPager->stmtInUse = 0;
25116     pPager->pStmt = 0;
25117   }
25118   pPager->stmtAutoopen = 0;
25119   pagerLeave(pPager);
25120   return SQLITE_OK;
25121 }
25122
25123 /*
25124 ** Rollback a statement.
25125 */
25126 SQLITE_PRIVATE int sqlite3PagerStmtRollback(Pager *pPager){
25127   int rc;
25128   pagerEnter(pPager);
25129   if( pPager->stmtInUse ){
25130     PAGERTRACE2("STMT-ROLLBACK %d\n", PAGERID(pPager));
25131     if( MEMDB ){
25132       PgHdr *pPg;
25133       PgHistory *pHist;
25134       for(pPg=pPager->pStmt; pPg; pPg=pHist->pNextStmt){
25135         pHist = PGHDR_TO_HIST(pPg, pPager);
25136         if( pHist->pStmt ){
25137           memcpy(PGHDR_TO_DATA(pPg), pHist->pStmt, pPager->pageSize);
25138           sqlite3_free(pHist->pStmt);
25139           pHist->pStmt = 0;
25140         }
25141       }
25142       pPager->dbSize = pPager->stmtSize;
25143       pager_truncate_cache(pPager);
25144       rc = SQLITE_OK;
25145     }else{
25146       rc = pager_stmt_playback(pPager);
25147     }
25148     sqlite3PagerStmtCommit(pPager);
25149   }else{
25150     rc = SQLITE_OK;
25151   }
25152   pPager->stmtAutoopen = 0;
25153   pagerLeave(pPager);
25154   return rc;
25155 }
25156
25157 /*
25158 ** Return the full pathname of the database file.
25159 */
25160 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
25161   return pPager->zFilename;
25162 }
25163
25164 /*
25165 ** Return the VFS structure for the pager.
25166 */
25167 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
25168   return pPager->pVfs;
25169 }
25170
25171 /*
25172 ** Return the file handle for the database file associated
25173 ** with the pager.  This might return NULL if the file has
25174 ** not yet been opened.
25175 */
25176 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
25177   return pPager->fd;
25178 }
25179
25180 /*
25181 ** Return the directory of the database file.
25182 */
25183 SQLITE_PRIVATE const char *sqlite3PagerDirname(Pager *pPager){
25184   return pPager->zDirectory;
25185 }
25186
25187 /*
25188 ** Return the full pathname of the journal file.
25189 */
25190 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
25191   return pPager->zJournal;
25192 }
25193
25194 /*
25195 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
25196 ** if fsync()s are executed normally.
25197 */
25198 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
25199   return pPager->noSync;
25200 }
25201
25202 #ifdef SQLITE_HAS_CODEC
25203 /*
25204 ** Set the codec for this pager
25205 */
25206 SQLITE_PRIVATE void sqlite3PagerSetCodec(
25207   Pager *pPager,
25208   void *(*xCodec)(void*,void*,Pgno,int),
25209   void *pCodecArg
25210 ){
25211   pPager->xCodec = xCodec;
25212   pPager->pCodecArg = pCodecArg;
25213 }
25214 #endif
25215
25216 #ifndef SQLITE_OMIT_AUTOVACUUM
25217 /*
25218 ** Move the page pPg to location pgno in the file. 
25219 **
25220 ** There must be no references to the page previously located at
25221 ** pgno (which we call pPgOld) though that page is allowed to be
25222 ** in cache.  If the page previous located at pgno is not already
25223 ** in the rollback journal, it is not put there by by this routine.
25224 **
25225 ** References to the page pPg remain valid. Updating any
25226 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
25227 ** allocated along with the page) is the responsibility of the caller.
25228 **
25229 ** A transaction must be active when this routine is called. It used to be
25230 ** required that a statement transaction was not active, but this restriction
25231 ** has been removed (CREATE INDEX needs to move a page when a statement
25232 ** transaction is active).
25233 */
25234 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno){
25235   PgHdr *pPgOld;  /* The page being overwritten. */
25236   int h;
25237   Pgno needSyncPgno = 0;
25238
25239   pagerEnter(pPager);
25240   assert( pPg->nRef>0 );
25241
25242   PAGERTRACE5("MOVE %d page %d (needSync=%d) moves to %d\n", 
25243       PAGERID(pPager), pPg->pgno, pPg->needSync, pgno);
25244   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
25245
25246   pager_get_content(pPg);
25247   if( pPg->needSync ){
25248     needSyncPgno = pPg->pgno;
25249     assert( pPg->inJournal || (int)pgno>pPager->origDbSize );
25250     assert( pPg->dirty );
25251     assert( pPager->needSync );
25252   }
25253
25254   /* Unlink pPg from its hash-chain */
25255   unlinkHashChain(pPager, pPg);
25256
25257   /* If the cache contains a page with page-number pgno, remove it
25258   ** from its hash chain. Also, if the PgHdr.needSync was set for 
25259   ** page pgno before the 'move' operation, it needs to be retained 
25260   ** for the page moved there.
25261   */
25262   pPg->needSync = 0;
25263   pPgOld = pager_lookup(pPager, pgno);
25264   if( pPgOld ){
25265     assert( pPgOld->nRef==0 );
25266     unlinkHashChain(pPager, pPgOld);
25267     makeClean(pPgOld);
25268     pPg->needSync = pPgOld->needSync;
25269   }else{
25270     pPg->needSync = 0;
25271   }
25272   if( pPager->aInJournal && (int)pgno<=pPager->origDbSize ){
25273     pPg->inJournal =  (pPager->aInJournal[pgno/8] & (1<<(pgno&7)))!=0;
25274   }else{
25275     pPg->inJournal = 0;
25276     assert( pPg->needSync==0 || (int)pgno>pPager->origDbSize );
25277   }
25278
25279   /* Change the page number for pPg and insert it into the new hash-chain. */
25280   assert( pgno!=0 );
25281   pPg->pgno = pgno;
25282   h = pgno & (pPager->nHash-1);
25283   if( pPager->aHash[h] ){
25284     assert( pPager->aHash[h]->pPrevHash==0 );
25285     pPager->aHash[h]->pPrevHash = pPg;
25286   }
25287   pPg->pNextHash = pPager->aHash[h];
25288   pPager->aHash[h] = pPg;
25289   pPg->pPrevHash = 0;
25290
25291   makeDirty(pPg);
25292   pPager->dirtyCache = 1;
25293
25294   if( needSyncPgno ){
25295     /* If needSyncPgno is non-zero, then the journal file needs to be 
25296     ** sync()ed before any data is written to database file page needSyncPgno.
25297     ** Currently, no such page exists in the page-cache and the 
25298     ** Pager.aInJournal bit has been set. This needs to be remedied by loading
25299     ** the page into the pager-cache and setting the PgHdr.needSync flag.
25300     **
25301     ** The sqlite3PagerGet() call may cause the journal to sync. So make
25302     ** sure the Pager.needSync flag is set too.
25303     */
25304     int rc;
25305     PgHdr *pPgHdr;
25306     assert( pPager->needSync );
25307     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
25308     if( rc!=SQLITE_OK ) return rc;
25309     pPager->needSync = 1;
25310     pPgHdr->needSync = 1;
25311     pPgHdr->inJournal = 1;
25312     makeDirty(pPgHdr);
25313     sqlite3PagerUnref(pPgHdr);
25314   }
25315
25316   pagerLeave(pPager);
25317   return SQLITE_OK;
25318 }
25319 #endif
25320
25321 /*
25322 ** Return a pointer to the data for the specified page.
25323 */
25324 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
25325   return PGHDR_TO_DATA(pPg);
25326 }
25327
25328 /*
25329 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
25330 ** allocated along with the specified page.
25331 */
25332 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
25333   Pager *pPager = pPg->pPager;
25334   return (pPager?PGHDR_TO_EXTRA(pPg, pPager):0);
25335 }
25336
25337 /*
25338 ** Get/set the locking-mode for this pager. Parameter eMode must be one
25339 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
25340 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
25341 ** the locking-mode is set to the value specified.
25342 **
25343 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
25344 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
25345 ** locking-mode.
25346 */
25347 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
25348   assert( eMode==PAGER_LOCKINGMODE_QUERY
25349             || eMode==PAGER_LOCKINGMODE_NORMAL
25350             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
25351   assert( PAGER_LOCKINGMODE_QUERY<0 );
25352   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
25353   if( eMode>=0 && !pPager->tempFile ){
25354     pPager->exclusiveMode = eMode;
25355   }
25356   return (int)pPager->exclusiveMode;
25357 }
25358
25359 #ifdef SQLITE_TEST
25360 /*
25361 ** Print a listing of all referenced pages and their ref count.
25362 */
25363 SQLITE_PRIVATE void sqlite3PagerRefdump(Pager *pPager){
25364   PgHdr *pPg;
25365   for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
25366     if( pPg->nRef<=0 ) continue;
25367     sqlite3DebugPrintf("PAGE %3d addr=%p nRef=%d\n", 
25368        pPg->pgno, PGHDR_TO_DATA(pPg), pPg->nRef);
25369   }
25370 }
25371 #endif
25372
25373 #endif /* SQLITE_OMIT_DISKIO */
25374
25375 /************** End of pager.c ***********************************************/
25376 /************** Begin file btmutex.c *****************************************/
25377 /*
25378 ** 2007 August 27
25379 **
25380 ** The author disclaims copyright to this source code.  In place of
25381 ** a legal notice, here is a blessing:
25382 **
25383 **    May you do good and not evil.
25384 **    May you find forgiveness for yourself and forgive others.
25385 **    May you share freely, never taking more than you give.
25386 **
25387 *************************************************************************
25388 **
25389 ** $Id: btmutex.c,v 1.8 2007/12/07 18:55:28 drh Exp $
25390 **
25391 ** This file contains code used to implement mutexes on Btree objects.
25392 ** This code really belongs in btree.c.  But btree.c is getting too
25393 ** big and we want to break it down some.  This packaged seemed like
25394 ** a good breakout.
25395 */
25396 /************** Include btreeInt.h in the middle of btmutex.c ****************/
25397 /************** Begin file btreeInt.h ****************************************/
25398 /*
25399 ** 2004 April 6
25400 **
25401 ** The author disclaims copyright to this source code.  In place of
25402 ** a legal notice, here is a blessing:
25403 **
25404 **    May you do good and not evil.
25405 **    May you find forgiveness for yourself and forgive others.
25406 **    May you share freely, never taking more than you give.
25407 **
25408 *************************************************************************
25409 ** $Id: btreeInt.h,v 1.14 2007/12/07 18:55:28 drh Exp $
25410 **
25411 ** This file implements a external (disk-based) database using BTrees.
25412 ** For a detailed discussion of BTrees, refer to
25413 **
25414 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
25415 **     "Sorting And Searching", pages 473-480. Addison-Wesley
25416 **     Publishing Company, Reading, Massachusetts.
25417 **
25418 ** The basic idea is that each page of the file contains N database
25419 ** entries and N+1 pointers to subpages.
25420 **
25421 **   ----------------------------------------------------------------
25422 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
25423 **   ----------------------------------------------------------------
25424 **
25425 ** All of the keys on the page that Ptr(0) points to have values less
25426 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
25427 ** values greater than Key(0) and less than Key(1).  All of the keys
25428 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
25429 ** so forth.
25430 **
25431 ** Finding a particular key requires reading O(log(M)) pages from the 
25432 ** disk where M is the number of entries in the tree.
25433 **
25434 ** In this implementation, a single file can hold one or more separate 
25435 ** BTrees.  Each BTree is identified by the index of its root page.  The
25436 ** key and data for any entry are combined to form the "payload".  A
25437 ** fixed amount of payload can be carried directly on the database
25438 ** page.  If the payload is larger than the preset amount then surplus
25439 ** bytes are stored on overflow pages.  The payload for an entry
25440 ** and the preceding pointer are combined to form a "Cell".  Each 
25441 ** page has a small header which contains the Ptr(N) pointer and other
25442 ** information such as the size of key and data.
25443 **
25444 ** FORMAT DETAILS
25445 **
25446 ** The file is divided into pages.  The first page is called page 1,
25447 ** the second is page 2, and so forth.  A page number of zero indicates
25448 ** "no such page".  The page size can be anything between 512 and 65536.
25449 ** Each page can be either a btree page, a freelist page or an overflow
25450 ** page.
25451 **
25452 ** The first page is always a btree page.  The first 100 bytes of the first
25453 ** page contain a special header (the "file header") that describes the file.
25454 ** The format of the file header is as follows:
25455 **
25456 **   OFFSET   SIZE    DESCRIPTION
25457 **      0      16     Header string: "SQLite format 3\000"
25458 **     16       2     Page size in bytes.  
25459 **     18       1     File format write version
25460 **     19       1     File format read version
25461 **     20       1     Bytes of unused space at the end of each page
25462 **     21       1     Max embedded payload fraction
25463 **     22       1     Min embedded payload fraction
25464 **     23       1     Min leaf payload fraction
25465 **     24       4     File change counter
25466 **     28       4     Reserved for future use
25467 **     32       4     First freelist page
25468 **     36       4     Number of freelist pages in the file
25469 **     40      60     15 4-byte meta values passed to higher layers
25470 **
25471 ** All of the integer values are big-endian (most significant byte first).
25472 **
25473 ** The file change counter is incremented when the database is changed
25474 ** This counter allows other processes to know when the file has changed
25475 ** and thus when they need to flush their cache.
25476 **
25477 ** The max embedded payload fraction is the amount of the total usable
25478 ** space in a page that can be consumed by a single cell for standard
25479 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
25480 ** is to limit the maximum cell size so that at least 4 cells will fit
25481 ** on one page.  Thus the default max embedded payload fraction is 64.
25482 **
25483 ** If the payload for a cell is larger than the max payload, then extra
25484 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
25485 ** as many bytes as possible are moved into the overflow pages without letting
25486 ** the cell size drop below the min embedded payload fraction.
25487 **
25488 ** The min leaf payload fraction is like the min embedded payload fraction
25489 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
25490 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
25491 ** not specified in the header.
25492 **
25493 ** Each btree pages is divided into three sections:  The header, the
25494 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
25495 ** file header that occurs before the page header.
25496 **
25497 **      |----------------|
25498 **      | file header    |   100 bytes.  Page 1 only.
25499 **      |----------------|
25500 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
25501 **      |----------------|
25502 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
25503 **      | array          |   |  Grows downward
25504 **      |                |   v
25505 **      |----------------|
25506 **      | unallocated    |
25507 **      | space          |
25508 **      |----------------|   ^  Grows upwards
25509 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
25510 **      | area           |   |  and free space fragments.
25511 **      |----------------|
25512 **
25513 ** The page headers looks like this:
25514 **
25515 **   OFFSET   SIZE     DESCRIPTION
25516 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
25517 **      1       2      byte offset to the first freeblock
25518 **      3       2      number of cells on this page
25519 **      5       2      first byte of the cell content area
25520 **      7       1      number of fragmented free bytes
25521 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
25522 **
25523 ** The flags define the format of this btree page.  The leaf flag means that
25524 ** this page has no children.  The zerodata flag means that this page carries
25525 ** only keys and no data.  The intkey flag means that the key is a integer
25526 ** which is stored in the key size entry of the cell header rather than in
25527 ** the payload area.
25528 **
25529 ** The cell pointer array begins on the first byte after the page header.
25530 ** The cell pointer array contains zero or more 2-byte numbers which are
25531 ** offsets from the beginning of the page to the cell content in the cell
25532 ** content area.  The cell pointers occur in sorted order.  The system strives
25533 ** to keep free space after the last cell pointer so that new cells can
25534 ** be easily added without having to defragment the page.
25535 **
25536 ** Cell content is stored at the very end of the page and grows toward the
25537 ** beginning of the page.
25538 **
25539 ** Unused space within the cell content area is collected into a linked list of
25540 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
25541 ** to the first freeblock is given in the header.  Freeblocks occur in
25542 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
25543 ** any group of 3 or fewer unused bytes in the cell content area cannot
25544 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
25545 ** a fragment.  The total number of bytes in all fragments is recorded.
25546 ** in the page header at offset 7.
25547 **
25548 **    SIZE    DESCRIPTION
25549 **      2     Byte offset of the next freeblock
25550 **      2     Bytes in this freeblock
25551 **
25552 ** Cells are of variable length.  Cells are stored in the cell content area at
25553 ** the end of the page.  Pointers to the cells are in the cell pointer array
25554 ** that immediately follows the page header.  Cells is not necessarily
25555 ** contiguous or in order, but cell pointers are contiguous and in order.
25556 **
25557 ** Cell content makes use of variable length integers.  A variable
25558 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
25559 ** byte are used.  The integer consists of all bytes that have bit 8 set and
25560 ** the first byte with bit 8 clear.  The most significant byte of the integer
25561 ** appears first.  A variable-length integer may not be more than 9 bytes long.
25562 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
25563 ** allows a 64-bit integer to be encoded in 9 bytes.
25564 **
25565 **    0x00                      becomes  0x00000000
25566 **    0x7f                      becomes  0x0000007f
25567 **    0x81 0x00                 becomes  0x00000080
25568 **    0x82 0x00                 becomes  0x00000100
25569 **    0x80 0x7f                 becomes  0x0000007f
25570 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
25571 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
25572 **
25573 ** Variable length integers are used for rowids and to hold the number of
25574 ** bytes of key and data in a btree cell.
25575 **
25576 ** The content of a cell looks like this:
25577 **
25578 **    SIZE    DESCRIPTION
25579 **      4     Page number of the left child. Omitted if leaf flag is set.
25580 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
25581 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
25582 **      *     Payload
25583 **      4     First page of the overflow chain.  Omitted if no overflow
25584 **
25585 ** Overflow pages form a linked list.  Each page except the last is completely
25586 ** filled with data (pagesize - 4 bytes).  The last page can have as little
25587 ** as 1 byte of data.
25588 **
25589 **    SIZE    DESCRIPTION
25590 **      4     Page number of next overflow page
25591 **      *     Data
25592 **
25593 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
25594 ** file header points to the first in a linked list of trunk page.  Each trunk
25595 ** page points to multiple leaf pages.  The content of a leaf page is
25596 ** unspecified.  A trunk page looks like this:
25597 **
25598 **    SIZE    DESCRIPTION
25599 **      4     Page number of next trunk page
25600 **      4     Number of leaf pointers on this page
25601 **      *     zero or more pages numbers of leaves
25602 */
25603
25604 /* Round up a number to the next larger multiple of 8.  This is used
25605 ** to force 8-byte alignment on 64-bit architectures.
25606 */
25607 #define ROUND8(x)   ((x+7)&~7)
25608
25609
25610 /* The following value is the maximum cell size assuming a maximum page
25611 ** size give above.
25612 */
25613 #define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
25614
25615 /* The maximum number of cells on a single page of the database.  This
25616 ** assumes a minimum cell size of 3 bytes.  Such small cells will be
25617 ** exceedingly rare, but they are possible.
25618 */
25619 #define MX_CELL(pBt) ((pBt->pageSize-8)/3)
25620
25621 /* Forward declarations */
25622 typedef struct MemPage MemPage;
25623 typedef struct BtLock BtLock;
25624
25625 /*
25626 ** This is a magic string that appears at the beginning of every
25627 ** SQLite database in order to identify the file as a real database.
25628 **
25629 ** You can change this value at compile-time by specifying a
25630 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
25631 ** header must be exactly 16 bytes including the zero-terminator so
25632 ** the string itself should be 15 characters long.  If you change
25633 ** the header, then your custom library will not be able to read 
25634 ** databases generated by the standard tools and the standard tools
25635 ** will not be able to read databases created by your custom library.
25636 */
25637 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
25638 #  define SQLITE_FILE_HEADER "SQLite format 3"
25639 #endif
25640
25641 /*
25642 ** Page type flags.  An ORed combination of these flags appear as the
25643 ** first byte of on-disk image of every BTree page.
25644 */
25645 #define PTF_INTKEY    0x01
25646 #define PTF_ZERODATA  0x02
25647 #define PTF_LEAFDATA  0x04
25648 #define PTF_LEAF      0x08
25649
25650 /*
25651 ** As each page of the file is loaded into memory, an instance of the following
25652 ** structure is appended and initialized to zero.  This structure stores
25653 ** information about the page that is decoded from the raw file page.
25654 **
25655 ** The pParent field points back to the parent page.  This allows us to
25656 ** walk up the BTree from any leaf to the root.  Care must be taken to
25657 ** unref() the parent page pointer when this page is no longer referenced.
25658 ** The pageDestructor() routine handles that chore.
25659 **
25660 ** Access to all fields of this structure is controlled by the mutex
25661 ** stored in MemPage.pBt->mutex.
25662 */
25663 struct MemPage {
25664   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
25665   u8 idxShift;         /* True if Cell indices have changed */
25666   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
25667   u8 intKey;           /* True if intkey flag is set */
25668   u8 leaf;             /* True if leaf flag is set */
25669   u8 zeroData;         /* True if table stores keys only */
25670   u8 leafData;         /* True if tables stores data on leaves only */
25671   u8 hasData;          /* True if this page stores data */
25672   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
25673   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
25674   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
25675   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
25676   u16 cellOffset;      /* Index in aData of first cell pointer */
25677   u16 idxParent;       /* Index in parent of this node */
25678   u16 nFree;           /* Number of free bytes on the page */
25679   u16 nCell;           /* Number of cells on this page, local and ovfl */
25680   struct _OvflCell {   /* Cells that will not fit on aData[] */
25681     u8 *pCell;          /* Pointers to the body of the overflow cell */
25682     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
25683   } aOvfl[5];
25684   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
25685   u8 *aData;           /* Pointer to disk image of the page data */
25686   DbPage *pDbPage;     /* Pager page handle */
25687   Pgno pgno;           /* Page number for this page */
25688   MemPage *pParent;    /* The parent of this page.  NULL for root */
25689 };
25690
25691 /*
25692 ** The in-memory image of a disk page has the auxiliary information appended
25693 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
25694 ** that extra information.
25695 */
25696 #define EXTRA_SIZE sizeof(MemPage)
25697
25698 /* A Btree handle
25699 **
25700 ** A database connection contains a pointer to an instance of
25701 ** this object for every database file that it has open.  This structure
25702 ** is opaque to the database connection.  The database connection cannot
25703 ** see the internals of this structure and only deals with pointers to
25704 ** this structure.
25705 **
25706 ** For some database files, the same underlying database cache might be 
25707 ** shared between multiple connections.  In that case, each contection
25708 ** has it own pointer to this object.  But each instance of this object
25709 ** points to the same BtShared object.  The database cache and the
25710 ** schema associated with the database file are all contained within
25711 ** the BtShared object.
25712 **
25713 ** All fields in this structure are accessed under sqlite3.mutex.
25714 ** The pBt pointer itself may not be changed while there exists cursors 
25715 ** in the referenced BtShared that point back to this Btree since those
25716 ** cursors have to do go through this Btree to find their BtShared and
25717 ** they often do so without holding sqlite3.mutex.
25718 */
25719 struct Btree {
25720   sqlite3 *db;       /* The database connection holding this btree */
25721   BtShared *pBt;     /* Sharable content of this btree */
25722   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
25723   u8 sharable;       /* True if we can share pBt with another db */
25724   u8 locked;         /* True if db currently has pBt locked */
25725   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
25726   Btree *pNext;      /* List of other sharable Btrees from the same db */
25727   Btree *pPrev;      /* Back pointer of the same list */
25728 };
25729
25730 /*
25731 ** Btree.inTrans may take one of the following values.
25732 **
25733 ** If the shared-data extension is enabled, there may be multiple users
25734 ** of the Btree structure. At most one of these may open a write transaction,
25735 ** but any number may have active read transactions.
25736 */
25737 #define TRANS_NONE  0
25738 #define TRANS_READ  1
25739 #define TRANS_WRITE 2
25740
25741 /*
25742 ** An instance of this object represents a single database file.
25743 ** 
25744 ** A single database file can be in use as the same time by two
25745 ** or more database connections.  When two or more connections are
25746 ** sharing the same database file, each connection has it own
25747 ** private Btree object for the file and each of those Btrees points
25748 ** to this one BtShared object.  BtShared.nRef is the number of
25749 ** connections currently sharing this database file.
25750 **
25751 ** Fields in this structure are accessed under the BtShared.mutex
25752 ** mutex, except for nRef and pNext which are accessed under the
25753 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
25754 ** may not be modified once it is initially set as long as nRef>0.
25755 ** The pSchema field may be set once under BtShared.mutex and
25756 ** thereafter is unchanged as long as nRef>0.
25757 */
25758 struct BtShared {
25759   Pager *pPager;        /* The page cache */
25760   sqlite3 *db;          /* Database connection currently using this Btree */
25761   BtCursor *pCursor;    /* A list of all open cursors */
25762   MemPage *pPage1;      /* First page of the database */
25763   u8 inStmt;            /* True if we are in a statement subtransaction */
25764   u8 readOnly;          /* True if the underlying file is readonly */
25765   u8 maxEmbedFrac;      /* Maximum payload as % of total page size */
25766   u8 minEmbedFrac;      /* Minimum payload as % of total page size */
25767   u8 minLeafFrac;       /* Minimum leaf payload as % of total page size */
25768   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
25769 #ifndef SQLITE_OMIT_AUTOVACUUM
25770   u8 autoVacuum;        /* True if auto-vacuum is enabled */
25771   u8 incrVacuum;        /* True if incr-vacuum is enabled */
25772   Pgno nTrunc;          /* Non-zero if the db will be truncated (incr vacuum) */
25773 #endif
25774   u16 pageSize;         /* Total number of bytes on a page */
25775   u16 usableSize;       /* Number of usable bytes on each page */
25776   int maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
25777   int minLocal;         /* Minimum local payload in non-LEAFDATA tables */
25778   int maxLeaf;          /* Maximum local payload in a LEAFDATA table */
25779   int minLeaf;          /* Minimum local payload in a LEAFDATA table */
25780   u8 inTransaction;     /* Transaction state */
25781   int nTransaction;     /* Number of open transactions (read + write) */
25782   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
25783   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
25784   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
25785   BusyHandler busyHdr;  /* The busy handler for this btree */
25786 #ifndef SQLITE_OMIT_SHARED_CACHE
25787   int nRef;             /* Number of references to this structure */
25788   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
25789   BtLock *pLock;        /* List of locks held on this shared-btree struct */
25790 #endif
25791 };
25792
25793 /*
25794 ** An instance of the following structure is used to hold information
25795 ** about a cell.  The parseCellPtr() function fills in this structure
25796 ** based on information extract from the raw disk page.
25797 */
25798 typedef struct CellInfo CellInfo;
25799 struct CellInfo {
25800   u8 *pCell;     /* Pointer to the start of cell content */
25801   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
25802   u32 nData;     /* Number of bytes of data */
25803   u32 nPayload;  /* Total amount of payload */
25804   u16 nHeader;   /* Size of the cell content header in bytes */
25805   u16 nLocal;    /* Amount of payload held locally */
25806   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
25807   u16 nSize;     /* Size of the cell content on the main b-tree page */
25808 };
25809
25810 /*
25811 ** A cursor is a pointer to a particular entry within a particular
25812 ** b-tree within a database file.
25813 **
25814 ** The entry is identified by its MemPage and the index in
25815 ** MemPage.aCell[] of the entry.
25816 **
25817 ** When a single database file can shared by two more database connections,
25818 ** but cursors cannot be shared.  Each cursor is associated with a
25819 ** particular database connection identified BtCursor.pBtree.db.
25820 **
25821 ** Fields in this structure are accessed under the BtShared.mutex
25822 ** found at self->pBt->mutex. 
25823 */
25824 struct BtCursor {
25825   Btree *pBtree;            /* The Btree to which this cursor belongs */
25826   BtShared *pBt;            /* The BtShared this cursor points to */
25827   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
25828   int (*xCompare)(void*,int,const void*,int,const void*); /* Key comp func */
25829   void *pArg;               /* First arg to xCompare() */
25830   Pgno pgnoRoot;            /* The root page of this tree */
25831   MemPage *pPage;           /* Page that contains the entry */
25832   int idx;                  /* Index of the entry in pPage->aCell[] */
25833   CellInfo info;            /* A parse of the cell we are pointing at */
25834   u8 wrFlag;                /* True if writable */
25835   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
25836   void *pKey;      /* Saved key that was cursor's last known position */
25837   i64 nKey;        /* Size of pKey, or last integer key */
25838   int skip;        /* (skip<0) -> Prev() is a no-op. (skip>0) -> Next() is */
25839 #ifndef SQLITE_OMIT_INCRBLOB
25840   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
25841   Pgno *aOverflow;          /* Cache of overflow page locations */
25842 #endif
25843 };
25844
25845 /*
25846 ** Potential values for BtCursor.eState.
25847 **
25848 ** CURSOR_VALID:
25849 **   Cursor points to a valid entry. getPayload() etc. may be called.
25850 **
25851 ** CURSOR_INVALID:
25852 **   Cursor does not point to a valid entry. This can happen (for example) 
25853 **   because the table is empty or because BtreeCursorFirst() has not been
25854 **   called.
25855 **
25856 ** CURSOR_REQUIRESEEK:
25857 **   The table that this cursor was opened on still exists, but has been 
25858 **   modified since the cursor was last used. The cursor position is saved
25859 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
25860 **   this state, restoreOrClearCursorPosition() can be called to attempt to
25861 **   seek the cursor to the saved position.
25862 **
25863 ** CURSOR_FAULT:
25864 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
25865 **   on a different connection that shares the BtShared cache with this
25866 **   cursor.  The error has left the cache in an inconsistent state.
25867 **   Do nothing else with this cursor.  Any attempt to use the cursor
25868 **   should return the error code stored in BtCursor.skip
25869 */
25870 #define CURSOR_INVALID           0
25871 #define CURSOR_VALID             1
25872 #define CURSOR_REQUIRESEEK       2
25873 #define CURSOR_FAULT             3
25874
25875 /*
25876 ** The TRACE macro will print high-level status information about the
25877 ** btree operation when the global variable sqlite3_btree_trace is
25878 ** enabled.
25879 */
25880 #if SQLITE_TEST
25881 # define TRACE(X)   if( sqlite3_btree_trace ){ printf X; fflush(stdout); }
25882 #else
25883 # define TRACE(X)
25884 #endif
25885
25886 /*
25887 ** Routines to read and write variable-length integers.  These used to
25888 ** be defined locally, but now we use the varint routines in the util.c
25889 ** file.
25890 */
25891 #define getVarint    sqlite3GetVarint
25892 #define getVarint32(A,B)  ((*B=*(A))<=0x7f?1:sqlite3GetVarint32(A,B))
25893 #define putVarint    sqlite3PutVarint
25894
25895 /* The database page the PENDING_BYTE occupies. This page is never used.
25896 ** TODO: This macro is very similary to PAGER_MJ_PGNO() in pager.c. They
25897 ** should possibly be consolidated (presumably in pager.h).
25898 **
25899 ** If disk I/O is omitted (meaning that the database is stored purely
25900 ** in memory) then there is no pending byte.
25901 */
25902 #ifdef SQLITE_OMIT_DISKIO
25903 # define PENDING_BYTE_PAGE(pBt)  0x7fffffff
25904 #else
25905 # define PENDING_BYTE_PAGE(pBt) ((PENDING_BYTE/(pBt)->pageSize)+1)
25906 #endif
25907
25908 /*
25909 ** A linked list of the following structures is stored at BtShared.pLock.
25910 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
25911 ** is opened on the table with root page BtShared.iTable. Locks are removed
25912 ** from this list when a transaction is committed or rolled back, or when
25913 ** a btree handle is closed.
25914 */
25915 struct BtLock {
25916   Btree *pBtree;        /* Btree handle holding this lock */
25917   Pgno iTable;          /* Root page of table */
25918   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
25919   BtLock *pNext;        /* Next in BtShared.pLock list */
25920 };
25921
25922 /* Candidate values for BtLock.eLock */
25923 #define READ_LOCK     1
25924 #define WRITE_LOCK    2
25925
25926 /*
25927 ** These macros define the location of the pointer-map entry for a 
25928 ** database page. The first argument to each is the number of usable
25929 ** bytes on each page of the database (often 1024). The second is the
25930 ** page number to look up in the pointer map.
25931 **
25932 ** PTRMAP_PAGENO returns the database page number of the pointer-map
25933 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
25934 ** the offset of the requested map entry.
25935 **
25936 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
25937 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
25938 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
25939 ** this test.
25940 */
25941 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
25942 #define PTRMAP_PTROFFSET(pBt, pgno) (5*(pgno-ptrmapPageno(pBt, pgno)-1))
25943 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
25944
25945 /*
25946 ** The pointer map is a lookup table that identifies the parent page for
25947 ** each child page in the database file.  The parent page is the page that
25948 ** contains a pointer to the child.  Every page in the database contains
25949 ** 0 or 1 parent pages.  (In this context 'database page' refers
25950 ** to any page that is not part of the pointer map itself.)  Each pointer map
25951 ** entry consists of a single byte 'type' and a 4 byte parent page number.
25952 ** The PTRMAP_XXX identifiers below are the valid types.
25953 **
25954 ** The purpose of the pointer map is to facility moving pages from one
25955 ** position in the file to another as part of autovacuum.  When a page
25956 ** is moved, the pointer in its parent must be updated to point to the
25957 ** new location.  The pointer map is used to locate the parent page quickly.
25958 **
25959 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
25960 **                  used in this case.
25961 **
25962 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
25963 **                  is not used in this case.
25964 **
25965 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
25966 **                   overflow pages. The page number identifies the page that
25967 **                   contains the cell with a pointer to this overflow page.
25968 **
25969 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
25970 **                   overflow pages. The page-number identifies the previous
25971 **                   page in the overflow page list.
25972 **
25973 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
25974 **               identifies the parent page in the btree.
25975 */
25976 #define PTRMAP_ROOTPAGE 1
25977 #define PTRMAP_FREEPAGE 2
25978 #define PTRMAP_OVERFLOW1 3
25979 #define PTRMAP_OVERFLOW2 4
25980 #define PTRMAP_BTREE 5
25981
25982 /* A bunch of assert() statements to check the transaction state variables
25983 ** of handle p (type Btree*) are internally consistent.
25984 */
25985 #define btreeIntegrity(p) \
25986   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
25987   assert( p->pBt->inTransaction>=p->inTrans ); 
25988
25989
25990 /*
25991 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
25992 ** if the database supports auto-vacuum or not. Because it is used
25993 ** within an expression that is an argument to another macro 
25994 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
25995 ** So, this macro is defined instead.
25996 */
25997 #ifndef SQLITE_OMIT_AUTOVACUUM
25998 #define ISAUTOVACUUM (pBt->autoVacuum)
25999 #else
26000 #define ISAUTOVACUUM 0
26001 #endif
26002
26003
26004 /*
26005 ** This structure is passed around through all the sanity checking routines
26006 ** in order to keep track of some global state information.
26007 */
26008 typedef struct IntegrityCk IntegrityCk;
26009 struct IntegrityCk {
26010   BtShared *pBt;    /* The tree being checked out */
26011   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
26012   int nPage;        /* Number of pages in the database */
26013   int *anRef;       /* Number of times each page is referenced */
26014   int mxErr;        /* Stop accumulating errors when this reaches zero */
26015   char *zErrMsg;    /* An error message.  NULL if no errors seen. */
26016   int nErr;         /* Number of messages written to zErrMsg so far */
26017 };
26018
26019 /*
26020 ** Read or write a two- and four-byte big-endian integer values.
26021 */
26022 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
26023 #define put2byte(p,v) ((p)[0] = (v)>>8, (p)[1] = (v))
26024 #define get4byte sqlite3Get4byte
26025 #define put4byte sqlite3Put4byte
26026
26027 /*
26028 ** Internal routines that should be accessed by the btree layer only.
26029 */
26030 SQLITE_PRIVATE int sqlite3BtreeGetPage(BtShared*, Pgno, MemPage**, int);
26031 SQLITE_PRIVATE int sqlite3BtreeInitPage(MemPage *pPage, MemPage *pParent);
26032 SQLITE_PRIVATE void sqlite3BtreeParseCellPtr(MemPage*, u8*, CellInfo*);
26033 SQLITE_PRIVATE void sqlite3BtreeParseCell(MemPage*, int, CellInfo*);
26034 #ifdef SQLITE_TEST
26035 SQLITE_PRIVATE u8 *sqlite3BtreeFindCell(MemPage *pPage, int iCell);
26036 #endif
26037 SQLITE_PRIVATE int sqlite3BtreeRestoreOrClearCursorPosition(BtCursor *pCur);
26038 SQLITE_PRIVATE void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur);
26039 SQLITE_PRIVATE void sqlite3BtreeReleaseTempCursor(BtCursor *pCur);
26040 SQLITE_PRIVATE int sqlite3BtreeIsRootPage(MemPage *pPage);
26041 SQLITE_PRIVATE void sqlite3BtreeMoveToParent(BtCursor *pCur);
26042
26043 /************** End of btreeInt.h ********************************************/
26044 /************** Continuing where we left off in btmutex.c ********************/
26045 #if SQLITE_THREADSAFE && !defined(SQLITE_OMIT_SHARED_CACHE)
26046
26047
26048 /*
26049 ** Enter a mutex on the given BTree object.
26050 **
26051 ** If the object is not sharable, then no mutex is ever required
26052 ** and this routine is a no-op.  The underlying mutex is non-recursive.
26053 ** But we keep a reference count in Btree.wantToLock so the behavior
26054 ** of this interface is recursive.
26055 **
26056 ** To avoid deadlocks, multiple Btrees are locked in the same order
26057 ** by all database connections.  The p->pNext is a list of other
26058 ** Btrees belonging to the same database connection as the p Btree
26059 ** which need to be locked after p.  If we cannot get a lock on
26060 ** p, then first unlock all of the others on p->pNext, then wait
26061 ** for the lock to become available on p, then relock all of the
26062 ** subsequent Btrees that desire a lock.
26063 */
26064 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
26065   Btree *pLater;
26066
26067   /* Some basic sanity checking on the Btree.  The list of Btrees
26068   ** connected by pNext and pPrev should be in sorted order by
26069   ** Btree.pBt value. All elements of the list should belong to
26070   ** the same connection. Only shared Btrees are on the list. */
26071   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
26072   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
26073   assert( p->pNext==0 || p->pNext->db==p->db );
26074   assert( p->pPrev==0 || p->pPrev->db==p->db );
26075   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
26076
26077   /* Check for locking consistency */
26078   assert( !p->locked || p->wantToLock>0 );
26079   assert( p->sharable || p->wantToLock==0 );
26080
26081   /* We should already hold a lock on the database connection */
26082   assert( sqlite3_mutex_held(p->db->mutex) );
26083
26084   if( !p->sharable ) return;
26085   p->wantToLock++;
26086   if( p->locked ) return;
26087
26088   /* In most cases, we should be able to acquire the lock we
26089   ** want without having to go throught the ascending lock
26090   ** procedure that follows.  Just be sure not to block.
26091   */
26092   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
26093     p->locked = 1;
26094     return;
26095   }
26096
26097   /* To avoid deadlock, first release all locks with a larger
26098   ** BtShared address.  Then acquire our lock.  Then reacquire
26099   ** the other BtShared locks that we used to hold in ascending
26100   ** order.
26101   */
26102   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
26103     assert( pLater->sharable );
26104     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
26105     assert( !pLater->locked || pLater->wantToLock>0 );
26106     if( pLater->locked ){
26107       sqlite3_mutex_leave(pLater->pBt->mutex);
26108       pLater->locked = 0;
26109     }
26110   }
26111   sqlite3_mutex_enter(p->pBt->mutex);
26112   p->locked = 1;
26113   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
26114     if( pLater->wantToLock ){
26115       sqlite3_mutex_enter(pLater->pBt->mutex);
26116       pLater->locked = 1;
26117     }
26118   }
26119 }
26120
26121 /*
26122 ** Exit the recursive mutex on a Btree.
26123 */
26124 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
26125   if( p->sharable ){
26126     assert( p->wantToLock>0 );
26127     p->wantToLock--;
26128     if( p->wantToLock==0 ){
26129       assert( p->locked );
26130       sqlite3_mutex_leave(p->pBt->mutex);
26131       p->locked = 0;
26132     }
26133   }
26134 }
26135
26136 #ifndef NDEBUG
26137 /*
26138 ** Return true if the BtShared mutex is held on the btree.  
26139 **
26140 ** This routine makes no determination one why or another if the
26141 ** database connection mutex is held.
26142 **
26143 ** This routine is used only from within assert() statements.
26144 */
26145 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
26146   return (p->sharable==0 ||
26147              (p->locked && p->wantToLock && sqlite3_mutex_held(p->pBt->mutex)));
26148 }
26149 #endif
26150
26151
26152 #ifndef SQLITE_OMIT_INCRBLOB
26153 /*
26154 ** Enter and leave a mutex on a Btree given a cursor owned by that
26155 ** Btree.  These entry points are used by incremental I/O and can be
26156 ** omitted if that module is not used.
26157 */
26158 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
26159   sqlite3BtreeEnter(pCur->pBtree);
26160 }
26161 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
26162   sqlite3BtreeLeave(pCur->pBtree);
26163 }
26164 #endif /* SQLITE_OMIT_INCRBLOB */
26165
26166
26167 /*
26168 ** Enter the mutex on every Btree associated with a database
26169 ** connection.  This is needed (for example) prior to parsing
26170 ** a statement since we will be comparing table and column names
26171 ** against all schemas and we do not want those schemas being
26172 ** reset out from under us.
26173 **
26174 ** There is a corresponding leave-all procedures.
26175 **
26176 ** Enter the mutexes in accending order by BtShared pointer address
26177 ** to avoid the possibility of deadlock when two threads with
26178 ** two or more btrees in common both try to lock all their btrees
26179 ** at the same instant.
26180 */
26181 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
26182   int i;
26183   Btree *p, *pLater;
26184   assert( sqlite3_mutex_held(db->mutex) );
26185   for(i=0; i<db->nDb; i++){
26186     p = db->aDb[i].pBt;
26187     if( p && p->sharable ){
26188       p->wantToLock++;
26189       if( !p->locked ){
26190         assert( p->wantToLock==1 );
26191         while( p->pPrev ) p = p->pPrev;
26192         while( p->locked && p->pNext ) p = p->pNext;
26193         for(pLater = p->pNext; pLater; pLater=pLater->pNext){
26194           if( pLater->locked ){
26195             sqlite3_mutex_leave(pLater->pBt->mutex);
26196             pLater->locked = 0;
26197           }
26198         }
26199         while( p ){
26200           sqlite3_mutex_enter(p->pBt->mutex);
26201           p->locked++;
26202           p = p->pNext;
26203         }
26204       }
26205     }
26206   }
26207 }
26208 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
26209   int i;
26210   Btree *p;
26211   assert( sqlite3_mutex_held(db->mutex) );
26212   for(i=0; i<db->nDb; i++){
26213     p = db->aDb[i].pBt;
26214     if( p && p->sharable ){
26215       assert( p->wantToLock>0 );
26216       p->wantToLock--;
26217       if( p->wantToLock==0 ){
26218         assert( p->locked );
26219         sqlite3_mutex_leave(p->pBt->mutex);
26220         p->locked = 0;
26221       }
26222     }
26223   }
26224 }
26225
26226 #ifndef NDEBUG
26227 /*
26228 ** Return true if the current thread holds the database connection
26229 ** mutex and all required BtShared mutexes.
26230 **
26231 ** This routine is used inside assert() statements only.
26232 */
26233 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
26234   int i;
26235   if( !sqlite3_mutex_held(db->mutex) ){
26236     return 0;
26237   }
26238   for(i=0; i<db->nDb; i++){
26239     Btree *p;
26240     p = db->aDb[i].pBt;
26241     if( p && p->sharable &&
26242          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
26243       return 0;
26244     }
26245   }
26246   return 1;
26247 }
26248 #endif /* NDEBUG */
26249
26250 /*
26251 ** Potentially dd a new Btree pointer to a BtreeMutexArray.
26252 ** Really only add the Btree if it can possibly be shared with
26253 ** another database connection.
26254 **
26255 ** The Btrees are kept in sorted order by pBtree->pBt.  That
26256 ** way when we go to enter all the mutexes, we can enter them
26257 ** in order without every having to backup and retry and without
26258 ** worrying about deadlock.
26259 **
26260 ** The number of shared btrees will always be small (usually 0 or 1)
26261 ** so an insertion sort is an adequate algorithm here.
26262 */
26263 SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
26264   int i, j;
26265   BtShared *pBt;
26266   if( pBtree==0 || pBtree->sharable==0 ) return;
26267 #ifndef NDEBUG
26268   {
26269     for(i=0; i<pArray->nMutex; i++){
26270       assert( pArray->aBtree[i]!=pBtree );
26271     }
26272   }
26273 #endif
26274   assert( pArray->nMutex>=0 );
26275   assert( pArray->nMutex<sizeof(pArray->aBtree)/sizeof(pArray->aBtree[0])-1 );
26276   pBt = pBtree->pBt;
26277   for(i=0; i<pArray->nMutex; i++){
26278     assert( pArray->aBtree[i]!=pBtree );
26279     if( pArray->aBtree[i]->pBt>pBt ){
26280       for(j=pArray->nMutex; j>i; j--){
26281         pArray->aBtree[j] = pArray->aBtree[j-1];
26282       }
26283       pArray->aBtree[i] = pBtree;
26284       pArray->nMutex++;
26285       return;
26286     }
26287   }
26288   pArray->aBtree[pArray->nMutex++] = pBtree;
26289 }
26290
26291 /*
26292 ** Enter the mutex of every btree in the array.  This routine is
26293 ** called at the beginning of sqlite3VdbeExec().  The mutexes are
26294 ** exited at the end of the same function.
26295 */
26296 SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
26297   int i;
26298   for(i=0; i<pArray->nMutex; i++){
26299     Btree *p = pArray->aBtree[i];
26300     /* Some basic sanity checking */
26301     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
26302     assert( !p->locked || p->wantToLock>0 );
26303
26304     /* We should already hold a lock on the database connection */
26305     assert( sqlite3_mutex_held(p->db->mutex) );
26306
26307     p->wantToLock++;
26308     if( !p->locked && p->sharable ){
26309       sqlite3_mutex_enter(p->pBt->mutex);
26310       p->locked = 1;
26311     }
26312   }
26313 }
26314
26315 /*
26316 ** Leave the mutex of every btree in the group.
26317 */
26318 SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
26319   int i;
26320   for(i=0; i<pArray->nMutex; i++){
26321     Btree *p = pArray->aBtree[i];
26322     /* Some basic sanity checking */
26323     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
26324     assert( p->locked || !p->sharable );
26325     assert( p->wantToLock>0 );
26326
26327     /* We should already hold a lock on the database connection */
26328     assert( sqlite3_mutex_held(p->db->mutex) );
26329
26330     p->wantToLock--;
26331     if( p->wantToLock==0 && p->locked ){
26332       sqlite3_mutex_leave(p->pBt->mutex);
26333       p->locked = 0;
26334     }
26335   }
26336 }
26337
26338
26339 #endif  /* SQLITE_THREADSAFE && !SQLITE_OMIT_SHARED_CACHE */
26340
26341 /************** End of btmutex.c *********************************************/
26342 /************** Begin file btree.c *******************************************/
26343 /*
26344 ** 2004 April 6
26345 **
26346 ** The author disclaims copyright to this source code.  In place of
26347 ** a legal notice, here is a blessing:
26348 **
26349 **    May you do good and not evil.
26350 **    May you find forgiveness for yourself and forgive others.
26351 **    May you share freely, never taking more than you give.
26352 **
26353 *************************************************************************
26354 ** $Id: btree.c,v 1.433 2007/12/13 21:54:11 drh Exp $
26355 **
26356 ** This file implements a external (disk-based) database using BTrees.
26357 ** See the header comment on "btreeInt.h" for additional information.
26358 ** Including a description of file format and an overview of operation.
26359 */
26360
26361 /*
26362 ** The header string that appears at the beginning of every
26363 ** SQLite database.
26364 */
26365 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
26366
26367 /*
26368 ** Set this global variable to 1 to enable tracing using the TRACE
26369 ** macro.
26370 */
26371 #if SQLITE_TEST
26372 int sqlite3_btree_trace=0;  /* True to enable tracing */
26373 #endif
26374
26375
26376
26377 #ifndef SQLITE_OMIT_SHARED_CACHE
26378 /*
26379 ** A flag to indicate whether or not shared cache is enabled.  Also,
26380 ** a list of BtShared objects that are eligible for participation
26381 ** in shared cache.  The variables have file scope during normal builds,
26382 ** but the test harness needs to access these variables so we make them
26383 ** global for test builds.
26384 */
26385 #ifdef SQLITE_TEST
26386 SQLITE_PRIVATE BtShared *sqlite3SharedCacheList = 0;
26387 SQLITE_PRIVATE int sqlite3SharedCacheEnabled = 0;
26388 #else
26389 static BtShared *sqlite3SharedCacheList = 0;
26390 static int sqlite3SharedCacheEnabled = 0;
26391 #endif
26392 #endif /* SQLITE_OMIT_SHARED_CACHE */
26393
26394 #ifndef SQLITE_OMIT_SHARED_CACHE
26395 /*
26396 ** Enable or disable the shared pager and schema features.
26397 **
26398 ** This routine has no effect on existing database connections.
26399 ** The shared cache setting effects only future calls to
26400 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
26401 */
26402 SQLITE_API int sqlite3_enable_shared_cache(int enable){
26403   sqlite3SharedCacheEnabled = enable;
26404   return SQLITE_OK;
26405 }
26406 #endif
26407
26408
26409 /*
26410 ** Forward declaration
26411 */
26412 static int checkReadLocks(Btree*,Pgno,BtCursor*);
26413
26414
26415 #ifdef SQLITE_OMIT_SHARED_CACHE
26416   /*
26417   ** The functions queryTableLock(), lockTable() and unlockAllTables()
26418   ** manipulate entries in the BtShared.pLock linked list used to store
26419   ** shared-cache table level locks. If the library is compiled with the
26420   ** shared-cache feature disabled, then there is only ever one user
26421   ** of each BtShared structure and so this locking is not necessary. 
26422   ** So define the lock related functions as no-ops.
26423   */
26424   #define queryTableLock(a,b,c) SQLITE_OK
26425   #define lockTable(a,b,c) SQLITE_OK
26426   #define unlockAllTables(a)
26427 #endif
26428
26429 #ifndef SQLITE_OMIT_SHARED_CACHE
26430 /*
26431 ** Query to see if btree handle p may obtain a lock of type eLock 
26432 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
26433 ** SQLITE_OK if the lock may be obtained (by calling lockTable()), or
26434 ** SQLITE_LOCKED if not.
26435 */
26436 static int queryTableLock(Btree *p, Pgno iTab, u8 eLock){
26437   BtShared *pBt = p->pBt;
26438   BtLock *pIter;
26439
26440   assert( sqlite3BtreeHoldsMutex(p) );
26441   
26442   /* This is a no-op if the shared-cache is not enabled */
26443   if( !p->sharable ){
26444     return SQLITE_OK;
26445   }
26446
26447   /* This (along with lockTable()) is where the ReadUncommitted flag is
26448   ** dealt with. If the caller is querying for a read-lock and the flag is
26449   ** set, it is unconditionally granted - even if there are write-locks
26450   ** on the table. If a write-lock is requested, the ReadUncommitted flag
26451   ** is not considered.
26452   **
26453   ** In function lockTable(), if a read-lock is demanded and the 
26454   ** ReadUncommitted flag is set, no entry is added to the locks list 
26455   ** (BtShared.pLock).
26456   **
26457   ** To summarize: If the ReadUncommitted flag is set, then read cursors do
26458   ** not create or respect table locks. The locking procedure for a 
26459   ** write-cursor does not change.
26460   */
26461   if( 
26462     !p->db || 
26463     0==(p->db->flags&SQLITE_ReadUncommitted) || 
26464     eLock==WRITE_LOCK ||
26465     iTab==MASTER_ROOT
26466   ){
26467     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
26468       if( pIter->pBtree!=p && pIter->iTable==iTab && 
26469           (pIter->eLock!=eLock || eLock!=READ_LOCK) ){
26470         return SQLITE_LOCKED;
26471       }
26472     }
26473   }
26474   return SQLITE_OK;
26475 }
26476 #endif /* !SQLITE_OMIT_SHARED_CACHE */
26477
26478 #ifndef SQLITE_OMIT_SHARED_CACHE
26479 /*
26480 ** Add a lock on the table with root-page iTable to the shared-btree used
26481 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
26482 ** WRITE_LOCK.
26483 **
26484 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
26485 ** SQLITE_NOMEM may also be returned.
26486 */
26487 static int lockTable(Btree *p, Pgno iTable, u8 eLock){
26488   BtShared *pBt = p->pBt;
26489   BtLock *pLock = 0;
26490   BtLock *pIter;
26491
26492   assert( sqlite3BtreeHoldsMutex(p) );
26493
26494   /* This is a no-op if the shared-cache is not enabled */
26495   if( !p->sharable ){
26496     return SQLITE_OK;
26497   }
26498
26499   assert( SQLITE_OK==queryTableLock(p, iTable, eLock) );
26500
26501   /* If the read-uncommitted flag is set and a read-lock is requested,
26502   ** return early without adding an entry to the BtShared.pLock list. See
26503   ** comment in function queryTableLock() for more info on handling 
26504   ** the ReadUncommitted flag.
26505   */
26506   if( 
26507     (p->db) && 
26508     (p->db->flags&SQLITE_ReadUncommitted) && 
26509     (eLock==READ_LOCK) &&
26510     iTable!=MASTER_ROOT
26511   ){
26512     return SQLITE_OK;
26513   }
26514
26515   /* First search the list for an existing lock on this table. */
26516   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
26517     if( pIter->iTable==iTable && pIter->pBtree==p ){
26518       pLock = pIter;
26519       break;
26520     }
26521   }
26522
26523   /* If the above search did not find a BtLock struct associating Btree p
26524   ** with table iTable, allocate one and link it into the list.
26525   */
26526   if( !pLock ){
26527     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
26528     if( !pLock ){
26529       return SQLITE_NOMEM;
26530     }
26531     pLock->iTable = iTable;
26532     pLock->pBtree = p;
26533     pLock->pNext = pBt->pLock;
26534     pBt->pLock = pLock;
26535   }
26536
26537   /* Set the BtLock.eLock variable to the maximum of the current lock
26538   ** and the requested lock. This means if a write-lock was already held
26539   ** and a read-lock requested, we don't incorrectly downgrade the lock.
26540   */
26541   assert( WRITE_LOCK>READ_LOCK );
26542   if( eLock>pLock->eLock ){
26543     pLock->eLock = eLock;
26544   }
26545
26546   return SQLITE_OK;
26547 }
26548 #endif /* !SQLITE_OMIT_SHARED_CACHE */
26549
26550 #ifndef SQLITE_OMIT_SHARED_CACHE
26551 /*
26552 ** Release all the table locks (locks obtained via calls to the lockTable()
26553 ** procedure) held by Btree handle p.
26554 */
26555 static void unlockAllTables(Btree *p){
26556   BtLock **ppIter = &p->pBt->pLock;
26557
26558   assert( sqlite3BtreeHoldsMutex(p) );
26559   assert( p->sharable || 0==*ppIter );
26560
26561   while( *ppIter ){
26562     BtLock *pLock = *ppIter;
26563     if( pLock->pBtree==p ){
26564       *ppIter = pLock->pNext;
26565       sqlite3_free(pLock);
26566     }else{
26567       ppIter = &pLock->pNext;
26568     }
26569   }
26570 }
26571 #endif /* SQLITE_OMIT_SHARED_CACHE */
26572
26573 static void releasePage(MemPage *pPage);  /* Forward reference */
26574
26575 /*
26576 ** Verify that the cursor holds a mutex on the BtShared
26577 */
26578 #ifndef NDEBUG
26579 static int cursorHoldsMutex(BtCursor *p){
26580   return sqlite3_mutex_held(p->pBt->mutex);
26581 }
26582 #endif
26583
26584
26585 #ifndef SQLITE_OMIT_INCRBLOB
26586 /*
26587 ** Invalidate the overflow page-list cache for cursor pCur, if any.
26588 */
26589 static void invalidateOverflowCache(BtCursor *pCur){
26590   assert( cursorHoldsMutex(pCur) );
26591   sqlite3_free(pCur->aOverflow);
26592   pCur->aOverflow = 0;
26593 }
26594
26595 /*
26596 ** Invalidate the overflow page-list cache for all cursors opened
26597 ** on the shared btree structure pBt.
26598 */
26599 static void invalidateAllOverflowCache(BtShared *pBt){
26600   BtCursor *p;
26601   assert( sqlite3_mutex_held(pBt->mutex) );
26602   for(p=pBt->pCursor; p; p=p->pNext){
26603     invalidateOverflowCache(p);
26604   }
26605 }
26606 #else
26607   #define invalidateOverflowCache(x)
26608   #define invalidateAllOverflowCache(x)
26609 #endif
26610
26611 /*
26612 ** Save the current cursor position in the variables BtCursor.nKey 
26613 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
26614 */
26615 static int saveCursorPosition(BtCursor *pCur){
26616   int rc;
26617
26618   assert( CURSOR_VALID==pCur->eState );
26619   assert( 0==pCur->pKey );
26620   assert( cursorHoldsMutex(pCur) );
26621
26622   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
26623
26624   /* If this is an intKey table, then the above call to BtreeKeySize()
26625   ** stores the integer key in pCur->nKey. In this case this value is
26626   ** all that is required. Otherwise, if pCur is not open on an intKey
26627   ** table, then malloc space for and store the pCur->nKey bytes of key 
26628   ** data.
26629   */
26630   if( rc==SQLITE_OK && 0==pCur->pPage->intKey){
26631     void *pKey = sqlite3_malloc(pCur->nKey);
26632     if( pKey ){
26633       rc = sqlite3BtreeKey(pCur, 0, pCur->nKey, pKey);
26634       if( rc==SQLITE_OK ){
26635         pCur->pKey = pKey;
26636       }else{
26637         sqlite3_free(pKey);
26638       }
26639     }else{
26640       rc = SQLITE_NOMEM;
26641     }
26642   }
26643   assert( !pCur->pPage->intKey || !pCur->pKey );
26644
26645   if( rc==SQLITE_OK ){
26646     releasePage(pCur->pPage);
26647     pCur->pPage = 0;
26648     pCur->eState = CURSOR_REQUIRESEEK;
26649   }
26650
26651   invalidateOverflowCache(pCur);
26652   return rc;
26653 }
26654
26655 /*
26656 ** Save the positions of all cursors except pExcept open on the table 
26657 ** with root-page iRoot. Usually, this is called just before cursor
26658 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
26659 */
26660 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
26661   BtCursor *p;
26662   assert( sqlite3_mutex_held(pBt->mutex) );
26663   assert( pExcept==0 || pExcept->pBt==pBt );
26664   for(p=pBt->pCursor; p; p=p->pNext){
26665     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
26666         p->eState==CURSOR_VALID ){
26667       int rc = saveCursorPosition(p);
26668       if( SQLITE_OK!=rc ){
26669         return rc;
26670       }
26671     }
26672   }
26673   return SQLITE_OK;
26674 }
26675
26676 /*
26677 ** Clear the current cursor position.
26678 */
26679 static void clearCursorPosition(BtCursor *pCur){
26680   assert( cursorHoldsMutex(pCur) );
26681   sqlite3_free(pCur->pKey);
26682   pCur->pKey = 0;
26683   pCur->eState = CURSOR_INVALID;
26684 }
26685
26686 /*
26687 ** Restore the cursor to the position it was in (or as close to as possible)
26688 ** when saveCursorPosition() was called. Note that this call deletes the 
26689 ** saved position info stored by saveCursorPosition(), so there can be
26690 ** at most one effective restoreOrClearCursorPosition() call after each 
26691 ** saveCursorPosition().
26692 **
26693 ** If the second argument argument - doSeek - is false, then instead of 
26694 ** returning the cursor to its saved position, any saved position is deleted
26695 ** and the cursor state set to CURSOR_INVALID.
26696 */
26697 SQLITE_PRIVATE int sqlite3BtreeRestoreOrClearCursorPosition(BtCursor *pCur){
26698   int rc;
26699   assert( cursorHoldsMutex(pCur) );
26700   assert( pCur->eState>=CURSOR_REQUIRESEEK );
26701   if( pCur->eState==CURSOR_FAULT ){
26702     return pCur->skip;
26703   }
26704 #ifndef SQLITE_OMIT_INCRBLOB
26705   if( pCur->isIncrblobHandle ){
26706     return SQLITE_ABORT;
26707   }
26708 #endif
26709   pCur->eState = CURSOR_INVALID;
26710   rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skip);
26711   if( rc==SQLITE_OK ){
26712     sqlite3_free(pCur->pKey);
26713     pCur->pKey = 0;
26714     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
26715   }
26716   return rc;
26717 }
26718
26719 #define restoreOrClearCursorPosition(p) \
26720   (p->eState>=CURSOR_REQUIRESEEK ? \
26721          sqlite3BtreeRestoreOrClearCursorPosition(p) : \
26722          SQLITE_OK)
26723
26724 #ifndef SQLITE_OMIT_AUTOVACUUM
26725 /*
26726 ** Given a page number of a regular database page, return the page
26727 ** number for the pointer-map page that contains the entry for the
26728 ** input page number.
26729 */
26730 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
26731   int nPagesPerMapPage, iPtrMap, ret;
26732   assert( sqlite3_mutex_held(pBt->mutex) );
26733   nPagesPerMapPage = (pBt->usableSize/5)+1;
26734   iPtrMap = (pgno-2)/nPagesPerMapPage;
26735   ret = (iPtrMap*nPagesPerMapPage) + 2; 
26736   if( ret==PENDING_BYTE_PAGE(pBt) ){
26737     ret++;
26738   }
26739   return ret;
26740 }
26741
26742 /*
26743 ** Write an entry into the pointer map.
26744 **
26745 ** This routine updates the pointer map entry for page number 'key'
26746 ** so that it maps to type 'eType' and parent page number 'pgno'.
26747 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
26748 */
26749 static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
26750   DbPage *pDbPage;  /* The pointer map page */
26751   u8 *pPtrmap;      /* The pointer map data */
26752   Pgno iPtrmap;     /* The pointer map page number */
26753   int offset;       /* Offset in pointer map page */
26754   int rc;
26755
26756   assert( sqlite3_mutex_held(pBt->mutex) );
26757   /* The master-journal page number must never be used as a pointer map page */
26758   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
26759
26760   assert( pBt->autoVacuum );
26761   if( key==0 ){
26762     return SQLITE_CORRUPT_BKPT;
26763   }
26764   iPtrmap = PTRMAP_PAGENO(pBt, key);
26765   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
26766   if( rc!=SQLITE_OK ){
26767     return rc;
26768   }
26769   offset = PTRMAP_PTROFFSET(pBt, key);
26770   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
26771
26772   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
26773     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
26774     rc = sqlite3PagerWrite(pDbPage);
26775     if( rc==SQLITE_OK ){
26776       pPtrmap[offset] = eType;
26777       put4byte(&pPtrmap[offset+1], parent);
26778     }
26779   }
26780
26781   sqlite3PagerUnref(pDbPage);
26782   return rc;
26783 }
26784
26785 /*
26786 ** Read an entry from the pointer map.
26787 **
26788 ** This routine retrieves the pointer map entry for page 'key', writing
26789 ** the type and parent page number to *pEType and *pPgno respectively.
26790 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
26791 */
26792 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
26793   DbPage *pDbPage;   /* The pointer map page */
26794   int iPtrmap;       /* Pointer map page index */
26795   u8 *pPtrmap;       /* Pointer map page data */
26796   int offset;        /* Offset of entry in pointer map */
26797   int rc;
26798
26799   assert( sqlite3_mutex_held(pBt->mutex) );
26800
26801   iPtrmap = PTRMAP_PAGENO(pBt, key);
26802   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
26803   if( rc!=0 ){
26804     return rc;
26805   }
26806   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
26807
26808   offset = PTRMAP_PTROFFSET(pBt, key);
26809   assert( pEType!=0 );
26810   *pEType = pPtrmap[offset];
26811   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
26812
26813   sqlite3PagerUnref(pDbPage);
26814   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
26815   return SQLITE_OK;
26816 }
26817
26818 #endif /* SQLITE_OMIT_AUTOVACUUM */
26819
26820 /*
26821 ** Given a btree page and a cell index (0 means the first cell on
26822 ** the page, 1 means the second cell, and so forth) return a pointer
26823 ** to the cell content.
26824 **
26825 ** This routine works only for pages that do not contain overflow cells.
26826 */
26827 #define findCell(pPage, iCell) \
26828   ((pPage)->aData + get2byte(&(pPage)->aData[(pPage)->cellOffset+2*(iCell)]))
26829 #ifdef SQLITE_TEST
26830 SQLITE_PRIVATE u8 *sqlite3BtreeFindCell(MemPage *pPage, int iCell){
26831   assert( iCell>=0 );
26832   assert( iCell<get2byte(&pPage->aData[pPage->hdrOffset+3]) );
26833   return findCell(pPage, iCell);
26834 }
26835 #endif
26836
26837 /*
26838 ** This a more complex version of sqlite3BtreeFindCell() that works for
26839 ** pages that do contain overflow cells.  See insert
26840 */
26841 static u8 *findOverflowCell(MemPage *pPage, int iCell){
26842   int i;
26843   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
26844   for(i=pPage->nOverflow-1; i>=0; i--){
26845     int k;
26846     struct _OvflCell *pOvfl;
26847     pOvfl = &pPage->aOvfl[i];
26848     k = pOvfl->idx;
26849     if( k<=iCell ){
26850       if( k==iCell ){
26851         return pOvfl->pCell;
26852       }
26853       iCell--;
26854     }
26855   }
26856   return findCell(pPage, iCell);
26857 }
26858
26859 /*
26860 ** Parse a cell content block and fill in the CellInfo structure.  There
26861 ** are two versions of this function.  sqlite3BtreeParseCell() takes a 
26862 ** cell index as the second argument and sqlite3BtreeParseCellPtr() 
26863 ** takes a pointer to the body of the cell as its second argument.
26864 **
26865 ** Within this file, the parseCell() macro can be called instead of
26866 ** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
26867 */
26868 SQLITE_PRIVATE void sqlite3BtreeParseCellPtr(
26869   MemPage *pPage,         /* Page containing the cell */
26870   u8 *pCell,              /* Pointer to the cell text. */
26871   CellInfo *pInfo         /* Fill in this structure */
26872 ){
26873   int n;                  /* Number bytes in cell content header */
26874   u32 nPayload;           /* Number of bytes of cell payload */
26875
26876   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
26877
26878   pInfo->pCell = pCell;
26879   assert( pPage->leaf==0 || pPage->leaf==1 );
26880   n = pPage->childPtrSize;
26881   assert( n==4-4*pPage->leaf );
26882   if( pPage->hasData ){
26883     n += getVarint32(&pCell[n], &nPayload);
26884   }else{
26885     nPayload = 0;
26886   }
26887   pInfo->nData = nPayload;
26888   if( pPage->intKey ){
26889     n += getVarint(&pCell[n], (u64 *)&pInfo->nKey);
26890   }else{
26891     u32 x;
26892     n += getVarint32(&pCell[n], &x);
26893     pInfo->nKey = x;
26894     nPayload += x;
26895   }
26896   pInfo->nPayload = nPayload;
26897   pInfo->nHeader = n;
26898   if( nPayload<=pPage->maxLocal ){
26899     /* This is the (easy) common case where the entire payload fits
26900     ** on the local page.  No overflow is required.
26901     */
26902     int nSize;          /* Total size of cell content in bytes */
26903     pInfo->nLocal = nPayload;
26904     pInfo->iOverflow = 0;
26905     nSize = nPayload + n;
26906     if( nSize<4 ){
26907       nSize = 4;        /* Minimum cell size is 4 */
26908     }
26909     pInfo->nSize = nSize;
26910   }else{
26911     /* If the payload will not fit completely on the local page, we have
26912     ** to decide how much to store locally and how much to spill onto
26913     ** overflow pages.  The strategy is to minimize the amount of unused
26914     ** space on overflow pages while keeping the amount of local storage
26915     ** in between minLocal and maxLocal.
26916     **
26917     ** Warning:  changing the way overflow payload is distributed in any
26918     ** way will result in an incompatible file format.
26919     */
26920     int minLocal;  /* Minimum amount of payload held locally */
26921     int maxLocal;  /* Maximum amount of payload held locally */
26922     int surplus;   /* Overflow payload available for local storage */
26923
26924     minLocal = pPage->minLocal;
26925     maxLocal = pPage->maxLocal;
26926     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
26927     if( surplus <= maxLocal ){
26928       pInfo->nLocal = surplus;
26929     }else{
26930       pInfo->nLocal = minLocal;
26931     }
26932     pInfo->iOverflow = pInfo->nLocal + n;
26933     pInfo->nSize = pInfo->iOverflow + 4;
26934   }
26935 }
26936 #define parseCell(pPage, iCell, pInfo) \
26937   sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
26938 SQLITE_PRIVATE void sqlite3BtreeParseCell(
26939   MemPage *pPage,         /* Page containing the cell */
26940   int iCell,              /* The cell index.  First cell is 0 */
26941   CellInfo *pInfo         /* Fill in this structure */
26942 ){
26943   parseCell(pPage, iCell, pInfo);
26944 }
26945
26946 /*
26947 ** Compute the total number of bytes that a Cell needs in the cell
26948 ** data area of the btree-page.  The return number includes the cell
26949 ** data header and the local payload, but not any overflow page or
26950 ** the space used by the cell pointer.
26951 */
26952 #ifndef NDEBUG
26953 static int cellSize(MemPage *pPage, int iCell){
26954   CellInfo info;
26955   sqlite3BtreeParseCell(pPage, iCell, &info);
26956   return info.nSize;
26957 }
26958 #endif
26959 static int cellSizePtr(MemPage *pPage, u8 *pCell){
26960   CellInfo info;
26961   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
26962   return info.nSize;
26963 }
26964
26965 #ifndef SQLITE_OMIT_AUTOVACUUM
26966 /*
26967 ** If the cell pCell, part of page pPage contains a pointer
26968 ** to an overflow page, insert an entry into the pointer-map
26969 ** for the overflow page.
26970 */
26971 static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
26972   if( pCell ){
26973     CellInfo info;
26974     sqlite3BtreeParseCellPtr(pPage, pCell, &info);
26975     assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
26976     if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
26977       Pgno ovfl = get4byte(&pCell[info.iOverflow]);
26978       return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
26979     }
26980   }
26981   return SQLITE_OK;
26982 }
26983 /*
26984 ** If the cell with index iCell on page pPage contains a pointer
26985 ** to an overflow page, insert an entry into the pointer-map
26986 ** for the overflow page.
26987 */
26988 static int ptrmapPutOvfl(MemPage *pPage, int iCell){
26989   u8 *pCell;
26990   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
26991   pCell = findOverflowCell(pPage, iCell);
26992   return ptrmapPutOvflPtr(pPage, pCell);
26993 }
26994 #endif
26995
26996
26997 /*
26998 ** Defragment the page given.  All Cells are moved to the
26999 ** end of the page and all free space is collected into one
27000 ** big FreeBlk that occurs in between the header and cell
27001 ** pointer array and the cell content area.
27002 */
27003 static int defragmentPage(MemPage *pPage){
27004   int i;                     /* Loop counter */
27005   int pc;                    /* Address of a i-th cell */
27006   int addr;                  /* Offset of first byte after cell pointer array */
27007   int hdr;                   /* Offset to the page header */
27008   int size;                  /* Size of a cell */
27009   int usableSize;            /* Number of usable bytes on a page */
27010   int cellOffset;            /* Offset to the cell pointer array */
27011   int brk;                   /* Offset to the cell content area */
27012   int nCell;                 /* Number of cells on the page */
27013   unsigned char *data;       /* The page data */
27014   unsigned char *temp;       /* Temp area for cell content */
27015
27016   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
27017   assert( pPage->pBt!=0 );
27018   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
27019   assert( pPage->nOverflow==0 );
27020   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
27021   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
27022   data = pPage->aData;
27023   hdr = pPage->hdrOffset;
27024   cellOffset = pPage->cellOffset;
27025   nCell = pPage->nCell;
27026   assert( nCell==get2byte(&data[hdr+3]) );
27027   usableSize = pPage->pBt->usableSize;
27028   brk = get2byte(&data[hdr+5]);
27029   memcpy(&temp[brk], &data[brk], usableSize - brk);
27030   brk = usableSize;
27031   for(i=0; i<nCell; i++){
27032     u8 *pAddr;     /* The i-th cell pointer */
27033     pAddr = &data[cellOffset + i*2];
27034     pc = get2byte(pAddr);
27035     assert( pc<pPage->pBt->usableSize );
27036     size = cellSizePtr(pPage, &temp[pc]);
27037     brk -= size;
27038     memcpy(&data[brk], &temp[pc], size);
27039     put2byte(pAddr, brk);
27040   }
27041   assert( brk>=cellOffset+2*nCell );
27042   put2byte(&data[hdr+5], brk);
27043   data[hdr+1] = 0;
27044   data[hdr+2] = 0;
27045   data[hdr+7] = 0;
27046   addr = cellOffset+2*nCell;
27047   memset(&data[addr], 0, brk-addr);
27048   return SQLITE_OK;
27049 }
27050
27051 /*
27052 ** Allocate nByte bytes of space on a page.
27053 **
27054 ** Return the index into pPage->aData[] of the first byte of
27055 ** the new allocation. Or return 0 if there is not enough free
27056 ** space on the page to satisfy the allocation request.
27057 **
27058 ** If the page contains nBytes of free space but does not contain
27059 ** nBytes of contiguous free space, then this routine automatically
27060 ** calls defragementPage() to consolidate all free space before 
27061 ** allocating the new chunk.
27062 */
27063 static int allocateSpace(MemPage *pPage, int nByte){
27064   int addr, pc, hdr;
27065   int size;
27066   int nFrag;
27067   int top;
27068   int nCell;
27069   int cellOffset;
27070   unsigned char *data;
27071   
27072   data = pPage->aData;
27073   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
27074   assert( pPage->pBt );
27075   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
27076   if( nByte<4 ) nByte = 4;
27077   if( pPage->nFree<nByte || pPage->nOverflow>0 ) return 0;
27078   pPage->nFree -= nByte;
27079   hdr = pPage->hdrOffset;
27080
27081   nFrag = data[hdr+7];
27082   if( nFrag<60 ){
27083     /* Search the freelist looking for a slot big enough to satisfy the
27084     ** space request. */
27085     addr = hdr+1;
27086     while( (pc = get2byte(&data[addr]))>0 ){
27087       size = get2byte(&data[pc+2]);
27088       if( size>=nByte ){
27089         if( size<nByte+4 ){
27090           memcpy(&data[addr], &data[pc], 2);
27091           data[hdr+7] = nFrag + size - nByte;
27092           return pc;
27093         }else{
27094           put2byte(&data[pc+2], size-nByte);
27095           return pc + size - nByte;
27096         }
27097       }
27098       addr = pc;
27099     }
27100   }
27101
27102   /* Allocate memory from the gap in between the cell pointer array
27103   ** and the cell content area.
27104   */
27105   top = get2byte(&data[hdr+5]);
27106   nCell = get2byte(&data[hdr+3]);
27107   cellOffset = pPage->cellOffset;
27108   if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
27109     if( defragmentPage(pPage) ) return 0;
27110     top = get2byte(&data[hdr+5]);
27111   }
27112   top -= nByte;
27113   assert( cellOffset + 2*nCell <= top );
27114   put2byte(&data[hdr+5], top);
27115   return top;
27116 }
27117
27118 /*
27119 ** Return a section of the pPage->aData to the freelist.
27120 ** The first byte of the new free block is pPage->aDisk[start]
27121 ** and the size of the block is "size" bytes.
27122 **
27123 ** Most of the effort here is involved in coalesing adjacent
27124 ** free blocks into a single big free block.
27125 */
27126 static void freeSpace(MemPage *pPage, int start, int size){
27127   int addr, pbegin, hdr;
27128   unsigned char *data = pPage->aData;
27129
27130   assert( pPage->pBt!=0 );
27131   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
27132   assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
27133   assert( (start + size)<=pPage->pBt->usableSize );
27134   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
27135   if( size<4 ) size = 4;
27136
27137 #ifdef SQLITE_SECURE_DELETE
27138   /* Overwrite deleted information with zeros when the SECURE_DELETE 
27139   ** option is enabled at compile-time */
27140   memset(&data[start], 0, size);
27141 #endif
27142
27143   /* Add the space back into the linked list of freeblocks */
27144   hdr = pPage->hdrOffset;
27145   addr = hdr + 1;
27146   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
27147     assert( pbegin<=pPage->pBt->usableSize-4 );
27148     assert( pbegin>addr );
27149     addr = pbegin;
27150   }
27151   assert( pbegin<=pPage->pBt->usableSize-4 );
27152   assert( pbegin>addr || pbegin==0 );
27153   put2byte(&data[addr], start);
27154   put2byte(&data[start], pbegin);
27155   put2byte(&data[start+2], size);
27156   pPage->nFree += size;
27157
27158   /* Coalesce adjacent free blocks */
27159   addr = pPage->hdrOffset + 1;
27160   while( (pbegin = get2byte(&data[addr]))>0 ){
27161     int pnext, psize;
27162     assert( pbegin>addr );
27163     assert( pbegin<=pPage->pBt->usableSize-4 );
27164     pnext = get2byte(&data[pbegin]);
27165     psize = get2byte(&data[pbegin+2]);
27166     if( pbegin + psize + 3 >= pnext && pnext>0 ){
27167       int frag = pnext - (pbegin+psize);
27168       assert( frag<=data[pPage->hdrOffset+7] );
27169       data[pPage->hdrOffset+7] -= frag;
27170       put2byte(&data[pbegin], get2byte(&data[pnext]));
27171       put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
27172     }else{
27173       addr = pbegin;
27174     }
27175   }
27176
27177   /* If the cell content area begins with a freeblock, remove it. */
27178   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
27179     int top;
27180     pbegin = get2byte(&data[hdr+1]);
27181     memcpy(&data[hdr+1], &data[pbegin], 2);
27182     top = get2byte(&data[hdr+5]);
27183     put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
27184   }
27185 }
27186
27187 /*
27188 ** Decode the flags byte (the first byte of the header) for a page
27189 ** and initialize fields of the MemPage structure accordingly.
27190 */
27191 static void decodeFlags(MemPage *pPage, int flagByte){
27192   BtShared *pBt;     /* A copy of pPage->pBt */
27193
27194   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
27195   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
27196   pPage->intKey = (flagByte & (PTF_INTKEY|PTF_LEAFDATA))!=0;
27197   pPage->zeroData = (flagByte & PTF_ZERODATA)!=0;
27198   pPage->leaf = (flagByte & PTF_LEAF)!=0;
27199   pPage->childPtrSize = 4*(pPage->leaf==0);
27200   pBt = pPage->pBt;
27201   if( flagByte & PTF_LEAFDATA ){
27202     pPage->leafData = 1;
27203     pPage->maxLocal = pBt->maxLeaf;
27204     pPage->minLocal = pBt->minLeaf;
27205   }else{
27206     pPage->leafData = 0;
27207     pPage->maxLocal = pBt->maxLocal;
27208     pPage->minLocal = pBt->minLocal;
27209   }
27210   pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
27211 }
27212
27213 /*
27214 ** Initialize the auxiliary information for a disk block.
27215 **
27216 ** The pParent parameter must be a pointer to the MemPage which
27217 ** is the parent of the page being initialized.  The root of a
27218 ** BTree has no parent and so for that page, pParent==NULL.
27219 **
27220 ** Return SQLITE_OK on success.  If we see that the page does
27221 ** not contain a well-formed database page, then return 
27222 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
27223 ** guarantee that the page is well-formed.  It only shows that
27224 ** we failed to detect any corruption.
27225 */
27226 SQLITE_PRIVATE int sqlite3BtreeInitPage(
27227   MemPage *pPage,        /* The page to be initialized */
27228   MemPage *pParent       /* The parent.  Might be NULL */
27229 ){
27230   int pc;            /* Address of a freeblock within pPage->aData[] */
27231   int hdr;           /* Offset to beginning of page header */
27232   u8 *data;          /* Equal to pPage->aData */
27233   BtShared *pBt;        /* The main btree structure */
27234   int usableSize;    /* Amount of usable space on each page */
27235   int cellOffset;    /* Offset from start of page to first cell pointer */
27236   int nFree;         /* Number of unused bytes on the page */
27237   int top;           /* First byte of the cell content area */
27238
27239   pBt = pPage->pBt;
27240   assert( pBt!=0 );
27241   assert( pParent==0 || pParent->pBt==pBt );
27242   assert( sqlite3_mutex_held(pBt->mutex) );
27243   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
27244   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
27245   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
27246   if( pPage->pParent!=pParent && (pPage->pParent!=0 || pPage->isInit) ){
27247     /* The parent page should never change unless the file is corrupt */
27248     return SQLITE_CORRUPT_BKPT;
27249   }
27250   if( pPage->isInit ) return SQLITE_OK;
27251   if( pPage->pParent==0 && pParent!=0 ){
27252     pPage->pParent = pParent;
27253     sqlite3PagerRef(pParent->pDbPage);
27254   }
27255   hdr = pPage->hdrOffset;
27256   data = pPage->aData;
27257   decodeFlags(pPage, data[hdr]);
27258   pPage->nOverflow = 0;
27259   pPage->idxShift = 0;
27260   usableSize = pBt->usableSize;
27261   pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
27262   top = get2byte(&data[hdr+5]);
27263   pPage->nCell = get2byte(&data[hdr+3]);
27264   if( pPage->nCell>MX_CELL(pBt) ){
27265     /* To many cells for a single page.  The page must be corrupt */
27266     return SQLITE_CORRUPT_BKPT;
27267   }
27268   if( pPage->nCell==0 && pParent!=0 && pParent->pgno!=1 ){
27269     /* All pages must have at least one cell, except for root pages */
27270     return SQLITE_CORRUPT_BKPT;
27271   }
27272
27273   /* Compute the total free space on the page */
27274   pc = get2byte(&data[hdr+1]);
27275   nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
27276   while( pc>0 ){
27277     int next, size;
27278     if( pc>usableSize-4 ){
27279       /* Free block is off the page */
27280       return SQLITE_CORRUPT_BKPT; 
27281     }
27282     next = get2byte(&data[pc]);
27283     size = get2byte(&data[pc+2]);
27284     if( next>0 && next<=pc+size+3 ){
27285       /* Free blocks must be in accending order */
27286       return SQLITE_CORRUPT_BKPT; 
27287     }
27288     nFree += size;
27289     pc = next;
27290   }
27291   pPage->nFree = nFree;
27292   if( nFree>=usableSize ){
27293     /* Free space cannot exceed total page size */
27294     return SQLITE_CORRUPT_BKPT; 
27295   }
27296
27297   pPage->isInit = 1;
27298   return SQLITE_OK;
27299 }
27300
27301 /*
27302 ** Set up a raw page so that it looks like a database page holding
27303 ** no entries.
27304 */
27305 static void zeroPage(MemPage *pPage, int flags){
27306   unsigned char *data = pPage->aData;
27307   BtShared *pBt = pPage->pBt;
27308   int hdr = pPage->hdrOffset;
27309   int first;
27310
27311   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
27312   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
27313   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
27314   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
27315   assert( sqlite3_mutex_held(pBt->mutex) );
27316   memset(&data[hdr], 0, pBt->usableSize - hdr);
27317   data[hdr] = flags;
27318   first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
27319   memset(&data[hdr+1], 0, 4);
27320   data[hdr+7] = 0;
27321   put2byte(&data[hdr+5], pBt->usableSize);
27322   pPage->nFree = pBt->usableSize - first;
27323   decodeFlags(pPage, flags);
27324   pPage->hdrOffset = hdr;
27325   pPage->cellOffset = first;
27326   pPage->nOverflow = 0;
27327   pPage->idxShift = 0;
27328   pPage->nCell = 0;
27329   pPage->isInit = 1;
27330 }
27331
27332 /*
27333 ** Get a page from the pager.  Initialize the MemPage.pBt and
27334 ** MemPage.aData elements if needed.
27335 **
27336 ** If the noContent flag is set, it means that we do not care about
27337 ** the content of the page at this time.  So do not go to the disk
27338 ** to fetch the content.  Just fill in the content with zeros for now.
27339 ** If in the future we call sqlite3PagerWrite() on this page, that
27340 ** means we have started to be concerned about content and the disk
27341 ** read should occur at that point.
27342 */
27343 SQLITE_PRIVATE int sqlite3BtreeGetPage(
27344   BtShared *pBt,       /* The btree */
27345   Pgno pgno,           /* Number of the page to fetch */
27346   MemPage **ppPage,    /* Return the page in this parameter */
27347   int noContent        /* Do not load page content if true */
27348 ){
27349   int rc;
27350   MemPage *pPage;
27351   DbPage *pDbPage;
27352
27353   assert( sqlite3_mutex_held(pBt->mutex) );
27354   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
27355   if( rc ) return rc;
27356   pPage = (MemPage *)sqlite3PagerGetExtra(pDbPage);
27357   pPage->aData = sqlite3PagerGetData(pDbPage);
27358   pPage->pDbPage = pDbPage;
27359   pPage->pBt = pBt;
27360   pPage->pgno = pgno;
27361   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
27362   *ppPage = pPage;
27363   return SQLITE_OK;
27364 }
27365
27366 /*
27367 ** Get a page from the pager and initialize it.  This routine
27368 ** is just a convenience wrapper around separate calls to
27369 ** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
27370 */
27371 static int getAndInitPage(
27372   BtShared *pBt,          /* The database file */
27373   Pgno pgno,           /* Number of the page to get */
27374   MemPage **ppPage,    /* Write the page pointer here */
27375   MemPage *pParent     /* Parent of the page */
27376 ){
27377   int rc;
27378   assert( sqlite3_mutex_held(pBt->mutex) );
27379   if( pgno==0 ){
27380     return SQLITE_CORRUPT_BKPT; 
27381   }
27382   rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
27383   if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
27384     rc = sqlite3BtreeInitPage(*ppPage, pParent);
27385   }
27386   return rc;
27387 }
27388
27389 /*
27390 ** Release a MemPage.  This should be called once for each prior
27391 ** call to sqlite3BtreeGetPage.
27392 */
27393 static void releasePage(MemPage *pPage){
27394   if( pPage ){
27395     assert( pPage->aData );
27396     assert( pPage->pBt );
27397     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
27398     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
27399     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
27400     sqlite3PagerUnref(pPage->pDbPage);
27401   }
27402 }
27403
27404 /*
27405 ** This routine is called when the reference count for a page
27406 ** reaches zero.  We need to unref the pParent pointer when that
27407 ** happens.
27408 */
27409 static void pageDestructor(DbPage *pData, int pageSize){
27410   MemPage *pPage;
27411   assert( (pageSize & 7)==0 );
27412   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
27413   assert( pPage->isInit==0 || sqlite3_mutex_held(pPage->pBt->mutex) );
27414   if( pPage->pParent ){
27415     MemPage *pParent = pPage->pParent;
27416     assert( pParent->pBt==pPage->pBt );
27417     pPage->pParent = 0;
27418     releasePage(pParent);
27419   }
27420   pPage->isInit = 0;
27421 }
27422
27423 /*
27424 ** During a rollback, when the pager reloads information into the cache
27425 ** so that the cache is restored to its original state at the start of
27426 ** the transaction, for each page restored this routine is called.
27427 **
27428 ** This routine needs to reset the extra data section at the end of the
27429 ** page to agree with the restored data.
27430 */
27431 static void pageReinit(DbPage *pData, int pageSize){
27432   MemPage *pPage;
27433   assert( (pageSize & 7)==0 );
27434   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
27435   if( pPage->isInit ){
27436     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
27437     pPage->isInit = 0;
27438     sqlite3BtreeInitPage(pPage, pPage->pParent);
27439   }
27440 }
27441
27442 /*
27443 ** Invoke the busy handler for a btree.
27444 */
27445 static int sqlite3BtreeInvokeBusyHandler(void *pArg, int n){
27446   BtShared *pBt = (BtShared*)pArg;
27447   assert( pBt->db );
27448   assert( sqlite3_mutex_held(pBt->db->mutex) );
27449   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
27450 }
27451
27452 /*
27453 ** Open a database file.
27454 ** 
27455 ** zFilename is the name of the database file.  If zFilename is NULL
27456 ** a new database with a random name is created.  This randomly named
27457 ** database file will be deleted when sqlite3BtreeClose() is called.
27458 ** If zFilename is ":memory:" then an in-memory database is created
27459 ** that is automatically destroyed when it is closed.
27460 */
27461 SQLITE_PRIVATE int sqlite3BtreeOpen(
27462   const char *zFilename,  /* Name of the file containing the BTree database */
27463   sqlite3 *db,            /* Associated database handle */
27464   Btree **ppBtree,        /* Pointer to new Btree object written here */
27465   int flags,              /* Options */
27466   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
27467 ){
27468   sqlite3_vfs *pVfs;      /* The VFS to use for this btree */
27469   BtShared *pBt = 0;      /* Shared part of btree structure */
27470   Btree *p;               /* Handle to return */
27471   int rc = SQLITE_OK;
27472   int nReserve;
27473   unsigned char zDbHeader[100];
27474
27475   /* Set the variable isMemdb to true for an in-memory database, or 
27476   ** false for a file-based database. This symbol is only required if
27477   ** either of the shared-data or autovacuum features are compiled 
27478   ** into the library.
27479   */
27480 #if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
27481   #ifdef SQLITE_OMIT_MEMORYDB
27482     const int isMemdb = 0;
27483   #else
27484     const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
27485   #endif
27486 #endif
27487
27488   assert( db!=0 );
27489   assert( sqlite3_mutex_held(db->mutex) );
27490
27491   pVfs = db->pVfs;
27492   p = sqlite3MallocZero(sizeof(Btree));
27493   if( !p ){
27494     return SQLITE_NOMEM;
27495   }
27496   p->inTrans = TRANS_NONE;
27497   p->db = db;
27498
27499 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
27500   /*
27501   ** If this Btree is a candidate for shared cache, try to find an
27502   ** existing BtShared object that we can share with
27503   */
27504   if( (flags & BTREE_PRIVATE)==0
27505    && isMemdb==0
27506    && (db->flags & SQLITE_Vtab)==0
27507    && zFilename && zFilename[0]
27508   ){
27509     if( sqlite3SharedCacheEnabled ){
27510       int nFullPathname = pVfs->mxPathname+1;
27511       char *zFullPathname = (char *)sqlite3_malloc(nFullPathname);
27512       sqlite3_mutex *mutexShared;
27513       p->sharable = 1;
27514       if( db ){
27515         db->flags |= SQLITE_SharedCache;
27516       }
27517       if( !zFullPathname ){
27518         sqlite3_free(p);
27519         return SQLITE_NOMEM;
27520       }
27521       sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
27522       mutexShared = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
27523       sqlite3_mutex_enter(mutexShared);
27524       for(pBt=sqlite3SharedCacheList; pBt; pBt=pBt->pNext){
27525         assert( pBt->nRef>0 );
27526         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
27527                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
27528           p->pBt = pBt;
27529           pBt->nRef++;
27530           break;
27531         }
27532       }
27533       sqlite3_mutex_leave(mutexShared);
27534       sqlite3_free(zFullPathname);
27535     }
27536 #ifdef SQLITE_DEBUG
27537     else{
27538       /* In debug mode, we mark all persistent databases as sharable
27539       ** even when they are not.  This exercises the locking code and
27540       ** gives more opportunity for asserts(sqlite3_mutex_held())
27541       ** statements to find locking problems.
27542       */
27543       p->sharable = 1;
27544     }
27545 #endif
27546   }
27547 #endif
27548   if( pBt==0 ){
27549     /*
27550     ** The following asserts make sure that structures used by the btree are
27551     ** the right size.  This is to guard against size changes that result
27552     ** when compiling on a different architecture.
27553     */
27554     assert( sizeof(i64)==8 || sizeof(i64)==4 );
27555     assert( sizeof(u64)==8 || sizeof(u64)==4 );
27556     assert( sizeof(u32)==4 );
27557     assert( sizeof(u16)==2 );
27558     assert( sizeof(Pgno)==4 );
27559   
27560     pBt = sqlite3MallocZero( sizeof(*pBt) );
27561     if( pBt==0 ){
27562       rc = SQLITE_NOMEM;
27563       goto btree_open_out;
27564     }
27565     pBt->busyHdr.xFunc = sqlite3BtreeInvokeBusyHandler;
27566     pBt->busyHdr.pArg = pBt;
27567     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
27568                           EXTRA_SIZE, flags, vfsFlags);
27569     if( rc==SQLITE_OK ){
27570       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
27571     }
27572     if( rc!=SQLITE_OK ){
27573       goto btree_open_out;
27574     }
27575     sqlite3PagerSetBusyhandler(pBt->pPager, &pBt->busyHdr);
27576     p->pBt = pBt;
27577   
27578     sqlite3PagerSetDestructor(pBt->pPager, pageDestructor);
27579     sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
27580     pBt->pCursor = 0;
27581     pBt->pPage1 = 0;
27582     pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
27583     pBt->pageSize = get2byte(&zDbHeader[16]);
27584     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
27585          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
27586       pBt->pageSize = 0;
27587       sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
27588       pBt->maxEmbedFrac = 64;   /* 25% */
27589       pBt->minEmbedFrac = 32;   /* 12.5% */
27590       pBt->minLeafFrac = 32;    /* 12.5% */
27591 #ifndef SQLITE_OMIT_AUTOVACUUM
27592       /* If the magic name ":memory:" will create an in-memory database, then
27593       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
27594       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
27595       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
27596       ** regular file-name. In this case the auto-vacuum applies as per normal.
27597       */
27598       if( zFilename && !isMemdb ){
27599         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
27600         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
27601       }
27602 #endif
27603       nReserve = 0;
27604     }else{
27605       nReserve = zDbHeader[20];
27606       pBt->maxEmbedFrac = zDbHeader[21];
27607       pBt->minEmbedFrac = zDbHeader[22];
27608       pBt->minLeafFrac = zDbHeader[23];
27609       pBt->pageSizeFixed = 1;
27610 #ifndef SQLITE_OMIT_AUTOVACUUM
27611       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
27612       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
27613 #endif
27614     }
27615     pBt->usableSize = pBt->pageSize - nReserve;
27616     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
27617     sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
27618    
27619 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
27620     /* Add the new BtShared object to the linked list sharable BtShareds.
27621     */
27622     if( p->sharable ){
27623       sqlite3_mutex *mutexShared;
27624       pBt->nRef = 1;
27625       mutexShared = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
27626       if( SQLITE_THREADSAFE ){
27627         pBt->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
27628         if( pBt->mutex==0 ){
27629           rc = SQLITE_NOMEM;
27630           db->mallocFailed = 0;
27631           goto btree_open_out;
27632         }
27633       }
27634       sqlite3_mutex_enter(mutexShared);
27635       pBt->pNext = sqlite3SharedCacheList;
27636       sqlite3SharedCacheList = pBt;
27637       sqlite3_mutex_leave(mutexShared);
27638     }
27639 #endif
27640   }
27641
27642 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
27643   /* If the new Btree uses a sharable pBtShared, then link the new
27644   ** Btree into the list of all sharable Btrees for the same connection.
27645   ** The list is kept in ascending order by pBt address.
27646   */
27647   if( p->sharable ){
27648     int i;
27649     Btree *pSib;
27650     for(i=0; i<db->nDb; i++){
27651       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
27652         while( pSib->pPrev ){ pSib = pSib->pPrev; }
27653         if( p->pBt<pSib->pBt ){
27654           p->pNext = pSib;
27655           p->pPrev = 0;
27656           pSib->pPrev = p;
27657         }else{
27658           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
27659             pSib = pSib->pNext;
27660           }
27661           p->pNext = pSib->pNext;
27662           p->pPrev = pSib;
27663           if( p->pNext ){
27664             p->pNext->pPrev = p;
27665           }
27666           pSib->pNext = p;
27667         }
27668         break;
27669       }
27670     }
27671   }
27672 #endif
27673   *ppBtree = p;
27674
27675 btree_open_out:
27676   if( rc!=SQLITE_OK ){
27677     if( pBt && pBt->pPager ){
27678       sqlite3PagerClose(pBt->pPager);
27679     }
27680     sqlite3_free(pBt);
27681     sqlite3_free(p);
27682     *ppBtree = 0;
27683   }
27684   return rc;
27685 }
27686
27687 /*
27688 ** Decrement the BtShared.nRef counter.  When it reaches zero,
27689 ** remove the BtShared structure from the sharing list.  Return
27690 ** true if the BtShared.nRef counter reaches zero and return
27691 ** false if it is still positive.
27692 */
27693 static int removeFromSharingList(BtShared *pBt){
27694 #ifndef SQLITE_OMIT_SHARED_CACHE
27695   sqlite3_mutex *pMaster;
27696   BtShared *pList;
27697   int removed = 0;
27698
27699   assert( sqlite3_mutex_notheld(pBt->mutex) );
27700   pMaster = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
27701   sqlite3_mutex_enter(pMaster);
27702   pBt->nRef--;
27703   if( pBt->nRef<=0 ){
27704     if( sqlite3SharedCacheList==pBt ){
27705       sqlite3SharedCacheList = pBt->pNext;
27706     }else{
27707       pList = sqlite3SharedCacheList;
27708       while( pList && pList->pNext!=pBt ){
27709         pList=pList->pNext;
27710       }
27711       if( pList ){
27712         pList->pNext = pBt->pNext;
27713       }
27714     }
27715     if( SQLITE_THREADSAFE ){
27716       sqlite3_mutex_free(pBt->mutex);
27717     }
27718     removed = 1;
27719   }
27720   sqlite3_mutex_leave(pMaster);
27721   return removed;
27722 #else
27723   return 1;
27724 #endif
27725 }
27726
27727 /*
27728 ** Close an open database and invalidate all cursors.
27729 */
27730 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
27731   BtShared *pBt = p->pBt;
27732   BtCursor *pCur;
27733
27734   /* Close all cursors opened via this handle.  */
27735   assert( sqlite3_mutex_held(p->db->mutex) );
27736   sqlite3BtreeEnter(p);
27737   pBt->db = p->db;
27738   pCur = pBt->pCursor;
27739   while( pCur ){
27740     BtCursor *pTmp = pCur;
27741     pCur = pCur->pNext;
27742     if( pTmp->pBtree==p ){
27743       sqlite3BtreeCloseCursor(pTmp);
27744     }
27745   }
27746
27747   /* Rollback any active transaction and free the handle structure.
27748   ** The call to sqlite3BtreeRollback() drops any table-locks held by
27749   ** this handle.
27750   */
27751   sqlite3BtreeRollback(p);
27752   sqlite3BtreeLeave(p);
27753
27754   /* If there are still other outstanding references to the shared-btree
27755   ** structure, return now. The remainder of this procedure cleans 
27756   ** up the shared-btree.
27757   */
27758   assert( p->wantToLock==0 && p->locked==0 );
27759   if( !p->sharable || removeFromSharingList(pBt) ){
27760     /* The pBt is no longer on the sharing list, so we can access
27761     ** it without having to hold the mutex.
27762     **
27763     ** Clean out and delete the BtShared object.
27764     */
27765     assert( !pBt->pCursor );
27766     sqlite3PagerClose(pBt->pPager);
27767     if( pBt->xFreeSchema && pBt->pSchema ){
27768       pBt->xFreeSchema(pBt->pSchema);
27769     }
27770     sqlite3_free(pBt->pSchema);
27771     sqlite3_free(pBt);
27772   }
27773
27774 #ifndef SQLITE_OMIT_SHARED_CACHE
27775   assert( p->wantToLock==0 );
27776   assert( p->locked==0 );
27777   if( p->pPrev ) p->pPrev->pNext = p->pNext;
27778   if( p->pNext ) p->pNext->pPrev = p->pPrev;
27779 #endif
27780
27781   sqlite3_free(p);
27782   return SQLITE_OK;
27783 }
27784
27785 /*
27786 ** Change the limit on the number of pages allowed in the cache.
27787 **
27788 ** The maximum number of cache pages is set to the absolute
27789 ** value of mxPage.  If mxPage is negative, the pager will
27790 ** operate asynchronously - it will not stop to do fsync()s
27791 ** to insure data is written to the disk surface before
27792 ** continuing.  Transactions still work if synchronous is off,
27793 ** and the database cannot be corrupted if this program
27794 ** crashes.  But if the operating system crashes or there is
27795 ** an abrupt power failure when synchronous is off, the database
27796 ** could be left in an inconsistent and unrecoverable state.
27797 ** Synchronous is on by default so database corruption is not
27798 ** normally a worry.
27799 */
27800 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
27801   BtShared *pBt = p->pBt;
27802   assert( sqlite3_mutex_held(p->db->mutex) );
27803   sqlite3BtreeEnter(p);
27804   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
27805   sqlite3BtreeLeave(p);
27806   return SQLITE_OK;
27807 }
27808
27809 /*
27810 ** Change the way data is synced to disk in order to increase or decrease
27811 ** how well the database resists damage due to OS crashes and power
27812 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
27813 ** there is a high probability of damage)  Level 2 is the default.  There
27814 ** is a very low but non-zero probability of damage.  Level 3 reduces the
27815 ** probability of damage to near zero but with a write performance reduction.
27816 */
27817 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
27818 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
27819   BtShared *pBt = p->pBt;
27820   assert( sqlite3_mutex_held(p->db->mutex) );
27821   sqlite3BtreeEnter(p);
27822   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
27823   sqlite3BtreeLeave(p);
27824   return SQLITE_OK;
27825 }
27826 #endif
27827
27828 /*
27829 ** Return TRUE if the given btree is set to safety level 1.  In other
27830 ** words, return TRUE if no sync() occurs on the disk files.
27831 */
27832 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
27833   BtShared *pBt = p->pBt;
27834   int rc;
27835   assert( sqlite3_mutex_held(p->db->mutex) );  
27836   sqlite3BtreeEnter(p);
27837   assert( pBt && pBt->pPager );
27838   rc = sqlite3PagerNosync(pBt->pPager);
27839   sqlite3BtreeLeave(p);
27840   return rc;
27841 }
27842
27843 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
27844 /*
27845 ** Change the default pages size and the number of reserved bytes per page.
27846 **
27847 ** The page size must be a power of 2 between 512 and 65536.  If the page
27848 ** size supplied does not meet this constraint then the page size is not
27849 ** changed.
27850 **
27851 ** Page sizes are constrained to be a power of two so that the region
27852 ** of the database file used for locking (beginning at PENDING_BYTE,
27853 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
27854 ** at the beginning of a page.
27855 **
27856 ** If parameter nReserve is less than zero, then the number of reserved
27857 ** bytes per page is left unchanged.
27858 */
27859 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
27860   int rc = SQLITE_OK;
27861   BtShared *pBt = p->pBt;
27862   sqlite3BtreeEnter(p);
27863   if( pBt->pageSizeFixed ){
27864     sqlite3BtreeLeave(p);
27865     return SQLITE_READONLY;
27866   }
27867   if( nReserve<0 ){
27868     nReserve = pBt->pageSize - pBt->usableSize;
27869   }
27870   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
27871         ((pageSize-1)&pageSize)==0 ){
27872     assert( (pageSize & 7)==0 );
27873     assert( !pBt->pPage1 && !pBt->pCursor );
27874     pBt->pageSize = pageSize;
27875     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
27876   }
27877   pBt->usableSize = pBt->pageSize - nReserve;
27878   sqlite3BtreeLeave(p);
27879   return rc;
27880 }
27881
27882 /*
27883 ** Return the currently defined page size
27884 */
27885 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
27886   return p->pBt->pageSize;
27887 }
27888 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
27889   int n;
27890   sqlite3BtreeEnter(p);
27891   n = p->pBt->pageSize - p->pBt->usableSize;
27892   sqlite3BtreeLeave(p);
27893   return n;
27894 }
27895
27896 /*
27897 ** Set the maximum page count for a database if mxPage is positive.
27898 ** No changes are made if mxPage is 0 or negative.
27899 ** Regardless of the value of mxPage, return the maximum page count.
27900 */
27901 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
27902   int n;
27903   sqlite3BtreeEnter(p);
27904   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
27905   sqlite3BtreeLeave(p);
27906   return n;
27907 }
27908 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
27909
27910 /*
27911 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
27912 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
27913 ** is disabled. The default value for the auto-vacuum property is 
27914 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
27915 */
27916 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
27917 #ifdef SQLITE_OMIT_AUTOVACUUM
27918   return SQLITE_READONLY;
27919 #else
27920   BtShared *pBt = p->pBt;
27921   int rc = SQLITE_OK;
27922   int av = (autoVacuum?1:0);
27923
27924   sqlite3BtreeEnter(p);
27925   if( pBt->pageSizeFixed && av!=pBt->autoVacuum ){
27926     rc = SQLITE_READONLY;
27927   }else{
27928     pBt->autoVacuum = av;
27929   }
27930   sqlite3BtreeLeave(p);
27931   return rc;
27932 #endif
27933 }
27934
27935 /*
27936 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
27937 ** enabled 1 is returned. Otherwise 0.
27938 */
27939 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
27940 #ifdef SQLITE_OMIT_AUTOVACUUM
27941   return BTREE_AUTOVACUUM_NONE;
27942 #else
27943   int rc;
27944   sqlite3BtreeEnter(p);
27945   rc = (
27946     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
27947     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
27948     BTREE_AUTOVACUUM_INCR
27949   );
27950   sqlite3BtreeLeave(p);
27951   return rc;
27952 #endif
27953 }
27954
27955
27956 /*
27957 ** Get a reference to pPage1 of the database file.  This will
27958 ** also acquire a readlock on that file.
27959 **
27960 ** SQLITE_OK is returned on success.  If the file is not a
27961 ** well-formed database file, then SQLITE_CORRUPT is returned.
27962 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
27963 ** is returned if we run out of memory. 
27964 */
27965 static int lockBtree(BtShared *pBt){
27966   int rc, pageSize;
27967   MemPage *pPage1;
27968
27969   assert( sqlite3_mutex_held(pBt->mutex) );
27970   if( pBt->pPage1 ) return SQLITE_OK;
27971   rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
27972   if( rc!=SQLITE_OK ) return rc;
27973   
27974
27975   /* Do some checking to help insure the file we opened really is
27976   ** a valid database file. 
27977   */
27978   rc = SQLITE_NOTADB;
27979   if( sqlite3PagerPagecount(pBt->pPager)>0 ){
27980     u8 *page1 = pPage1->aData;
27981     if( memcmp(page1, zMagicHeader, 16)!=0 ){
27982       goto page1_init_failed;
27983     }
27984     if( page1[18]>1 ){
27985       pBt->readOnly = 1;
27986     }
27987     if( page1[19]>1 ){
27988       goto page1_init_failed;
27989     }
27990     pageSize = get2byte(&page1[16]);
27991     if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
27992         (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
27993     ){
27994       goto page1_init_failed;
27995     }
27996     assert( (pageSize & 7)==0 );
27997     pBt->pageSize = pageSize;
27998     pBt->usableSize = pageSize - page1[20];
27999     if( pBt->usableSize<500 ){
28000       goto page1_init_failed;
28001     }
28002     pBt->maxEmbedFrac = page1[21];
28003     pBt->minEmbedFrac = page1[22];
28004     pBt->minLeafFrac = page1[23];
28005 #ifndef SQLITE_OMIT_AUTOVACUUM
28006     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
28007     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
28008 #endif
28009   }
28010
28011   /* maxLocal is the maximum amount of payload to store locally for
28012   ** a cell.  Make sure it is small enough so that at least minFanout
28013   ** cells can will fit on one page.  We assume a 10-byte page header.
28014   ** Besides the payload, the cell must store:
28015   **     2-byte pointer to the cell
28016   **     4-byte child pointer
28017   **     9-byte nKey value
28018   **     4-byte nData value
28019   **     4-byte overflow page pointer
28020   ** So a cell consists of a 2-byte poiner, a header which is as much as
28021   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
28022   ** page pointer.
28023   */
28024   pBt->maxLocal = (pBt->usableSize-12)*pBt->maxEmbedFrac/255 - 23;
28025   pBt->minLocal = (pBt->usableSize-12)*pBt->minEmbedFrac/255 - 23;
28026   pBt->maxLeaf = pBt->usableSize - 35;
28027   pBt->minLeaf = (pBt->usableSize-12)*pBt->minLeafFrac/255 - 23;
28028   if( pBt->minLocal>pBt->maxLocal || pBt->maxLocal<0 ){
28029     goto page1_init_failed;
28030   }
28031   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
28032   pBt->pPage1 = pPage1;
28033   return SQLITE_OK;
28034
28035 page1_init_failed:
28036   releasePage(pPage1);
28037   pBt->pPage1 = 0;
28038   return rc;
28039 }
28040
28041 /*
28042 ** This routine works like lockBtree() except that it also invokes the
28043 ** busy callback if there is lock contention.
28044 */
28045 static int lockBtreeWithRetry(Btree *pRef){
28046   int rc = SQLITE_OK;
28047
28048   assert( sqlite3BtreeHoldsMutex(pRef) );
28049   if( pRef->inTrans==TRANS_NONE ){
28050     u8 inTransaction = pRef->pBt->inTransaction;
28051     btreeIntegrity(pRef);
28052     rc = sqlite3BtreeBeginTrans(pRef, 0);
28053     pRef->pBt->inTransaction = inTransaction;
28054     pRef->inTrans = TRANS_NONE;
28055     if( rc==SQLITE_OK ){
28056       pRef->pBt->nTransaction--;
28057     }
28058     btreeIntegrity(pRef);
28059   }
28060   return rc;
28061 }
28062        
28063
28064 /*
28065 ** If there are no outstanding cursors and we are not in the middle
28066 ** of a transaction but there is a read lock on the database, then
28067 ** this routine unrefs the first page of the database file which 
28068 ** has the effect of releasing the read lock.
28069 **
28070 ** If there are any outstanding cursors, this routine is a no-op.
28071 **
28072 ** If there is a transaction in progress, this routine is a no-op.
28073 */
28074 static void unlockBtreeIfUnused(BtShared *pBt){
28075   assert( sqlite3_mutex_held(pBt->mutex) );
28076   if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
28077     if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
28078       if( pBt->pPage1->aData==0 ){
28079         MemPage *pPage = pBt->pPage1;
28080         pPage->aData = sqlite3PagerGetData(pPage->pDbPage);
28081         pPage->pBt = pBt;
28082         pPage->pgno = 1;
28083       }
28084       releasePage(pBt->pPage1);
28085     }
28086     pBt->pPage1 = 0;
28087     pBt->inStmt = 0;
28088   }
28089 }
28090
28091 /*
28092 ** Create a new database by initializing the first page of the
28093 ** file.
28094 */
28095 static int newDatabase(BtShared *pBt){
28096   MemPage *pP1;
28097   unsigned char *data;
28098   int rc;
28099
28100   assert( sqlite3_mutex_held(pBt->mutex) );
28101   if( sqlite3PagerPagecount(pBt->pPager)>0 ) return SQLITE_OK;
28102   pP1 = pBt->pPage1;
28103   assert( pP1!=0 );
28104   data = pP1->aData;
28105   rc = sqlite3PagerWrite(pP1->pDbPage);
28106   if( rc ) return rc;
28107   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
28108   assert( sizeof(zMagicHeader)==16 );
28109   put2byte(&data[16], pBt->pageSize);
28110   data[18] = 1;
28111   data[19] = 1;
28112   data[20] = pBt->pageSize - pBt->usableSize;
28113   data[21] = pBt->maxEmbedFrac;
28114   data[22] = pBt->minEmbedFrac;
28115   data[23] = pBt->minLeafFrac;
28116   memset(&data[24], 0, 100-24);
28117   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
28118   pBt->pageSizeFixed = 1;
28119 #ifndef SQLITE_OMIT_AUTOVACUUM
28120   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
28121   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
28122   put4byte(&data[36 + 4*4], pBt->autoVacuum);
28123   put4byte(&data[36 + 7*4], pBt->incrVacuum);
28124 #endif
28125   return SQLITE_OK;
28126 }
28127
28128 /*
28129 ** Attempt to start a new transaction. A write-transaction
28130 ** is started if the second argument is nonzero, otherwise a read-
28131 ** transaction.  If the second argument is 2 or more and exclusive
28132 ** transaction is started, meaning that no other process is allowed
28133 ** to access the database.  A preexisting transaction may not be
28134 ** upgraded to exclusive by calling this routine a second time - the
28135 ** exclusivity flag only works for a new transaction.
28136 **
28137 ** A write-transaction must be started before attempting any 
28138 ** changes to the database.  None of the following routines 
28139 ** will work unless a transaction is started first:
28140 **
28141 **      sqlite3BtreeCreateTable()
28142 **      sqlite3BtreeCreateIndex()
28143 **      sqlite3BtreeClearTable()
28144 **      sqlite3BtreeDropTable()
28145 **      sqlite3BtreeInsert()
28146 **      sqlite3BtreeDelete()
28147 **      sqlite3BtreeUpdateMeta()
28148 **
28149 ** If an initial attempt to acquire the lock fails because of lock contention
28150 ** and the database was previously unlocked, then invoke the busy handler
28151 ** if there is one.  But if there was previously a read-lock, do not
28152 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
28153 ** returned when there is already a read-lock in order to avoid a deadlock.
28154 **
28155 ** Suppose there are two processes A and B.  A has a read lock and B has
28156 ** a reserved lock.  B tries to promote to exclusive but is blocked because
28157 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
28158 ** One or the other of the two processes must give way or there can be
28159 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
28160 ** when A already has a read lock, we encourage A to give up and let B
28161 ** proceed.
28162 */
28163 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
28164   BtShared *pBt = p->pBt;
28165   int rc = SQLITE_OK;
28166
28167   sqlite3BtreeEnter(p);
28168   pBt->db = p->db;
28169   btreeIntegrity(p);
28170
28171   /* If the btree is already in a write-transaction, or it
28172   ** is already in a read-transaction and a read-transaction
28173   ** is requested, this is a no-op.
28174   */
28175   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
28176     goto trans_begun;
28177   }
28178
28179   /* Write transactions are not possible on a read-only database */
28180   if( pBt->readOnly && wrflag ){
28181     rc = SQLITE_READONLY;
28182     goto trans_begun;
28183   }
28184
28185   /* If another database handle has already opened a write transaction 
28186   ** on this shared-btree structure and a second write transaction is
28187   ** requested, return SQLITE_BUSY.
28188   */
28189   if( pBt->inTransaction==TRANS_WRITE && wrflag ){
28190     rc = SQLITE_BUSY;
28191     goto trans_begun;
28192   }
28193
28194   do {
28195     if( pBt->pPage1==0 ){
28196       rc = lockBtree(pBt);
28197     }
28198
28199     if( rc==SQLITE_OK && wrflag ){
28200       if( pBt->readOnly ){
28201         rc = SQLITE_READONLY;
28202       }else{
28203         rc = sqlite3PagerBegin(pBt->pPage1->pDbPage, wrflag>1);
28204         if( rc==SQLITE_OK ){
28205           rc = newDatabase(pBt);
28206         }
28207       }
28208     }
28209   
28210     if( rc==SQLITE_OK ){
28211       if( wrflag ) pBt->inStmt = 0;
28212     }else{
28213       unlockBtreeIfUnused(pBt);
28214     }
28215   }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
28216           sqlite3BtreeInvokeBusyHandler(pBt, 0) );
28217
28218   if( rc==SQLITE_OK ){
28219     if( p->inTrans==TRANS_NONE ){
28220       pBt->nTransaction++;
28221     }
28222     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
28223     if( p->inTrans>pBt->inTransaction ){
28224       pBt->inTransaction = p->inTrans;
28225     }
28226   }
28227
28228
28229 trans_begun:
28230   btreeIntegrity(p);
28231   sqlite3BtreeLeave(p);
28232   return rc;
28233 }
28234
28235 #ifndef SQLITE_OMIT_AUTOVACUUM
28236
28237 /*
28238 ** Set the pointer-map entries for all children of page pPage. Also, if
28239 ** pPage contains cells that point to overflow pages, set the pointer
28240 ** map entries for the overflow pages as well.
28241 */
28242 static int setChildPtrmaps(MemPage *pPage){
28243   int i;                             /* Counter variable */
28244   int nCell;                         /* Number of cells in page pPage */
28245   int rc;                            /* Return code */
28246   BtShared *pBt = pPage->pBt;
28247   int isInitOrig = pPage->isInit;
28248   Pgno pgno = pPage->pgno;
28249
28250   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
28251   rc = sqlite3BtreeInitPage(pPage, pPage->pParent);
28252   if( rc!=SQLITE_OK ){
28253     goto set_child_ptrmaps_out;
28254   }
28255   nCell = pPage->nCell;
28256
28257   for(i=0; i<nCell; i++){
28258     u8 *pCell = findCell(pPage, i);
28259
28260     rc = ptrmapPutOvflPtr(pPage, pCell);
28261     if( rc!=SQLITE_OK ){
28262       goto set_child_ptrmaps_out;
28263     }
28264
28265     if( !pPage->leaf ){
28266       Pgno childPgno = get4byte(pCell);
28267       rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
28268       if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
28269     }
28270   }
28271
28272   if( !pPage->leaf ){
28273     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
28274     rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
28275   }
28276
28277 set_child_ptrmaps_out:
28278   pPage->isInit = isInitOrig;
28279   return rc;
28280 }
28281
28282 /*
28283 ** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
28284 ** page, is a pointer to page iFrom. Modify this pointer so that it points to
28285 ** iTo. Parameter eType describes the type of pointer to be modified, as 
28286 ** follows:
28287 **
28288 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
28289 **                   page of pPage.
28290 **
28291 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
28292 **                   page pointed to by one of the cells on pPage.
28293 **
28294 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
28295 **                   overflow page in the list.
28296 */
28297 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
28298   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
28299   if( eType==PTRMAP_OVERFLOW2 ){
28300     /* The pointer is always the first 4 bytes of the page in this case.  */
28301     if( get4byte(pPage->aData)!=iFrom ){
28302       return SQLITE_CORRUPT_BKPT;
28303     }
28304     put4byte(pPage->aData, iTo);
28305   }else{
28306     int isInitOrig = pPage->isInit;
28307     int i;
28308     int nCell;
28309
28310     sqlite3BtreeInitPage(pPage, 0);
28311     nCell = pPage->nCell;
28312
28313     for(i=0; i<nCell; i++){
28314       u8 *pCell = findCell(pPage, i);
28315       if( eType==PTRMAP_OVERFLOW1 ){
28316         CellInfo info;
28317         sqlite3BtreeParseCellPtr(pPage, pCell, &info);
28318         if( info.iOverflow ){
28319           if( iFrom==get4byte(&pCell[info.iOverflow]) ){
28320             put4byte(&pCell[info.iOverflow], iTo);
28321             break;
28322           }
28323         }
28324       }else{
28325         if( get4byte(pCell)==iFrom ){
28326           put4byte(pCell, iTo);
28327           break;
28328         }
28329       }
28330     }
28331   
28332     if( i==nCell ){
28333       if( eType!=PTRMAP_BTREE || 
28334           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
28335         return SQLITE_CORRUPT_BKPT;
28336       }
28337       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
28338     }
28339
28340     pPage->isInit = isInitOrig;
28341   }
28342   return SQLITE_OK;
28343 }
28344
28345
28346 /*
28347 ** Move the open database page pDbPage to location iFreePage in the 
28348 ** database. The pDbPage reference remains valid.
28349 */
28350 static int relocatePage(
28351   BtShared *pBt,           /* Btree */
28352   MemPage *pDbPage,        /* Open page to move */
28353   u8 eType,                /* Pointer map 'type' entry for pDbPage */
28354   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
28355   Pgno iFreePage           /* The location to move pDbPage to */
28356 ){
28357   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
28358   Pgno iDbPage = pDbPage->pgno;
28359   Pager *pPager = pBt->pPager;
28360   int rc;
28361
28362   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
28363       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
28364   assert( sqlite3_mutex_held(pBt->mutex) );
28365   assert( pDbPage->pBt==pBt );
28366
28367   /* Move page iDbPage from its current location to page number iFreePage */
28368   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
28369       iDbPage, iFreePage, iPtrPage, eType));
28370   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage);
28371   if( rc!=SQLITE_OK ){
28372     return rc;
28373   }
28374   pDbPage->pgno = iFreePage;
28375
28376   /* If pDbPage was a btree-page, then it may have child pages and/or cells
28377   ** that point to overflow pages. The pointer map entries for all these
28378   ** pages need to be changed.
28379   **
28380   ** If pDbPage is an overflow page, then the first 4 bytes may store a
28381   ** pointer to a subsequent overflow page. If this is the case, then
28382   ** the pointer map needs to be updated for the subsequent overflow page.
28383   */
28384   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
28385     rc = setChildPtrmaps(pDbPage);
28386     if( rc!=SQLITE_OK ){
28387       return rc;
28388     }
28389   }else{
28390     Pgno nextOvfl = get4byte(pDbPage->aData);
28391     if( nextOvfl!=0 ){
28392       rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
28393       if( rc!=SQLITE_OK ){
28394         return rc;
28395       }
28396     }
28397   }
28398
28399   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
28400   ** that it points at iFreePage. Also fix the pointer map entry for
28401   ** iPtrPage.
28402   */
28403   if( eType!=PTRMAP_ROOTPAGE ){
28404     rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
28405     if( rc!=SQLITE_OK ){
28406       return rc;
28407     }
28408     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
28409     if( rc!=SQLITE_OK ){
28410       releasePage(pPtrPage);
28411       return rc;
28412     }
28413     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
28414     releasePage(pPtrPage);
28415     if( rc==SQLITE_OK ){
28416       rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
28417     }
28418   }
28419   return rc;
28420 }
28421
28422 /* Forward declaration required by incrVacuumStep(). */
28423 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
28424
28425 /*
28426 ** Perform a single step of an incremental-vacuum. If successful,
28427 ** return SQLITE_OK. If there is no work to do (and therefore no
28428 ** point in calling this function again), return SQLITE_DONE.
28429 **
28430 ** More specificly, this function attempts to re-organize the 
28431 ** database so that the last page of the file currently in use
28432 ** is no longer in use.
28433 **
28434 ** If the nFin parameter is non-zero, the implementation assumes
28435 ** that the caller will keep calling incrVacuumStep() until
28436 ** it returns SQLITE_DONE or an error, and that nFin is the
28437 ** number of pages the database file will contain after this 
28438 ** process is complete.
28439 */
28440 static int incrVacuumStep(BtShared *pBt, Pgno nFin){
28441   Pgno iLastPg;             /* Last page in the database */
28442   Pgno nFreeList;           /* Number of pages still on the free-list */
28443
28444   assert( sqlite3_mutex_held(pBt->mutex) );
28445   iLastPg = pBt->nTrunc;
28446   if( iLastPg==0 ){
28447     iLastPg = sqlite3PagerPagecount(pBt->pPager);
28448   }
28449
28450   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
28451     int rc;
28452     u8 eType;
28453     Pgno iPtrPage;
28454
28455     nFreeList = get4byte(&pBt->pPage1->aData[36]);
28456     if( nFreeList==0 || nFin==iLastPg ){
28457       return SQLITE_DONE;
28458     }
28459
28460     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
28461     if( rc!=SQLITE_OK ){
28462       return rc;
28463     }
28464     if( eType==PTRMAP_ROOTPAGE ){
28465       return SQLITE_CORRUPT_BKPT;
28466     }
28467
28468     if( eType==PTRMAP_FREEPAGE ){
28469       if( nFin==0 ){
28470         /* Remove the page from the files free-list. This is not required
28471         ** if nFin is non-zero. In that case, the free-list will be
28472         ** truncated to zero after this function returns, so it doesn't 
28473         ** matter if it still contains some garbage entries.
28474         */
28475         Pgno iFreePg;
28476         MemPage *pFreePg;
28477         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
28478         if( rc!=SQLITE_OK ){
28479           return rc;
28480         }
28481         assert( iFreePg==iLastPg );
28482         releasePage(pFreePg);
28483       }
28484     } else {
28485       Pgno iFreePg;             /* Index of free page to move pLastPg to */
28486       MemPage *pLastPg;
28487
28488       rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
28489       if( rc!=SQLITE_OK ){
28490         return rc;
28491       }
28492
28493       /* If nFin is zero, this loop runs exactly once and page pLastPg
28494       ** is swapped with the first free page pulled off the free list.
28495       **
28496       ** On the other hand, if nFin is greater than zero, then keep
28497       ** looping until a free-page located within the first nFin pages
28498       ** of the file is found.
28499       */
28500       do {
28501         MemPage *pFreePg;
28502         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
28503         if( rc!=SQLITE_OK ){
28504           releasePage(pLastPg);
28505           return rc;
28506         }
28507         releasePage(pFreePg);
28508       }while( nFin!=0 && iFreePg>nFin );
28509       assert( iFreePg<iLastPg );
28510       
28511       rc = sqlite3PagerWrite(pLastPg->pDbPage);
28512       if( rc==SQLITE_OK ){
28513         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg);
28514       }
28515       releasePage(pLastPg);
28516       if( rc!=SQLITE_OK ){
28517         return rc;
28518       }
28519     }
28520   }
28521
28522   pBt->nTrunc = iLastPg - 1;
28523   while( pBt->nTrunc==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, pBt->nTrunc) ){
28524     pBt->nTrunc--;
28525   }
28526   return SQLITE_OK;
28527 }
28528
28529 /*
28530 ** A write-transaction must be opened before calling this function.
28531 ** It performs a single unit of work towards an incremental vacuum.
28532 **
28533 ** If the incremental vacuum is finished after this function has run,
28534 ** SQLITE_DONE is returned. If it is not finished, but no error occured,
28535 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
28536 */
28537 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
28538   int rc;
28539   BtShared *pBt = p->pBt;
28540
28541   sqlite3BtreeEnter(p);
28542   pBt->db = p->db;
28543   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
28544   if( !pBt->autoVacuum ){
28545     rc = SQLITE_DONE;
28546   }else{
28547     invalidateAllOverflowCache(pBt);
28548     rc = incrVacuumStep(pBt, 0);
28549   }
28550   sqlite3BtreeLeave(p);
28551   return rc;
28552 }
28553
28554 /*
28555 ** This routine is called prior to sqlite3PagerCommit when a transaction
28556 ** is commited for an auto-vacuum database.
28557 **
28558 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
28559 ** the database file should be truncated to during the commit process. 
28560 ** i.e. the database has been reorganized so that only the first *pnTrunc
28561 ** pages are in use.
28562 */
28563 static int autoVacuumCommit(BtShared *pBt, Pgno *pnTrunc){
28564   int rc = SQLITE_OK;
28565   Pager *pPager = pBt->pPager;
28566 #ifndef NDEBUG
28567   int nRef = sqlite3PagerRefcount(pPager);
28568 #endif
28569
28570   assert( sqlite3_mutex_held(pBt->mutex) );
28571   invalidateAllOverflowCache(pBt);
28572   assert(pBt->autoVacuum);
28573   if( !pBt->incrVacuum ){
28574     Pgno nFin = 0;
28575
28576     if( pBt->nTrunc==0 ){
28577       Pgno nFree;
28578       Pgno nPtrmap;
28579       const int pgsz = pBt->pageSize;
28580       Pgno nOrig = sqlite3PagerPagecount(pBt->pPager);
28581
28582       if( PTRMAP_ISPAGE(pBt, nOrig) ){
28583         return SQLITE_CORRUPT_BKPT;
28584       }
28585       if( nOrig==PENDING_BYTE_PAGE(pBt) ){
28586         nOrig--;
28587       }
28588       nFree = get4byte(&pBt->pPage1->aData[36]);
28589       nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
28590       nFin = nOrig - nFree - nPtrmap;
28591       if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
28592         nFin--;
28593       }
28594       while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
28595         nFin--;
28596       }
28597     }
28598
28599     while( rc==SQLITE_OK ){
28600       rc = incrVacuumStep(pBt, nFin);
28601     }
28602     if( rc==SQLITE_DONE ){
28603       assert(nFin==0 || pBt->nTrunc==0 || nFin<=pBt->nTrunc);
28604       rc = SQLITE_OK;
28605       if( pBt->nTrunc ){
28606         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
28607         put4byte(&pBt->pPage1->aData[32], 0);
28608         put4byte(&pBt->pPage1->aData[36], 0);
28609         pBt->nTrunc = nFin;
28610       }
28611     }
28612     if( rc!=SQLITE_OK ){
28613       sqlite3PagerRollback(pPager);
28614     }
28615   }
28616
28617   if( rc==SQLITE_OK ){
28618     *pnTrunc = pBt->nTrunc;
28619     pBt->nTrunc = 0;
28620   }
28621   assert( nRef==sqlite3PagerRefcount(pPager) );
28622   return rc;
28623 }
28624
28625 #endif
28626
28627 /*
28628 ** This routine does the first phase of a two-phase commit.  This routine
28629 ** causes a rollback journal to be created (if it does not already exist)
28630 ** and populated with enough information so that if a power loss occurs
28631 ** the database can be restored to its original state by playing back
28632 ** the journal.  Then the contents of the journal are flushed out to
28633 ** the disk.  After the journal is safely on oxide, the changes to the
28634 ** database are written into the database file and flushed to oxide.
28635 ** At the end of this call, the rollback journal still exists on the
28636 ** disk and we are still holding all locks, so the transaction has not
28637 ** committed.  See sqlite3BtreeCommit() for the second phase of the
28638 ** commit process.
28639 **
28640 ** This call is a no-op if no write-transaction is currently active on pBt.
28641 **
28642 ** Otherwise, sync the database file for the btree pBt. zMaster points to
28643 ** the name of a master journal file that should be written into the
28644 ** individual journal file, or is NULL, indicating no master journal file 
28645 ** (single database transaction).
28646 **
28647 ** When this is called, the master journal should already have been
28648 ** created, populated with this journal pointer and synced to disk.
28649 **
28650 ** Once this is routine has returned, the only thing required to commit
28651 ** the write-transaction for this database file is to delete the journal.
28652 */
28653 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
28654   int rc = SQLITE_OK;
28655   if( p->inTrans==TRANS_WRITE ){
28656     BtShared *pBt = p->pBt;
28657     Pgno nTrunc = 0;
28658     sqlite3BtreeEnter(p);
28659     pBt->db = p->db;
28660 #ifndef SQLITE_OMIT_AUTOVACUUM
28661     if( pBt->autoVacuum ){
28662       rc = autoVacuumCommit(pBt, &nTrunc); 
28663       if( rc!=SQLITE_OK ){
28664         sqlite3BtreeLeave(p);
28665         return rc;
28666       }
28667     }
28668 #endif
28669     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, nTrunc);
28670     sqlite3BtreeLeave(p);
28671   }
28672   return rc;
28673 }
28674
28675 /*
28676 ** Commit the transaction currently in progress.
28677 **
28678 ** This routine implements the second phase of a 2-phase commit.  The
28679 ** sqlite3BtreeSync() routine does the first phase and should be invoked
28680 ** prior to calling this routine.  The sqlite3BtreeSync() routine did
28681 ** all the work of writing information out to disk and flushing the
28682 ** contents so that they are written onto the disk platter.  All this
28683 ** routine has to do is delete or truncate the rollback journal
28684 ** (which causes the transaction to commit) and drop locks.
28685 **
28686 ** This will release the write lock on the database file.  If there
28687 ** are no active cursors, it also releases the read lock.
28688 */
28689 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
28690   BtShared *pBt = p->pBt;
28691
28692   sqlite3BtreeEnter(p);
28693   pBt->db = p->db;
28694   btreeIntegrity(p);
28695
28696   /* If the handle has a write-transaction open, commit the shared-btrees 
28697   ** transaction and set the shared state to TRANS_READ.
28698   */
28699   if( p->inTrans==TRANS_WRITE ){
28700     int rc;
28701     assert( pBt->inTransaction==TRANS_WRITE );
28702     assert( pBt->nTransaction>0 );
28703     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
28704     if( rc!=SQLITE_OK ){
28705       sqlite3BtreeLeave(p);
28706       return rc;
28707     }
28708     pBt->inTransaction = TRANS_READ;
28709     pBt->inStmt = 0;
28710   }
28711   unlockAllTables(p);
28712
28713   /* If the handle has any kind of transaction open, decrement the transaction
28714   ** count of the shared btree. If the transaction count reaches 0, set
28715   ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
28716   ** will unlock the pager.
28717   */
28718   if( p->inTrans!=TRANS_NONE ){
28719     pBt->nTransaction--;
28720     if( 0==pBt->nTransaction ){
28721       pBt->inTransaction = TRANS_NONE;
28722     }
28723   }
28724
28725   /* Set the handles current transaction state to TRANS_NONE and unlock
28726   ** the pager if this call closed the only read or write transaction.
28727   */
28728   p->inTrans = TRANS_NONE;
28729   unlockBtreeIfUnused(pBt);
28730
28731   btreeIntegrity(p);
28732   sqlite3BtreeLeave(p);
28733   return SQLITE_OK;
28734 }
28735
28736 /*
28737 ** Do both phases of a commit.
28738 */
28739 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
28740   int rc;
28741   sqlite3BtreeEnter(p);
28742   rc = sqlite3BtreeCommitPhaseOne(p, 0);
28743   if( rc==SQLITE_OK ){
28744     rc = sqlite3BtreeCommitPhaseTwo(p);
28745   }
28746   sqlite3BtreeLeave(p);
28747   return rc;
28748 }
28749
28750 #ifndef NDEBUG
28751 /*
28752 ** Return the number of write-cursors open on this handle. This is for use
28753 ** in assert() expressions, so it is only compiled if NDEBUG is not
28754 ** defined.
28755 **
28756 ** For the purposes of this routine, a write-cursor is any cursor that
28757 ** is capable of writing to the databse.  That means the cursor was
28758 ** originally opened for writing and the cursor has not be disabled
28759 ** by having its state changed to CURSOR_FAULT.
28760 */
28761 static int countWriteCursors(BtShared *pBt){
28762   BtCursor *pCur;
28763   int r = 0;
28764   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
28765     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
28766   }
28767   return r;
28768 }
28769 #endif
28770
28771 /*
28772 ** This routine sets the state to CURSOR_FAULT and the error
28773 ** code to errCode for every cursor on BtShared that pBtree
28774 ** references.
28775 **
28776 ** Every cursor is tripped, including cursors that belong
28777 ** to other database connections that happen to be sharing
28778 ** the cache with pBtree.
28779 **
28780 ** This routine gets called when a rollback occurs.
28781 ** All cursors using the same cache must be tripped
28782 ** to prevent them from trying to use the btree after
28783 ** the rollback.  The rollback may have deleted tables
28784 ** or moved root pages, so it is not sufficient to
28785 ** save the state of the cursor.  The cursor must be
28786 ** invalidated.
28787 */
28788 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
28789   BtCursor *p;
28790   sqlite3BtreeEnter(pBtree);
28791   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
28792     clearCursorPosition(p);
28793     p->eState = CURSOR_FAULT;
28794     p->skip = errCode;
28795   }
28796   sqlite3BtreeLeave(pBtree);
28797 }
28798
28799 /*
28800 ** Rollback the transaction in progress.  All cursors will be
28801 ** invalided by this operation.  Any attempt to use a cursor
28802 ** that was open at the beginning of this operation will result
28803 ** in an error.
28804 **
28805 ** This will release the write lock on the database file.  If there
28806 ** are no active cursors, it also releases the read lock.
28807 */
28808 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
28809   int rc;
28810   BtShared *pBt = p->pBt;
28811   MemPage *pPage1;
28812
28813   sqlite3BtreeEnter(p);
28814   pBt->db = p->db;
28815   rc = saveAllCursors(pBt, 0, 0);
28816 #ifndef SQLITE_OMIT_SHARED_CACHE
28817   if( rc!=SQLITE_OK ){
28818     /* This is a horrible situation. An IO or malloc() error occured whilst
28819     ** trying to save cursor positions. If this is an automatic rollback (as
28820     ** the result of a constraint, malloc() failure or IO error) then 
28821     ** the cache may be internally inconsistent (not contain valid trees) so
28822     ** we cannot simply return the error to the caller. Instead, abort 
28823     ** all queries that may be using any of the cursors that failed to save.
28824     */
28825     sqlite3BtreeTripAllCursors(p, rc);
28826   }
28827 #endif
28828   btreeIntegrity(p);
28829   unlockAllTables(p);
28830
28831   if( p->inTrans==TRANS_WRITE ){
28832     int rc2;
28833
28834 #ifndef SQLITE_OMIT_AUTOVACUUM
28835     pBt->nTrunc = 0;
28836 #endif
28837
28838     assert( TRANS_WRITE==pBt->inTransaction );
28839     rc2 = sqlite3PagerRollback(pBt->pPager);
28840     if( rc2!=SQLITE_OK ){
28841       rc = rc2;
28842     }
28843
28844     /* The rollback may have destroyed the pPage1->aData value.  So
28845     ** call sqlite3BtreeGetPage() on page 1 again to make
28846     ** sure pPage1->aData is set correctly. */
28847     if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
28848       releasePage(pPage1);
28849     }
28850     assert( countWriteCursors(pBt)==0 );
28851     pBt->inTransaction = TRANS_READ;
28852   }
28853
28854   if( p->inTrans!=TRANS_NONE ){
28855     assert( pBt->nTransaction>0 );
28856     pBt->nTransaction--;
28857     if( 0==pBt->nTransaction ){
28858       pBt->inTransaction = TRANS_NONE;
28859     }
28860   }
28861
28862   p->inTrans = TRANS_NONE;
28863   pBt->inStmt = 0;
28864   unlockBtreeIfUnused(pBt);
28865
28866   btreeIntegrity(p);
28867   sqlite3BtreeLeave(p);
28868   return rc;
28869 }
28870
28871 /*
28872 ** Start a statement subtransaction.  The subtransaction can
28873 ** can be rolled back independently of the main transaction.
28874 ** You must start a transaction before starting a subtransaction.
28875 ** The subtransaction is ended automatically if the main transaction
28876 ** commits or rolls back.
28877 **
28878 ** Only one subtransaction may be active at a time.  It is an error to try
28879 ** to start a new subtransaction if another subtransaction is already active.
28880 **
28881 ** Statement subtransactions are used around individual SQL statements
28882 ** that are contained within a BEGIN...COMMIT block.  If a constraint
28883 ** error occurs within the statement, the effect of that one statement
28884 ** can be rolled back without having to rollback the entire transaction.
28885 */
28886 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p){
28887   int rc;
28888   BtShared *pBt = p->pBt;
28889   sqlite3BtreeEnter(p);
28890   pBt->db = p->db;
28891   if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
28892     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
28893   }else{
28894     assert( pBt->inTransaction==TRANS_WRITE );
28895     rc = pBt->readOnly ? SQLITE_OK : sqlite3PagerStmtBegin(pBt->pPager);
28896     pBt->inStmt = 1;
28897   }
28898   sqlite3BtreeLeave(p);
28899   return rc;
28900 }
28901
28902
28903 /*
28904 ** Commit the statment subtransaction currently in progress.  If no
28905 ** subtransaction is active, this is a no-op.
28906 */
28907 SQLITE_PRIVATE int sqlite3BtreeCommitStmt(Btree *p){
28908   int rc;
28909   BtShared *pBt = p->pBt;
28910   sqlite3BtreeEnter(p);
28911   pBt->db = p->db;
28912   if( pBt->inStmt && !pBt->readOnly ){
28913     rc = sqlite3PagerStmtCommit(pBt->pPager);
28914   }else{
28915     rc = SQLITE_OK;
28916   }
28917   pBt->inStmt = 0;
28918   sqlite3BtreeLeave(p);
28919   return rc;
28920 }
28921
28922 /*
28923 ** Rollback the active statement subtransaction.  If no subtransaction
28924 ** is active this routine is a no-op.
28925 **
28926 ** All cursors will be invalidated by this operation.  Any attempt
28927 ** to use a cursor that was open at the beginning of this operation
28928 ** will result in an error.
28929 */
28930 SQLITE_PRIVATE int sqlite3BtreeRollbackStmt(Btree *p){
28931   int rc = SQLITE_OK;
28932   BtShared *pBt = p->pBt;
28933   sqlite3BtreeEnter(p);
28934   pBt->db = p->db;
28935   if( pBt->inStmt && !pBt->readOnly ){
28936     rc = sqlite3PagerStmtRollback(pBt->pPager);
28937     assert( countWriteCursors(pBt)==0 );
28938     pBt->inStmt = 0;
28939   }
28940   sqlite3BtreeLeave(p);
28941   return rc;
28942 }
28943
28944 /*
28945 ** Default key comparison function to be used if no comparison function
28946 ** is specified on the sqlite3BtreeCursor() call.
28947 */
28948 static int dfltCompare(
28949   void *NotUsed,             /* User data is not used */
28950   int n1, const void *p1,    /* First key to compare */
28951   int n2, const void *p2     /* Second key to compare */
28952 ){
28953   int c;
28954   c = memcmp(p1, p2, n1<n2 ? n1 : n2);
28955   if( c==0 ){
28956     c = n1 - n2;
28957   }
28958   return c;
28959 }
28960
28961 /*
28962 ** Create a new cursor for the BTree whose root is on the page
28963 ** iTable.  The act of acquiring a cursor gets a read lock on 
28964 ** the database file.
28965 **
28966 ** If wrFlag==0, then the cursor can only be used for reading.
28967 ** If wrFlag==1, then the cursor can be used for reading or for
28968 ** writing if other conditions for writing are also met.  These
28969 ** are the conditions that must be met in order for writing to
28970 ** be allowed:
28971 **
28972 ** 1:  The cursor must have been opened with wrFlag==1
28973 **
28974 ** 2:  Other database connections that share the same pager cache
28975 **     but which are not in the READ_UNCOMMITTED state may not have
28976 **     cursors open with wrFlag==0 on the same table.  Otherwise
28977 **     the changes made by this write cursor would be visible to
28978 **     the read cursors in the other database connection.
28979 **
28980 ** 3:  The database must be writable (not on read-only media)
28981 **
28982 ** 4:  There must be an active transaction.
28983 **
28984 ** No checking is done to make sure that page iTable really is the
28985 ** root page of a b-tree.  If it is not, then the cursor acquired
28986 ** will not work correctly.
28987 **
28988 ** The comparison function must be logically the same for every cursor
28989 ** on a particular table.  Changing the comparison function will result
28990 ** in incorrect operations.  If the comparison function is NULL, a
28991 ** default comparison function is used.  The comparison function is
28992 ** always ignored for INTKEY tables.
28993 */
28994 static int btreeCursor(
28995   Btree *p,                                   /* The btree */
28996   int iTable,                                 /* Root page of table to open */
28997   int wrFlag,                                 /* 1 to write. 0 read-only */
28998   int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
28999   void *pArg,                                 /* First arg to xCompare() */
29000   BtCursor **ppCur                            /* Write new cursor here */
29001 ){
29002   int rc;
29003   BtCursor *pCur;
29004   BtShared *pBt = p->pBt;
29005
29006   assert( sqlite3BtreeHoldsMutex(p) );
29007   *ppCur = 0;
29008   if( wrFlag ){
29009     if( pBt->readOnly ){
29010       return SQLITE_READONLY;
29011     }
29012     if( checkReadLocks(p, iTable, 0) ){
29013       return SQLITE_LOCKED;
29014     }
29015   }
29016
29017   if( pBt->pPage1==0 ){
29018     rc = lockBtreeWithRetry(p);
29019     if( rc!=SQLITE_OK ){
29020       return rc;
29021     }
29022     if( pBt->readOnly && wrFlag ){
29023       return SQLITE_READONLY;
29024     }
29025   }
29026   pCur = sqlite3MallocZero( sizeof(*pCur) );
29027   if( pCur==0 ){
29028     rc = SQLITE_NOMEM;
29029     goto create_cursor_exception;
29030   }
29031   pCur->pgnoRoot = (Pgno)iTable;
29032   if( iTable==1 && sqlite3PagerPagecount(pBt->pPager)==0 ){
29033     rc = SQLITE_EMPTY;
29034     goto create_cursor_exception;
29035   }
29036   rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
29037   if( rc!=SQLITE_OK ){
29038     goto create_cursor_exception;
29039   }
29040
29041   /* Now that no other errors can occur, finish filling in the BtCursor
29042   ** variables, link the cursor into the BtShared list and set *ppCur (the
29043   ** output argument to this function).
29044   */
29045   pCur->xCompare = xCmp ? xCmp : dfltCompare;
29046   pCur->pArg = pArg;
29047   pCur->pBtree = p;
29048   pCur->pBt = pBt;
29049   pCur->wrFlag = wrFlag;
29050   pCur->pNext = pBt->pCursor;
29051   if( pCur->pNext ){
29052     pCur->pNext->pPrev = pCur;
29053   }
29054   pBt->pCursor = pCur;
29055   pCur->eState = CURSOR_INVALID;
29056   *ppCur = pCur;
29057
29058   return SQLITE_OK;
29059
29060 create_cursor_exception:
29061   if( pCur ){
29062     releasePage(pCur->pPage);
29063     sqlite3_free(pCur);
29064   }
29065   unlockBtreeIfUnused(pBt);
29066   return rc;
29067 }
29068 SQLITE_PRIVATE int sqlite3BtreeCursor(
29069   Btree *p,                                   /* The btree */
29070   int iTable,                                 /* Root page of table to open */
29071   int wrFlag,                                 /* 1 to write. 0 read-only */
29072   int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
29073   void *pArg,                                 /* First arg to xCompare() */
29074   BtCursor **ppCur                            /* Write new cursor here */
29075 ){
29076   int rc;
29077   sqlite3BtreeEnter(p);
29078   p->pBt->db = p->db;
29079   rc = btreeCursor(p, iTable, wrFlag, xCmp, pArg, ppCur);
29080   sqlite3BtreeLeave(p);
29081   return rc;
29082 }
29083
29084
29085 /*
29086 ** Close a cursor.  The read lock on the database file is released
29087 ** when the last cursor is closed.
29088 */
29089 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
29090   BtShared *pBt = pCur->pBt;
29091   Btree *pBtree = pCur->pBtree;
29092
29093   sqlite3BtreeEnter(pBtree);
29094   pBt->db = pBtree->db;
29095   clearCursorPosition(pCur);
29096   if( pCur->pPrev ){
29097     pCur->pPrev->pNext = pCur->pNext;
29098   }else{
29099     pBt->pCursor = pCur->pNext;
29100   }
29101   if( pCur->pNext ){
29102     pCur->pNext->pPrev = pCur->pPrev;
29103   }
29104   releasePage(pCur->pPage);
29105   unlockBtreeIfUnused(pBt);
29106   invalidateOverflowCache(pCur);
29107   sqlite3_free(pCur);
29108   sqlite3BtreeLeave(pBtree);
29109   return SQLITE_OK;
29110 }
29111
29112 /*
29113 ** Make a temporary cursor by filling in the fields of pTempCur.
29114 ** The temporary cursor is not on the cursor list for the Btree.
29115 */
29116 SQLITE_PRIVATE void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
29117   assert( cursorHoldsMutex(pCur) );
29118   memcpy(pTempCur, pCur, sizeof(*pCur));
29119   pTempCur->pNext = 0;
29120   pTempCur->pPrev = 0;
29121   if( pTempCur->pPage ){
29122     sqlite3PagerRef(pTempCur->pPage->pDbPage);
29123   }
29124 }
29125
29126 /*
29127 ** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
29128 ** function above.
29129 */
29130 SQLITE_PRIVATE void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
29131   assert( cursorHoldsMutex(pCur) );
29132   if( pCur->pPage ){
29133     sqlite3PagerUnref(pCur->pPage->pDbPage);
29134   }
29135 }
29136
29137 /*
29138 ** Make sure the BtCursor* given in the argument has a valid
29139 ** BtCursor.info structure.  If it is not already valid, call
29140 ** sqlite3BtreeParseCell() to fill it in.
29141 **
29142 ** BtCursor.info is a cache of the information in the current cell.
29143 ** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
29144 **
29145 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
29146 ** compiler to crash when getCellInfo() is implemented as a macro.
29147 ** But there is a measureable speed advantage to using the macro on gcc
29148 ** (when less compiler optimizations like -Os or -O0 are used and the
29149 ** compiler is not doing agressive inlining.)  So we use a real function
29150 ** for MSVC and a macro for everything else.  Ticket #2457.
29151 */
29152 #ifndef NDEBUG
29153   static void assertCellInfo(BtCursor *pCur){
29154     CellInfo info;
29155     memset(&info, 0, sizeof(info));
29156     sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &info);
29157     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
29158   }
29159 #else
29160   #define assertCellInfo(x)
29161 #endif
29162 #ifdef _MSC_VER
29163   /* Use a real function in MSVC to work around bugs in that compiler. */
29164   static void getCellInfo(BtCursor *pCur){
29165     if( pCur->info.nSize==0 ){
29166       sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info);
29167     }else{
29168       assertCellInfo(pCur);
29169     }
29170   }
29171 #else /* if not _MSC_VER */
29172   /* Use a macro in all other compilers so that the function is inlined */
29173 #define getCellInfo(pCur)                                               \
29174   if( pCur->info.nSize==0 ){                                            \
29175     sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info);         \
29176   }else{                                                                \
29177     assertCellInfo(pCur);                                               \
29178   }
29179 #endif /* _MSC_VER */
29180
29181 /*
29182 ** Set *pSize to the size of the buffer needed to hold the value of
29183 ** the key for the current entry.  If the cursor is not pointing
29184 ** to a valid entry, *pSize is set to 0. 
29185 **
29186 ** For a table with the INTKEY flag set, this routine returns the key
29187 ** itself, not the number of bytes in the key.
29188 */
29189 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
29190   int rc;
29191
29192   assert( cursorHoldsMutex(pCur) );
29193   rc = restoreOrClearCursorPosition(pCur);
29194   if( rc==SQLITE_OK ){
29195     assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
29196     if( pCur->eState==CURSOR_INVALID ){
29197       *pSize = 0;
29198     }else{
29199       getCellInfo(pCur);
29200       *pSize = pCur->info.nKey;
29201     }
29202   }
29203   return rc;
29204 }
29205
29206 /*
29207 ** Set *pSize to the number of bytes of data in the entry the
29208 ** cursor currently points to.  Always return SQLITE_OK.
29209 ** Failure is not possible.  If the cursor is not currently
29210 ** pointing to an entry (which can happen, for example, if
29211 ** the database is empty) then *pSize is set to 0.
29212 */
29213 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
29214   int rc;
29215
29216   assert( cursorHoldsMutex(pCur) );
29217   rc = restoreOrClearCursorPosition(pCur);
29218   if( rc==SQLITE_OK ){
29219     assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
29220     if( pCur->eState==CURSOR_INVALID ){
29221       /* Not pointing at a valid entry - set *pSize to 0. */
29222       *pSize = 0;
29223     }else{
29224       getCellInfo(pCur);
29225       *pSize = pCur->info.nData;
29226     }
29227   }
29228   return rc;
29229 }
29230
29231 /*
29232 ** Given the page number of an overflow page in the database (parameter
29233 ** ovfl), this function finds the page number of the next page in the 
29234 ** linked list of overflow pages. If possible, it uses the auto-vacuum
29235 ** pointer-map data instead of reading the content of page ovfl to do so. 
29236 **
29237 ** If an error occurs an SQLite error code is returned. Otherwise:
29238 **
29239 ** Unless pPgnoNext is NULL, the page number of the next overflow 
29240 ** page in the linked list is written to *pPgnoNext. If page ovfl
29241 ** is the last page in its linked list, *pPgnoNext is set to zero. 
29242 **
29243 ** If ppPage is not NULL, *ppPage is set to the MemPage* handle
29244 ** for page ovfl. The underlying pager page may have been requested
29245 ** with the noContent flag set, so the page data accessable via
29246 ** this handle may not be trusted.
29247 */
29248 static int getOverflowPage(
29249   BtShared *pBt, 
29250   Pgno ovfl,                   /* Overflow page */
29251   MemPage **ppPage,            /* OUT: MemPage handle */
29252   Pgno *pPgnoNext              /* OUT: Next overflow page number */
29253 ){
29254   Pgno next = 0;
29255   int rc;
29256
29257   assert( sqlite3_mutex_held(pBt->mutex) );
29258   /* One of these must not be NULL. Otherwise, why call this function? */
29259   assert(ppPage || pPgnoNext);
29260
29261   /* If pPgnoNext is NULL, then this function is being called to obtain
29262   ** a MemPage* reference only. No page-data is required in this case.
29263   */
29264   if( !pPgnoNext ){
29265     return sqlite3BtreeGetPage(pBt, ovfl, ppPage, 1);
29266   }
29267
29268 #ifndef SQLITE_OMIT_AUTOVACUUM
29269   /* Try to find the next page in the overflow list using the
29270   ** autovacuum pointer-map pages. Guess that the next page in 
29271   ** the overflow list is page number (ovfl+1). If that guess turns 
29272   ** out to be wrong, fall back to loading the data of page 
29273   ** number ovfl to determine the next page number.
29274   */
29275   if( pBt->autoVacuum ){
29276     Pgno pgno;
29277     Pgno iGuess = ovfl+1;
29278     u8 eType;
29279
29280     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
29281       iGuess++;
29282     }
29283
29284     if( iGuess<=sqlite3PagerPagecount(pBt->pPager) ){
29285       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
29286       if( rc!=SQLITE_OK ){
29287         return rc;
29288       }
29289       if( eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
29290         next = iGuess;
29291       }
29292     }
29293   }
29294 #endif
29295
29296   if( next==0 || ppPage ){
29297     MemPage *pPage = 0;
29298
29299     rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, next!=0);
29300     assert(rc==SQLITE_OK || pPage==0);
29301     if( next==0 && rc==SQLITE_OK ){
29302       next = get4byte(pPage->aData);
29303     }
29304
29305     if( ppPage ){
29306       *ppPage = pPage;
29307     }else{
29308       releasePage(pPage);
29309     }
29310   }
29311   *pPgnoNext = next;
29312
29313   return rc;
29314 }
29315
29316 /*
29317 ** Copy data from a buffer to a page, or from a page to a buffer.
29318 **
29319 ** pPayload is a pointer to data stored on database page pDbPage.
29320 ** If argument eOp is false, then nByte bytes of data are copied
29321 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
29322 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
29323 ** of data are copied from the buffer pBuf to pPayload.
29324 **
29325 ** SQLITE_OK is returned on success, otherwise an error code.
29326 */
29327 static int copyPayload(
29328   void *pPayload,           /* Pointer to page data */
29329   void *pBuf,               /* Pointer to buffer */
29330   int nByte,                /* Number of bytes to copy */
29331   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
29332   DbPage *pDbPage           /* Page containing pPayload */
29333 ){
29334   if( eOp ){
29335     /* Copy data from buffer to page (a write operation) */
29336     int rc = sqlite3PagerWrite(pDbPage);
29337     if( rc!=SQLITE_OK ){
29338       return rc;
29339     }
29340     memcpy(pPayload, pBuf, nByte);
29341   }else{
29342     /* Copy data from page to buffer (a read operation) */
29343     memcpy(pBuf, pPayload, nByte);
29344   }
29345   return SQLITE_OK;
29346 }
29347
29348 /*
29349 ** This function is used to read or overwrite payload information
29350 ** for the entry that the pCur cursor is pointing to. If the eOp
29351 ** parameter is 0, this is a read operation (data copied into
29352 ** buffer pBuf). If it is non-zero, a write (data copied from
29353 ** buffer pBuf).
29354 **
29355 ** A total of "amt" bytes are read or written beginning at "offset".
29356 ** Data is read to or from the buffer pBuf.
29357 **
29358 ** This routine does not make a distinction between key and data.
29359 ** It just reads or writes bytes from the payload area.  Data might 
29360 ** appear on the main page or be scattered out on multiple overflow 
29361 ** pages.
29362 **
29363 ** If the BtCursor.isIncrblobHandle flag is set, and the current
29364 ** cursor entry uses one or more overflow pages, this function
29365 ** allocates space for and lazily popluates the overflow page-list 
29366 ** cache array (BtCursor.aOverflow). Subsequent calls use this
29367 ** cache to make seeking to the supplied offset more efficient.
29368 **
29369 ** Once an overflow page-list cache has been allocated, it may be
29370 ** invalidated if some other cursor writes to the same table, or if
29371 ** the cursor is moved to a different row. Additionally, in auto-vacuum
29372 ** mode, the following events may invalidate an overflow page-list cache.
29373 **
29374 **   * An incremental vacuum,
29375 **   * A commit in auto_vacuum="full" mode,
29376 **   * Creating a table (may require moving an overflow page).
29377 */
29378 static int accessPayload(
29379   BtCursor *pCur,      /* Cursor pointing to entry to read from */
29380   int offset,          /* Begin reading this far into payload */
29381   int amt,             /* Read this many bytes */
29382   unsigned char *pBuf, /* Write the bytes into this buffer */ 
29383   int skipKey,         /* offset begins at data if this is true */
29384   int eOp              /* zero to read. non-zero to write. */
29385 ){
29386   unsigned char *aPayload;
29387   int rc = SQLITE_OK;
29388   u32 nKey;
29389   int iIdx = 0;
29390   MemPage *pPage = pCur->pPage;     /* Btree page of current cursor entry */
29391   BtShared *pBt;                   /* Btree this cursor belongs to */
29392
29393   assert( pPage );
29394   assert( pCur->eState==CURSOR_VALID );
29395   assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
29396   assert( offset>=0 );
29397   assert( cursorHoldsMutex(pCur) );
29398
29399   getCellInfo(pCur);
29400   aPayload = pCur->info.pCell + pCur->info.nHeader;
29401   nKey = (pPage->intKey ? 0 : pCur->info.nKey);
29402
29403   if( skipKey ){
29404     offset += nKey;
29405   }
29406   if( offset+amt > nKey+pCur->info.nData ){
29407     /* Trying to read or write past the end of the data is an error */
29408     return SQLITE_ERROR;
29409   }
29410
29411   /* Check if data must be read/written to/from the btree page itself. */
29412   if( offset<pCur->info.nLocal ){
29413     int a = amt;
29414     if( a+offset>pCur->info.nLocal ){
29415       a = pCur->info.nLocal - offset;
29416     }
29417     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
29418     offset = 0;
29419     pBuf += a;
29420     amt -= a;
29421   }else{
29422     offset -= pCur->info.nLocal;
29423   }
29424
29425   pBt = pCur->pBt;
29426   if( rc==SQLITE_OK && amt>0 ){
29427     const int ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
29428     Pgno nextPage;
29429
29430     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
29431
29432 #ifndef SQLITE_OMIT_INCRBLOB
29433     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
29434     ** has not been allocated, allocate it now. The array is sized at
29435     ** one entry for each overflow page in the overflow chain. The
29436     ** page number of the first overflow page is stored in aOverflow[0],
29437     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
29438     ** (the cache is lazily populated).
29439     */
29440     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
29441       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
29442       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
29443       if( nOvfl && !pCur->aOverflow ){
29444         rc = SQLITE_NOMEM;
29445       }
29446     }
29447
29448     /* If the overflow page-list cache has been allocated and the
29449     ** entry for the first required overflow page is valid, skip
29450     ** directly to it.
29451     */
29452     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
29453       iIdx = (offset/ovflSize);
29454       nextPage = pCur->aOverflow[iIdx];
29455       offset = (offset%ovflSize);
29456     }
29457 #endif
29458
29459     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
29460
29461 #ifndef SQLITE_OMIT_INCRBLOB
29462       /* If required, populate the overflow page-list cache. */
29463       if( pCur->aOverflow ){
29464         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
29465         pCur->aOverflow[iIdx] = nextPage;
29466       }
29467 #endif
29468
29469       if( offset>=ovflSize ){
29470         /* The only reason to read this page is to obtain the page
29471         ** number for the next page in the overflow chain. The page
29472         ** data is not required. So first try to lookup the overflow
29473         ** page-list cache, if any, then fall back to the getOverflowPage()
29474         ** function.
29475         */
29476 #ifndef SQLITE_OMIT_INCRBLOB
29477         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
29478           nextPage = pCur->aOverflow[iIdx+1];
29479         } else 
29480 #endif
29481           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
29482         offset -= ovflSize;
29483       }else{
29484         /* Need to read this page properly. It contains some of the
29485         ** range of data that is being read (eOp==0) or written (eOp!=0).
29486         */
29487         DbPage *pDbPage;
29488         int a = amt;
29489         rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
29490         if( rc==SQLITE_OK ){
29491           aPayload = sqlite3PagerGetData(pDbPage);
29492           nextPage = get4byte(aPayload);
29493           if( a + offset > ovflSize ){
29494             a = ovflSize - offset;
29495           }
29496           rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
29497           sqlite3PagerUnref(pDbPage);
29498           offset = 0;
29499           amt -= a;
29500           pBuf += a;
29501         }
29502       }
29503     }
29504   }
29505
29506   if( rc==SQLITE_OK && amt>0 ){
29507     return SQLITE_CORRUPT_BKPT;
29508   }
29509   return rc;
29510 }
29511
29512 /*
29513 ** Read part of the key associated with cursor pCur.  Exactly
29514 ** "amt" bytes will be transfered into pBuf[].  The transfer
29515 ** begins at "offset".
29516 **
29517 ** Return SQLITE_OK on success or an error code if anything goes
29518 ** wrong.  An error is returned if "offset+amt" is larger than
29519 ** the available payload.
29520 */
29521 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
29522   int rc;
29523
29524   assert( cursorHoldsMutex(pCur) );
29525   rc = restoreOrClearCursorPosition(pCur);
29526   if( rc==SQLITE_OK ){
29527     assert( pCur->eState==CURSOR_VALID );
29528     assert( pCur->pPage!=0 );
29529     if( pCur->pPage->intKey ){
29530       return SQLITE_CORRUPT_BKPT;
29531     }
29532     assert( pCur->pPage->intKey==0 );
29533     assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
29534     rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
29535   }
29536   return rc;
29537 }
29538
29539 /*
29540 ** Read part of the data associated with cursor pCur.  Exactly
29541 ** "amt" bytes will be transfered into pBuf[].  The transfer
29542 ** begins at "offset".
29543 **
29544 ** Return SQLITE_OK on success or an error code if anything goes
29545 ** wrong.  An error is returned if "offset+amt" is larger than
29546 ** the available payload.
29547 */
29548 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
29549   int rc;
29550
29551   assert( cursorHoldsMutex(pCur) );
29552   rc = restoreOrClearCursorPosition(pCur);
29553   if( rc==SQLITE_OK ){
29554     assert( pCur->eState==CURSOR_VALID );
29555     assert( pCur->pPage!=0 );
29556     assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
29557     rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
29558   }
29559   return rc;
29560 }
29561
29562 /*
29563 ** Return a pointer to payload information from the entry that the 
29564 ** pCur cursor is pointing to.  The pointer is to the beginning of
29565 ** the key if skipKey==0 and it points to the beginning of data if
29566 ** skipKey==1.  The number of bytes of available key/data is written
29567 ** into *pAmt.  If *pAmt==0, then the value returned will not be
29568 ** a valid pointer.
29569 **
29570 ** This routine is an optimization.  It is common for the entire key
29571 ** and data to fit on the local page and for there to be no overflow
29572 ** pages.  When that is so, this routine can be used to access the
29573 ** key and data without making a copy.  If the key and/or data spills
29574 ** onto overflow pages, then accessPayload() must be used to reassembly
29575 ** the key/data and copy it into a preallocated buffer.
29576 **
29577 ** The pointer returned by this routine looks directly into the cached
29578 ** page of the database.  The data might change or move the next time
29579 ** any btree routine is called.
29580 */
29581 static const unsigned char *fetchPayload(
29582   BtCursor *pCur,      /* Cursor pointing to entry to read from */
29583   int *pAmt,           /* Write the number of available bytes here */
29584   int skipKey          /* read beginning at data if this is true */
29585 ){
29586   unsigned char *aPayload;
29587   MemPage *pPage;
29588   u32 nKey;
29589   int nLocal;
29590
29591   assert( pCur!=0 && pCur->pPage!=0 );
29592   assert( pCur->eState==CURSOR_VALID );
29593   assert( cursorHoldsMutex(pCur) );
29594   pPage = pCur->pPage;
29595   assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
29596   getCellInfo(pCur);
29597   aPayload = pCur->info.pCell;
29598   aPayload += pCur->info.nHeader;
29599   if( pPage->intKey ){
29600     nKey = 0;
29601   }else{
29602     nKey = pCur->info.nKey;
29603   }
29604   if( skipKey ){
29605     aPayload += nKey;
29606     nLocal = pCur->info.nLocal - nKey;
29607   }else{
29608     nLocal = pCur->info.nLocal;
29609     if( nLocal>nKey ){
29610       nLocal = nKey;
29611     }
29612   }
29613   *pAmt = nLocal;
29614   return aPayload;
29615 }
29616
29617
29618 /*
29619 ** For the entry that cursor pCur is point to, return as
29620 ** many bytes of the key or data as are available on the local
29621 ** b-tree page.  Write the number of available bytes into *pAmt.
29622 **
29623 ** The pointer returned is ephemeral.  The key/data may move
29624 ** or be destroyed on the next call to any Btree routine,
29625 ** including calls from other threads against the same cache.
29626 ** Hence, a mutex on the BtShared should be held prior to calling
29627 ** this routine.
29628 **
29629 ** These routines is used to get quick access to key and data
29630 ** in the common case where no overflow pages are used.
29631 */
29632 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
29633   assert( cursorHoldsMutex(pCur) );
29634   if( pCur->eState==CURSOR_VALID ){
29635     return (const void*)fetchPayload(pCur, pAmt, 0);
29636   }
29637   return 0;
29638 }
29639 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
29640   assert( cursorHoldsMutex(pCur) );
29641   if( pCur->eState==CURSOR_VALID ){
29642     return (const void*)fetchPayload(pCur, pAmt, 1);
29643   }
29644   return 0;
29645 }
29646
29647
29648 /*
29649 ** Move the cursor down to a new child page.  The newPgno argument is the
29650 ** page number of the child page to move to.
29651 */
29652 static int moveToChild(BtCursor *pCur, u32 newPgno){
29653   int rc;
29654   MemPage *pNewPage;
29655   MemPage *pOldPage;
29656   BtShared *pBt = pCur->pBt;
29657
29658   assert( cursorHoldsMutex(pCur) );
29659   assert( pCur->eState==CURSOR_VALID );
29660   rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
29661   if( rc ) return rc;
29662   pNewPage->idxParent = pCur->idx;
29663   pOldPage = pCur->pPage;
29664   pOldPage->idxShift = 0;
29665   releasePage(pOldPage);
29666   pCur->pPage = pNewPage;
29667   pCur->idx = 0;
29668   pCur->info.nSize = 0;
29669   if( pNewPage->nCell<1 ){
29670     return SQLITE_CORRUPT_BKPT;
29671   }
29672   return SQLITE_OK;
29673 }
29674
29675 /*
29676 ** Return true if the page is the virtual root of its table.
29677 **
29678 ** The virtual root page is the root page for most tables.  But
29679 ** for the table rooted on page 1, sometime the real root page
29680 ** is empty except for the right-pointer.  In such cases the
29681 ** virtual root page is the page that the right-pointer of page
29682 ** 1 is pointing to.
29683 */
29684 SQLITE_PRIVATE int sqlite3BtreeIsRootPage(MemPage *pPage){
29685   MemPage *pParent;
29686
29687   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
29688   pParent = pPage->pParent;
29689   if( pParent==0 ) return 1;
29690   if( pParent->pgno>1 ) return 0;
29691   if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
29692   return 0;
29693 }
29694
29695 /*
29696 ** Move the cursor up to the parent page.
29697 **
29698 ** pCur->idx is set to the cell index that contains the pointer
29699 ** to the page we are coming from.  If we are coming from the
29700 ** right-most child page then pCur->idx is set to one more than
29701 ** the largest cell index.
29702 */
29703 SQLITE_PRIVATE void sqlite3BtreeMoveToParent(BtCursor *pCur){
29704   MemPage *pParent;
29705   MemPage *pPage;
29706   int idxParent;
29707
29708   assert( cursorHoldsMutex(pCur) );
29709   assert( pCur->eState==CURSOR_VALID );
29710   pPage = pCur->pPage;
29711   assert( pPage!=0 );
29712   assert( !sqlite3BtreeIsRootPage(pPage) );
29713   pParent = pPage->pParent;
29714   assert( pParent!=0 );
29715   idxParent = pPage->idxParent;
29716   sqlite3PagerRef(pParent->pDbPage);
29717   releasePage(pPage);
29718   pCur->pPage = pParent;
29719   pCur->info.nSize = 0;
29720   assert( pParent->idxShift==0 );
29721   pCur->idx = idxParent;
29722 }
29723
29724 /*
29725 ** Move the cursor to the root page
29726 */
29727 static int moveToRoot(BtCursor *pCur){
29728   MemPage *pRoot;
29729   int rc = SQLITE_OK;
29730   Btree *p = pCur->pBtree;
29731   BtShared *pBt = p->pBt;
29732
29733   assert( cursorHoldsMutex(pCur) );
29734   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
29735   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
29736   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
29737   if( pCur->eState>=CURSOR_REQUIRESEEK ){
29738     if( pCur->eState==CURSOR_FAULT ){
29739       return pCur->skip;
29740     }
29741     clearCursorPosition(pCur);
29742   }
29743   pRoot = pCur->pPage;
29744   if( pRoot && pRoot->pgno==pCur->pgnoRoot ){
29745     assert( pRoot->isInit );
29746   }else{
29747     if( 
29748       SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0))
29749     ){
29750       pCur->eState = CURSOR_INVALID;
29751       return rc;
29752     }
29753     releasePage(pCur->pPage);
29754     pCur->pPage = pRoot;
29755   }
29756   pCur->idx = 0;
29757   pCur->info.nSize = 0;
29758   if( pRoot->nCell==0 && !pRoot->leaf ){
29759     Pgno subpage;
29760     assert( pRoot->pgno==1 );
29761     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
29762     assert( subpage>0 );
29763     pCur->eState = CURSOR_VALID;
29764     rc = moveToChild(pCur, subpage);
29765   }
29766   pCur->eState = ((pCur->pPage->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
29767   return rc;
29768 }
29769
29770 /*
29771 ** Move the cursor down to the left-most leaf entry beneath the
29772 ** entry to which it is currently pointing.
29773 **
29774 ** The left-most leaf is the one with the smallest key - the first
29775 ** in ascending order.
29776 */
29777 static int moveToLeftmost(BtCursor *pCur){
29778   Pgno pgno;
29779   int rc = SQLITE_OK;
29780   MemPage *pPage;
29781
29782   assert( cursorHoldsMutex(pCur) );
29783   assert( pCur->eState==CURSOR_VALID );
29784   while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
29785     assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
29786     pgno = get4byte(findCell(pPage, pCur->idx));
29787     rc = moveToChild(pCur, pgno);
29788   }
29789   return rc;
29790 }
29791
29792 /*
29793 ** Move the cursor down to the right-most leaf entry beneath the
29794 ** page to which it is currently pointing.  Notice the difference
29795 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
29796 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
29797 ** finds the right-most entry beneath the *page*.
29798 **
29799 ** The right-most entry is the one with the largest key - the last
29800 ** key in ascending order.
29801 */
29802 static int moveToRightmost(BtCursor *pCur){
29803   Pgno pgno;
29804   int rc = SQLITE_OK;
29805   MemPage *pPage;
29806
29807   assert( cursorHoldsMutex(pCur) );
29808   assert( pCur->eState==CURSOR_VALID );
29809   while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
29810     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
29811     pCur->idx = pPage->nCell;
29812     rc = moveToChild(pCur, pgno);
29813   }
29814   if( rc==SQLITE_OK ){
29815     pCur->idx = pPage->nCell - 1;
29816     pCur->info.nSize = 0;
29817   }
29818   return SQLITE_OK;
29819 }
29820
29821 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
29822 ** on success.  Set *pRes to 0 if the cursor actually points to something
29823 ** or set *pRes to 1 if the table is empty.
29824 */
29825 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
29826   int rc;
29827
29828   assert( cursorHoldsMutex(pCur) );
29829   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
29830   rc = moveToRoot(pCur);
29831   if( rc==SQLITE_OK ){
29832     if( pCur->eState==CURSOR_INVALID ){
29833       assert( pCur->pPage->nCell==0 );
29834       *pRes = 1;
29835       rc = SQLITE_OK;
29836     }else{
29837       assert( pCur->pPage->nCell>0 );
29838       *pRes = 0;
29839       rc = moveToLeftmost(pCur);
29840     }
29841   }
29842   return rc;
29843 }
29844
29845 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
29846 ** on success.  Set *pRes to 0 if the cursor actually points to something
29847 ** or set *pRes to 1 if the table is empty.
29848 */
29849 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
29850   int rc;
29851  
29852   assert( cursorHoldsMutex(pCur) );
29853   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
29854   rc = moveToRoot(pCur);
29855   if( rc==SQLITE_OK ){
29856     if( CURSOR_INVALID==pCur->eState ){
29857       assert( pCur->pPage->nCell==0 );
29858       *pRes = 1;
29859     }else{
29860       assert( pCur->eState==CURSOR_VALID );
29861       *pRes = 0;
29862       rc = moveToRightmost(pCur);
29863     }
29864   }
29865   return rc;
29866 }
29867
29868 /* Move the cursor so that it points to an entry near pKey/nKey.
29869 ** Return a success code.
29870 **
29871 ** For INTKEY tables, only the nKey parameter is used.  pKey is
29872 ** ignored.  For other tables, nKey is the number of bytes of data
29873 ** in pKey.  The comparison function specified when the cursor was
29874 ** created is used to compare keys.
29875 **
29876 ** If an exact match is not found, then the cursor is always
29877 ** left pointing at a leaf page which would hold the entry if it
29878 ** were present.  The cursor might point to an entry that comes
29879 ** before or after the key.
29880 **
29881 ** The result of comparing the key with the entry to which the
29882 ** cursor is written to *pRes if pRes!=NULL.  The meaning of
29883 ** this value is as follows:
29884 **
29885 **     *pRes<0      The cursor is left pointing at an entry that
29886 **                  is smaller than pKey or if the table is empty
29887 **                  and the cursor is therefore left point to nothing.
29888 **
29889 **     *pRes==0     The cursor is left pointing at an entry that
29890 **                  exactly matches pKey.
29891 **
29892 **     *pRes>0      The cursor is left pointing at an entry that
29893 **                  is larger than pKey.
29894 **
29895 */
29896 SQLITE_PRIVATE int sqlite3BtreeMoveto(
29897   BtCursor *pCur,        /* The cursor to be moved */
29898   const void *pKey,      /* The key content for indices.  Not used by tables */
29899   i64 nKey,              /* Size of pKey.  Or the key for tables */
29900   int biasRight,         /* If true, bias the search to the high end */
29901   int *pRes              /* Search result flag */
29902 ){
29903   int rc;
29904
29905   assert( cursorHoldsMutex(pCur) );
29906   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
29907   rc = moveToRoot(pCur);
29908   if( rc ){
29909     return rc;
29910   }
29911   assert( pCur->pPage );
29912   assert( pCur->pPage->isInit );
29913   if( pCur->eState==CURSOR_INVALID ){
29914     *pRes = -1;
29915     assert( pCur->pPage->nCell==0 );
29916     return SQLITE_OK;
29917   }
29918   for(;;){
29919     int lwr, upr;
29920     Pgno chldPg;
29921     MemPage *pPage = pCur->pPage;
29922     int c = -1;  /* pRes return if table is empty must be -1 */
29923     lwr = 0;
29924     upr = pPage->nCell-1;
29925     if( !pPage->intKey && pKey==0 ){
29926       return SQLITE_CORRUPT_BKPT;
29927     }
29928     if( biasRight ){
29929       pCur->idx = upr;
29930     }else{
29931       pCur->idx = (upr+lwr)/2;
29932     }
29933     if( lwr<=upr ) for(;;){
29934       void *pCellKey;
29935       i64 nCellKey;
29936       pCur->info.nSize = 0;
29937       if( pPage->intKey ){
29938         u8 *pCell;
29939         pCell = findCell(pPage, pCur->idx) + pPage->childPtrSize;
29940         if( pPage->hasData ){
29941           u32 dummy;
29942           pCell += getVarint32(pCell, &dummy);
29943         }
29944         getVarint(pCell, (u64 *)&nCellKey);
29945         if( nCellKey<nKey ){
29946           c = -1;
29947         }else if( nCellKey>nKey ){
29948           c = +1;
29949         }else{
29950           c = 0;
29951         }
29952       }else{
29953         int available;
29954         pCellKey = (void *)fetchPayload(pCur, &available, 0);
29955         nCellKey = pCur->info.nKey;
29956         if( available>=nCellKey ){
29957           c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
29958         }else{
29959           pCellKey = sqlite3_malloc( nCellKey );
29960           if( pCellKey==0 ) return SQLITE_NOMEM;
29961           rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
29962           c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
29963           sqlite3_free(pCellKey);
29964           if( rc ){
29965             return rc;
29966           }
29967         }
29968       }
29969       if( c==0 ){
29970         if( pPage->leafData && !pPage->leaf ){
29971           lwr = pCur->idx;
29972           upr = lwr - 1;
29973           break;
29974         }else{
29975           if( pRes ) *pRes = 0;
29976           return SQLITE_OK;
29977         }
29978       }
29979       if( c<0 ){
29980         lwr = pCur->idx+1;
29981       }else{
29982         upr = pCur->idx-1;
29983       }
29984       if( lwr>upr ){
29985         break;
29986       }
29987       pCur->idx = (lwr+upr)/2;
29988     }
29989     assert( lwr==upr+1 );
29990     assert( pPage->isInit );
29991     if( pPage->leaf ){
29992       chldPg = 0;
29993     }else if( lwr>=pPage->nCell ){
29994       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
29995     }else{
29996       chldPg = get4byte(findCell(pPage, lwr));
29997     }
29998     if( chldPg==0 ){
29999       assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
30000       if( pRes ) *pRes = c;
30001       return SQLITE_OK;
30002     }
30003     pCur->idx = lwr;
30004     pCur->info.nSize = 0;
30005     rc = moveToChild(pCur, chldPg);
30006     if( rc ){
30007       return rc;
30008     }
30009   }
30010   /* NOT REACHED */
30011 }
30012
30013
30014 /*
30015 ** Return TRUE if the cursor is not pointing at an entry of the table.
30016 **
30017 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
30018 ** past the last entry in the table or sqlite3BtreePrev() moves past
30019 ** the first entry.  TRUE is also returned if the table is empty.
30020 */
30021 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
30022   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
30023   ** have been deleted? This API will need to change to return an error code
30024   ** as well as the boolean result value.
30025   */
30026   return (CURSOR_VALID!=pCur->eState);
30027 }
30028
30029 /*
30030 ** Return the database connection handle for a cursor.
30031 */
30032 SQLITE_PRIVATE sqlite3 *sqlite3BtreeCursorDb(const BtCursor *pCur){
30033   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
30034   return pCur->pBtree->db;
30035 }
30036
30037 /*
30038 ** Advance the cursor to the next entry in the database.  If
30039 ** successful then set *pRes=0.  If the cursor
30040 ** was already pointing to the last entry in the database before
30041 ** this routine was called, then set *pRes=1.
30042 */
30043 static int btreeNext(BtCursor *pCur, int *pRes){
30044   int rc;
30045   MemPage *pPage;
30046
30047   assert( cursorHoldsMutex(pCur) );
30048   rc = restoreOrClearCursorPosition(pCur);
30049   if( rc!=SQLITE_OK ){
30050     return rc;
30051   }
30052   assert( pRes!=0 );
30053   pPage = pCur->pPage;
30054   if( CURSOR_INVALID==pCur->eState ){
30055     *pRes = 1;
30056     return SQLITE_OK;
30057   }
30058   if( pCur->skip>0 ){
30059     pCur->skip = 0;
30060     *pRes = 0;
30061     return SQLITE_OK;
30062   }
30063   pCur->skip = 0;
30064
30065   assert( pPage->isInit );
30066   assert( pCur->idx<pPage->nCell );
30067
30068   pCur->idx++;
30069   pCur->info.nSize = 0;
30070   if( pCur->idx>=pPage->nCell ){
30071     if( !pPage->leaf ){
30072       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
30073       if( rc ) return rc;
30074       rc = moveToLeftmost(pCur);
30075       *pRes = 0;
30076       return rc;
30077     }
30078     do{
30079       if( sqlite3BtreeIsRootPage(pPage) ){
30080         *pRes = 1;
30081         pCur->eState = CURSOR_INVALID;
30082         return SQLITE_OK;
30083       }
30084       sqlite3BtreeMoveToParent(pCur);
30085       pPage = pCur->pPage;
30086     }while( pCur->idx>=pPage->nCell );
30087     *pRes = 0;
30088     if( pPage->leafData ){
30089       rc = sqlite3BtreeNext(pCur, pRes);
30090     }else{
30091       rc = SQLITE_OK;
30092     }
30093     return rc;
30094   }
30095   *pRes = 0;
30096   if( pPage->leaf ){
30097     return SQLITE_OK;
30098   }
30099   rc = moveToLeftmost(pCur);
30100   return rc;
30101 }
30102 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
30103   int rc;
30104   assert( cursorHoldsMutex(pCur) );
30105   rc = btreeNext(pCur, pRes);
30106   return rc;
30107 }
30108
30109
30110 /*
30111 ** Step the cursor to the back to the previous entry in the database.  If
30112 ** successful then set *pRes=0.  If the cursor
30113 ** was already pointing to the first entry in the database before
30114 ** this routine was called, then set *pRes=1.
30115 */
30116 static int btreePrevious(BtCursor *pCur, int *pRes){
30117   int rc;
30118   Pgno pgno;
30119   MemPage *pPage;
30120
30121   assert( cursorHoldsMutex(pCur) );
30122   rc = restoreOrClearCursorPosition(pCur);
30123   if( rc!=SQLITE_OK ){
30124     return rc;
30125   }
30126   if( CURSOR_INVALID==pCur->eState ){
30127     *pRes = 1;
30128     return SQLITE_OK;
30129   }
30130   if( pCur->skip<0 ){
30131     pCur->skip = 0;
30132     *pRes = 0;
30133     return SQLITE_OK;
30134   }
30135   pCur->skip = 0;
30136
30137   pPage = pCur->pPage;
30138   assert( pPage->isInit );
30139   assert( pCur->idx>=0 );
30140   if( !pPage->leaf ){
30141     pgno = get4byte( findCell(pPage, pCur->idx) );
30142     rc = moveToChild(pCur, pgno);
30143     if( rc ){
30144       return rc;
30145     }
30146     rc = moveToRightmost(pCur);
30147   }else{
30148     while( pCur->idx==0 ){
30149       if( sqlite3BtreeIsRootPage(pPage) ){
30150         pCur->eState = CURSOR_INVALID;
30151         *pRes = 1;
30152         return SQLITE_OK;
30153       }
30154       sqlite3BtreeMoveToParent(pCur);
30155       pPage = pCur->pPage;
30156     }
30157     pCur->idx--;
30158     pCur->info.nSize = 0;
30159     if( pPage->leafData && !pPage->leaf ){
30160       rc = sqlite3BtreePrevious(pCur, pRes);
30161     }else{
30162       rc = SQLITE_OK;
30163     }
30164   }
30165   *pRes = 0;
30166   return rc;
30167 }
30168 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
30169   int rc;
30170   assert( cursorHoldsMutex(pCur) );
30171   rc = btreePrevious(pCur, pRes);
30172   return rc;
30173 }
30174
30175 /*
30176 ** Allocate a new page from the database file.
30177 **
30178 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
30179 ** has already been called on the new page.)  The new page has also
30180 ** been referenced and the calling routine is responsible for calling
30181 ** sqlite3PagerUnref() on the new page when it is done.
30182 **
30183 ** SQLITE_OK is returned on success.  Any other return value indicates
30184 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
30185 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
30186 **
30187 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
30188 ** locate a page close to the page number "nearby".  This can be used in an
30189 ** attempt to keep related pages close to each other in the database file,
30190 ** which in turn can make database access faster.
30191 **
30192 ** If the "exact" parameter is not 0, and the page-number nearby exists 
30193 ** anywhere on the free-list, then it is guarenteed to be returned. This
30194 ** is only used by auto-vacuum databases when allocating a new table.
30195 */
30196 static int allocateBtreePage(
30197   BtShared *pBt, 
30198   MemPage **ppPage, 
30199   Pgno *pPgno, 
30200   Pgno nearby,
30201   u8 exact
30202 ){
30203   MemPage *pPage1;
30204   int rc;
30205   int n;     /* Number of pages on the freelist */
30206   int k;     /* Number of leaves on the trunk of the freelist */
30207   MemPage *pTrunk = 0;
30208   MemPage *pPrevTrunk = 0;
30209
30210   assert( sqlite3_mutex_held(pBt->mutex) );
30211   pPage1 = pBt->pPage1;
30212   n = get4byte(&pPage1->aData[36]);
30213   if( n>0 ){
30214     /* There are pages on the freelist.  Reuse one of those pages. */
30215     Pgno iTrunk;
30216     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
30217     
30218     /* If the 'exact' parameter was true and a query of the pointer-map
30219     ** shows that the page 'nearby' is somewhere on the free-list, then
30220     ** the entire-list will be searched for that page.
30221     */
30222 #ifndef SQLITE_OMIT_AUTOVACUUM
30223     if( exact && nearby<=sqlite3PagerPagecount(pBt->pPager) ){
30224       u8 eType;
30225       assert( nearby>0 );
30226       assert( pBt->autoVacuum );
30227       rc = ptrmapGet(pBt, nearby, &eType, 0);
30228       if( rc ) return rc;
30229       if( eType==PTRMAP_FREEPAGE ){
30230         searchList = 1;
30231       }
30232       *pPgno = nearby;
30233     }
30234 #endif
30235
30236     /* Decrement the free-list count by 1. Set iTrunk to the index of the
30237     ** first free-list trunk page. iPrevTrunk is initially 1.
30238     */
30239     rc = sqlite3PagerWrite(pPage1->pDbPage);
30240     if( rc ) return rc;
30241     put4byte(&pPage1->aData[36], n-1);
30242
30243     /* The code within this loop is run only once if the 'searchList' variable
30244     ** is not true. Otherwise, it runs once for each trunk-page on the
30245     ** free-list until the page 'nearby' is located.
30246     */
30247     do {
30248       pPrevTrunk = pTrunk;
30249       if( pPrevTrunk ){
30250         iTrunk = get4byte(&pPrevTrunk->aData[0]);
30251       }else{
30252         iTrunk = get4byte(&pPage1->aData[32]);
30253       }
30254       rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
30255       if( rc ){
30256         pTrunk = 0;
30257         goto end_allocate_page;
30258       }
30259
30260       k = get4byte(&pTrunk->aData[4]);
30261       if( k==0 && !searchList ){
30262         /* The trunk has no leaves and the list is not being searched. 
30263         ** So extract the trunk page itself and use it as the newly 
30264         ** allocated page */
30265         assert( pPrevTrunk==0 );
30266         rc = sqlite3PagerWrite(pTrunk->pDbPage);
30267         if( rc ){
30268           goto end_allocate_page;
30269         }
30270         *pPgno = iTrunk;
30271         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
30272         *ppPage = pTrunk;
30273         pTrunk = 0;
30274         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
30275       }else if( k>pBt->usableSize/4 - 8 ){
30276         /* Value of k is out of range.  Database corruption */
30277         rc = SQLITE_CORRUPT_BKPT;
30278         goto end_allocate_page;
30279 #ifndef SQLITE_OMIT_AUTOVACUUM
30280       }else if( searchList && nearby==iTrunk ){
30281         /* The list is being searched and this trunk page is the page
30282         ** to allocate, regardless of whether it has leaves.
30283         */
30284         assert( *pPgno==iTrunk );
30285         *ppPage = pTrunk;
30286         searchList = 0;
30287         rc = sqlite3PagerWrite(pTrunk->pDbPage);
30288         if( rc ){
30289           goto end_allocate_page;
30290         }
30291         if( k==0 ){
30292           if( !pPrevTrunk ){
30293             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
30294           }else{
30295             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
30296           }
30297         }else{
30298           /* The trunk page is required by the caller but it contains 
30299           ** pointers to free-list leaves. The first leaf becomes a trunk
30300           ** page in this case.
30301           */
30302           MemPage *pNewTrunk;
30303           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
30304           rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
30305           if( rc!=SQLITE_OK ){
30306             goto end_allocate_page;
30307           }
30308           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
30309           if( rc!=SQLITE_OK ){
30310             releasePage(pNewTrunk);
30311             goto end_allocate_page;
30312           }
30313           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
30314           put4byte(&pNewTrunk->aData[4], k-1);
30315           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
30316           releasePage(pNewTrunk);
30317           if( !pPrevTrunk ){
30318             put4byte(&pPage1->aData[32], iNewTrunk);
30319           }else{
30320             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
30321             if( rc ){
30322               goto end_allocate_page;
30323             }
30324             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
30325           }
30326         }
30327         pTrunk = 0;
30328         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
30329 #endif
30330       }else{
30331         /* Extract a leaf from the trunk */
30332         int closest;
30333         Pgno iPage;
30334         unsigned char *aData = pTrunk->aData;
30335         rc = sqlite3PagerWrite(pTrunk->pDbPage);
30336         if( rc ){
30337           goto end_allocate_page;
30338         }
30339         if( nearby>0 ){
30340           int i, dist;
30341           closest = 0;
30342           dist = get4byte(&aData[8]) - nearby;
30343           if( dist<0 ) dist = -dist;
30344           for(i=1; i<k; i++){
30345             int d2 = get4byte(&aData[8+i*4]) - nearby;
30346             if( d2<0 ) d2 = -d2;
30347             if( d2<dist ){
30348               closest = i;
30349               dist = d2;
30350             }
30351           }
30352         }else{
30353           closest = 0;
30354         }
30355
30356         iPage = get4byte(&aData[8+closest*4]);
30357         if( !searchList || iPage==nearby ){
30358           *pPgno = iPage;
30359           if( *pPgno>sqlite3PagerPagecount(pBt->pPager) ){
30360             /* Free page off the end of the file */
30361             return SQLITE_CORRUPT_BKPT;
30362           }
30363           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
30364                  ": %d more free pages\n",
30365                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
30366           if( closest<k-1 ){
30367             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
30368           }
30369           put4byte(&aData[4], k-1);
30370           rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 1);
30371           if( rc==SQLITE_OK ){
30372             sqlite3PagerDontRollback((*ppPage)->pDbPage);
30373             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
30374             if( rc!=SQLITE_OK ){
30375               releasePage(*ppPage);
30376             }
30377           }
30378           searchList = 0;
30379         }
30380       }
30381       releasePage(pPrevTrunk);
30382       pPrevTrunk = 0;
30383     }while( searchList );
30384   }else{
30385     /* There are no pages on the freelist, so create a new page at the
30386     ** end of the file */
30387     *pPgno = sqlite3PagerPagecount(pBt->pPager) + 1;
30388
30389 #ifndef SQLITE_OMIT_AUTOVACUUM
30390     if( pBt->nTrunc ){
30391       /* An incr-vacuum has already run within this transaction. So the
30392       ** page to allocate is not from the physical end of the file, but
30393       ** at pBt->nTrunc. 
30394       */
30395       *pPgno = pBt->nTrunc+1;
30396       if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
30397         (*pPgno)++;
30398       }
30399     }
30400     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
30401       /* If *pPgno refers to a pointer-map page, allocate two new pages
30402       ** at the end of the file instead of one. The first allocated page
30403       ** becomes a new pointer-map page, the second is used by the caller.
30404       */
30405       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
30406       assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
30407       (*pPgno)++;
30408     }
30409     if( pBt->nTrunc ){
30410       pBt->nTrunc = *pPgno;
30411     }
30412 #endif
30413
30414     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
30415     rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
30416     if( rc ) return rc;
30417     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
30418     if( rc!=SQLITE_OK ){
30419       releasePage(*ppPage);
30420     }
30421     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
30422   }
30423
30424   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
30425
30426 end_allocate_page:
30427   releasePage(pTrunk);
30428   releasePage(pPrevTrunk);
30429   return rc;
30430 }
30431
30432 /*
30433 ** Add a page of the database file to the freelist.
30434 **
30435 ** sqlite3PagerUnref() is NOT called for pPage.
30436 */
30437 static int freePage(MemPage *pPage){
30438   BtShared *pBt = pPage->pBt;
30439   MemPage *pPage1 = pBt->pPage1;
30440   int rc, n, k;
30441
30442   /* Prepare the page for freeing */
30443   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
30444   assert( pPage->pgno>1 );
30445   pPage->isInit = 0;
30446   releasePage(pPage->pParent);
30447   pPage->pParent = 0;
30448
30449   /* Increment the free page count on pPage1 */
30450   rc = sqlite3PagerWrite(pPage1->pDbPage);
30451   if( rc ) return rc;
30452   n = get4byte(&pPage1->aData[36]);
30453   put4byte(&pPage1->aData[36], n+1);
30454
30455 #ifdef SQLITE_SECURE_DELETE
30456   /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
30457   ** always fully overwrite deleted information with zeros.
30458   */
30459   rc = sqlite3PagerWrite(pPage->pDbPage);
30460   if( rc ) return rc;
30461   memset(pPage->aData, 0, pPage->pBt->pageSize);
30462 #endif
30463
30464 #ifndef SQLITE_OMIT_AUTOVACUUM
30465   /* If the database supports auto-vacuum, write an entry in the pointer-map
30466   ** to indicate that the page is free.
30467   */
30468   if( pBt->autoVacuum ){
30469     rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
30470     if( rc ) return rc;
30471   }
30472 #endif
30473
30474   if( n==0 ){
30475     /* This is the first free page */
30476     rc = sqlite3PagerWrite(pPage->pDbPage);
30477     if( rc ) return rc;
30478     memset(pPage->aData, 0, 8);
30479     put4byte(&pPage1->aData[32], pPage->pgno);
30480     TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
30481   }else{
30482     /* Other free pages already exist.  Retrive the first trunk page
30483     ** of the freelist and find out how many leaves it has. */
30484     MemPage *pTrunk;
30485     rc = sqlite3BtreeGetPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk, 0);
30486     if( rc ) return rc;
30487     k = get4byte(&pTrunk->aData[4]);
30488     if( k>=pBt->usableSize/4 - 8 ){
30489       /* The trunk is full.  Turn the page being freed into a new
30490       ** trunk page with no leaves. */
30491       rc = sqlite3PagerWrite(pPage->pDbPage);
30492       if( rc==SQLITE_OK ){
30493         put4byte(pPage->aData, pTrunk->pgno);
30494         put4byte(&pPage->aData[4], 0);
30495         put4byte(&pPage1->aData[32], pPage->pgno);
30496         TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
30497                 pPage->pgno, pTrunk->pgno));
30498       }
30499     }else if( k<0 ){
30500       rc = SQLITE_CORRUPT;
30501     }else{
30502       /* Add the newly freed page as a leaf on the current trunk */
30503       rc = sqlite3PagerWrite(pTrunk->pDbPage);
30504       if( rc==SQLITE_OK ){
30505         put4byte(&pTrunk->aData[4], k+1);
30506         put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
30507 #ifndef SQLITE_SECURE_DELETE
30508         sqlite3PagerDontWrite(pPage->pDbPage);
30509 #endif
30510       }
30511       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
30512     }
30513     releasePage(pTrunk);
30514   }
30515   return rc;
30516 }
30517
30518 /*
30519 ** Free any overflow pages associated with the given Cell.
30520 */
30521 static int clearCell(MemPage *pPage, unsigned char *pCell){
30522   BtShared *pBt = pPage->pBt;
30523   CellInfo info;
30524   Pgno ovflPgno;
30525   int rc;
30526   int nOvfl;
30527   int ovflPageSize;
30528
30529   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
30530   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
30531   if( info.iOverflow==0 ){
30532     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
30533   }
30534   ovflPgno = get4byte(&pCell[info.iOverflow]);
30535   ovflPageSize = pBt->usableSize - 4;
30536   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
30537   assert( ovflPgno==0 || nOvfl>0 );
30538   while( nOvfl-- ){
30539     MemPage *pOvfl;
30540     if( ovflPgno==0 || ovflPgno>sqlite3PagerPagecount(pBt->pPager) ){
30541       return SQLITE_CORRUPT_BKPT;
30542     }
30543
30544     rc = getOverflowPage(pBt, ovflPgno, &pOvfl, (nOvfl==0)?0:&ovflPgno);
30545     if( rc ) return rc;
30546     rc = freePage(pOvfl);
30547     sqlite3PagerUnref(pOvfl->pDbPage);
30548     if( rc ) return rc;
30549   }
30550   return SQLITE_OK;
30551 }
30552
30553 /*
30554 ** Create the byte sequence used to represent a cell on page pPage
30555 ** and write that byte sequence into pCell[].  Overflow pages are
30556 ** allocated and filled in as necessary.  The calling procedure
30557 ** is responsible for making sure sufficient space has been allocated
30558 ** for pCell[].
30559 **
30560 ** Note that pCell does not necessary need to point to the pPage->aData
30561 ** area.  pCell might point to some temporary storage.  The cell will
30562 ** be constructed in this temporary area then copied into pPage->aData
30563 ** later.
30564 */
30565 static int fillInCell(
30566   MemPage *pPage,                /* The page that contains the cell */
30567   unsigned char *pCell,          /* Complete text of the cell */
30568   const void *pKey, i64 nKey,    /* The key */
30569   const void *pData,int nData,   /* The data */
30570   int nZero,                     /* Extra zero bytes to append to pData */
30571   int *pnSize                    /* Write cell size here */
30572 ){
30573   int nPayload;
30574   const u8 *pSrc;
30575   int nSrc, n, rc;
30576   int spaceLeft;
30577   MemPage *pOvfl = 0;
30578   MemPage *pToRelease = 0;
30579   unsigned char *pPrior;
30580   unsigned char *pPayload;
30581   BtShared *pBt = pPage->pBt;
30582   Pgno pgnoOvfl = 0;
30583   int nHeader;
30584   CellInfo info;
30585
30586   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
30587
30588   /* Fill in the header. */
30589   nHeader = 0;
30590   if( !pPage->leaf ){
30591     nHeader += 4;
30592   }
30593   if( pPage->hasData ){
30594     nHeader += putVarint(&pCell[nHeader], nData+nZero);
30595   }else{
30596     nData = nZero = 0;
30597   }
30598   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
30599   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
30600   assert( info.nHeader==nHeader );
30601   assert( info.nKey==nKey );
30602   assert( info.nData==nData+nZero );
30603   
30604   /* Fill in the payload */
30605   nPayload = nData + nZero;
30606   if( pPage->intKey ){
30607     pSrc = pData;
30608     nSrc = nData;
30609     nData = 0;
30610   }else{
30611     nPayload += nKey;
30612     pSrc = pKey;
30613     nSrc = nKey;
30614   }
30615   *pnSize = info.nSize;
30616   spaceLeft = info.nLocal;
30617   pPayload = &pCell[nHeader];
30618   pPrior = &pCell[info.iOverflow];
30619
30620   while( nPayload>0 ){
30621     if( spaceLeft==0 ){
30622       int isExact = 0;
30623 #ifndef SQLITE_OMIT_AUTOVACUUM
30624       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
30625       if( pBt->autoVacuum ){
30626         do{
30627           pgnoOvfl++;
30628         } while( 
30629           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
30630         );
30631         if( pgnoOvfl>1 ){
30632           /* isExact = 1; */
30633         }
30634       }
30635 #endif
30636       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, isExact);
30637 #ifndef SQLITE_OMIT_AUTOVACUUM
30638       /* If the database supports auto-vacuum, and the second or subsequent
30639       ** overflow page is being allocated, add an entry to the pointer-map
30640       ** for that page now. 
30641       **
30642       ** If this is the first overflow page, then write a partial entry 
30643       ** to the pointer-map. If we write nothing to this pointer-map slot,
30644       ** then the optimistic overflow chain processing in clearCell()
30645       ** may misinterpret the uninitialised values and delete the
30646       ** wrong pages from the database.
30647       */
30648       if( pBt->autoVacuum && rc==SQLITE_OK ){
30649         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
30650         rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
30651         if( rc ){
30652           releasePage(pOvfl);
30653         }
30654       }
30655 #endif
30656       if( rc ){
30657         releasePage(pToRelease);
30658         return rc;
30659       }
30660       put4byte(pPrior, pgnoOvfl);
30661       releasePage(pToRelease);
30662       pToRelease = pOvfl;
30663       pPrior = pOvfl->aData;
30664       put4byte(pPrior, 0);
30665       pPayload = &pOvfl->aData[4];
30666       spaceLeft = pBt->usableSize - 4;
30667     }
30668     n = nPayload;
30669     if( n>spaceLeft ) n = spaceLeft;
30670     if( nSrc>0 ){
30671       if( n>nSrc ) n = nSrc;
30672       assert( pSrc );
30673       memcpy(pPayload, pSrc, n);
30674     }else{
30675       memset(pPayload, 0, n);
30676     }
30677     nPayload -= n;
30678     pPayload += n;
30679     pSrc += n;
30680     nSrc -= n;
30681     spaceLeft -= n;
30682     if( nSrc==0 ){
30683       nSrc = nData;
30684       pSrc = pData;
30685     }
30686   }
30687   releasePage(pToRelease);
30688   return SQLITE_OK;
30689 }
30690
30691 /*
30692 ** Change the MemPage.pParent pointer on the page whose number is
30693 ** given in the second argument so that MemPage.pParent holds the
30694 ** pointer in the third argument.
30695 */
30696 static int reparentPage(BtShared *pBt, Pgno pgno, MemPage *pNewParent, int idx){
30697   MemPage *pThis;
30698   DbPage *pDbPage;
30699
30700   assert( sqlite3_mutex_held(pBt->mutex) );
30701   assert( pNewParent!=0 );
30702   if( pgno==0 ) return SQLITE_OK;
30703   assert( pBt->pPager!=0 );
30704   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
30705   if( pDbPage ){
30706     pThis = (MemPage *)sqlite3PagerGetExtra(pDbPage);
30707     if( pThis->isInit ){
30708       assert( pThis->aData==sqlite3PagerGetData(pDbPage) );
30709       if( pThis->pParent!=pNewParent ){
30710         if( pThis->pParent ) sqlite3PagerUnref(pThis->pParent->pDbPage);
30711         pThis->pParent = pNewParent;
30712         sqlite3PagerRef(pNewParent->pDbPage);
30713       }
30714       pThis->idxParent = idx;
30715     }
30716     sqlite3PagerUnref(pDbPage);
30717   }
30718
30719 #ifndef SQLITE_OMIT_AUTOVACUUM
30720   if( pBt->autoVacuum ){
30721     return ptrmapPut(pBt, pgno, PTRMAP_BTREE, pNewParent->pgno);
30722   }
30723 #endif
30724   return SQLITE_OK;
30725 }
30726
30727
30728
30729 /*
30730 ** Change the pParent pointer of all children of pPage to point back
30731 ** to pPage.
30732 **
30733 ** In other words, for every child of pPage, invoke reparentPage()
30734 ** to make sure that each child knows that pPage is its parent.
30735 **
30736 ** This routine gets called after you memcpy() one page into
30737 ** another.
30738 */
30739 static int reparentChildPages(MemPage *pPage){
30740   int i;
30741   BtShared *pBt = pPage->pBt;
30742   int rc = SQLITE_OK;
30743
30744   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
30745   if( pPage->leaf ) return SQLITE_OK;
30746
30747   for(i=0; i<pPage->nCell; i++){
30748     u8 *pCell = findCell(pPage, i);
30749     if( !pPage->leaf ){
30750       rc = reparentPage(pBt, get4byte(pCell), pPage, i);
30751       if( rc!=SQLITE_OK ) return rc;
30752     }
30753   }
30754   if( !pPage->leaf ){
30755     rc = reparentPage(pBt, get4byte(&pPage->aData[pPage->hdrOffset+8]), 
30756        pPage, i);
30757     pPage->idxShift = 0;
30758   }
30759   return rc;
30760 }
30761
30762 /*
30763 ** Remove the i-th cell from pPage.  This routine effects pPage only.
30764 ** The cell content is not freed or deallocated.  It is assumed that
30765 ** the cell content has been copied someplace else.  This routine just
30766 ** removes the reference to the cell from pPage.
30767 **
30768 ** "sz" must be the number of bytes in the cell.
30769 */
30770 static void dropCell(MemPage *pPage, int idx, int sz){
30771   int i;          /* Loop counter */
30772   int pc;         /* Offset to cell content of cell being deleted */
30773   u8 *data;       /* pPage->aData */
30774   u8 *ptr;        /* Used to move bytes around within data[] */
30775
30776   assert( idx>=0 && idx<pPage->nCell );
30777   assert( sz==cellSize(pPage, idx) );
30778   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
30779   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
30780   data = pPage->aData;
30781   ptr = &data[pPage->cellOffset + 2*idx];
30782   pc = get2byte(ptr);
30783   assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
30784   freeSpace(pPage, pc, sz);
30785   for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
30786     ptr[0] = ptr[2];
30787     ptr[1] = ptr[3];
30788   }
30789   pPage->nCell--;
30790   put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
30791   pPage->nFree += 2;
30792   pPage->idxShift = 1;
30793 }
30794
30795 /*
30796 ** Insert a new cell on pPage at cell index "i".  pCell points to the
30797 ** content of the cell.
30798 **
30799 ** If the cell content will fit on the page, then put it there.  If it
30800 ** will not fit, then make a copy of the cell content into pTemp if
30801 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
30802 ** in pPage->aOvfl[] and make it point to the cell content (either
30803 ** in pTemp or the original pCell) and also record its index. 
30804 ** Allocating a new entry in pPage->aCell[] implies that 
30805 ** pPage->nOverflow is incremented.
30806 **
30807 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
30808 ** cell. The caller will overwrite them after this function returns. If
30809 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
30810 ** (but pCell+nSkip is always valid).
30811 */
30812 static int insertCell(
30813   MemPage *pPage,   /* Page into which we are copying */
30814   int i,            /* New cell becomes the i-th cell of the page */
30815   u8 *pCell,        /* Content of the new cell */
30816   int sz,           /* Bytes of content in pCell */
30817   u8 *pTemp,        /* Temp storage space for pCell, if needed */
30818   u8 nSkip          /* Do not write the first nSkip bytes of the cell */
30819 ){
30820   int idx;          /* Where to write new cell content in data[] */
30821   int j;            /* Loop counter */
30822   int top;          /* First byte of content for any cell in data[] */
30823   int end;          /* First byte past the last cell pointer in data[] */
30824   int ins;          /* Index in data[] where new cell pointer is inserted */
30825   int hdr;          /* Offset into data[] of the page header */
30826   int cellOffset;   /* Address of first cell pointer in data[] */
30827   u8 *data;         /* The content of the whole page */
30828   u8 *ptr;          /* Used for moving information around in data[] */
30829
30830   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
30831   assert( sz==cellSizePtr(pPage, pCell) );
30832   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
30833   if( pPage->nOverflow || sz+2>pPage->nFree ){
30834     if( pTemp ){
30835       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
30836       pCell = pTemp;
30837     }
30838     j = pPage->nOverflow++;
30839     assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
30840     pPage->aOvfl[j].pCell = pCell;
30841     pPage->aOvfl[j].idx = i;
30842     pPage->nFree = 0;
30843   }else{
30844     int rc = sqlite3PagerWrite(pPage->pDbPage);
30845     if( rc!=SQLITE_OK ){
30846       return rc;
30847     }
30848     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
30849     data = pPage->aData;
30850     hdr = pPage->hdrOffset;
30851     top = get2byte(&data[hdr+5]);
30852     cellOffset = pPage->cellOffset;
30853     end = cellOffset + 2*pPage->nCell + 2;
30854     ins = cellOffset + 2*i;
30855     if( end > top - sz ){
30856       rc = defragmentPage(pPage);
30857       if( rc!=SQLITE_OK ) return rc;
30858       top = get2byte(&data[hdr+5]);
30859       assert( end + sz <= top );
30860     }
30861     idx = allocateSpace(pPage, sz);
30862     assert( idx>0 );
30863     assert( end <= get2byte(&data[hdr+5]) );
30864     pPage->nCell++;
30865     pPage->nFree -= 2;
30866     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
30867     for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
30868       ptr[0] = ptr[-2];
30869       ptr[1] = ptr[-1];
30870     }
30871     put2byte(&data[ins], idx);
30872     put2byte(&data[hdr+3], pPage->nCell);
30873     pPage->idxShift = 1;
30874 #ifndef SQLITE_OMIT_AUTOVACUUM
30875     if( pPage->pBt->autoVacuum ){
30876       /* The cell may contain a pointer to an overflow page. If so, write
30877       ** the entry for the overflow page into the pointer map.
30878       */
30879       CellInfo info;
30880       sqlite3BtreeParseCellPtr(pPage, pCell, &info);
30881       assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
30882       if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
30883         Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
30884         rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
30885         if( rc!=SQLITE_OK ) return rc;
30886       }
30887     }
30888 #endif
30889   }
30890
30891   return SQLITE_OK;
30892 }
30893
30894 /*
30895 ** Add a list of cells to a page.  The page should be initially empty.
30896 ** The cells are guaranteed to fit on the page.
30897 */
30898 static void assemblePage(
30899   MemPage *pPage,   /* The page to be assemblied */
30900   int nCell,        /* The number of cells to add to this page */
30901   u8 **apCell,      /* Pointers to cell bodies */
30902   int *aSize        /* Sizes of the cells */
30903 ){
30904   int i;            /* Loop counter */
30905   int totalSize;    /* Total size of all cells */
30906   int hdr;          /* Index of page header */
30907   int cellptr;      /* Address of next cell pointer */
30908   int cellbody;     /* Address of next cell body */
30909   u8 *data;         /* Data for the page */
30910
30911   assert( pPage->nOverflow==0 );
30912   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
30913   totalSize = 0;
30914   for(i=0; i<nCell; i++){
30915     totalSize += aSize[i];
30916   }
30917   assert( totalSize+2*nCell<=pPage->nFree );
30918   assert( pPage->nCell==0 );
30919   cellptr = pPage->cellOffset;
30920   data = pPage->aData;
30921   hdr = pPage->hdrOffset;
30922   put2byte(&data[hdr+3], nCell);
30923   if( nCell ){
30924     cellbody = allocateSpace(pPage, totalSize);
30925     assert( cellbody>0 );
30926     assert( pPage->nFree >= 2*nCell );
30927     pPage->nFree -= 2*nCell;
30928     for(i=0; i<nCell; i++){
30929       put2byte(&data[cellptr], cellbody);
30930       memcpy(&data[cellbody], apCell[i], aSize[i]);
30931       cellptr += 2;
30932       cellbody += aSize[i];
30933     }
30934     assert( cellbody==pPage->pBt->usableSize );
30935   }
30936   pPage->nCell = nCell;
30937 }
30938
30939 /*
30940 ** The following parameters determine how many adjacent pages get involved
30941 ** in a balancing operation.  NN is the number of neighbors on either side
30942 ** of the page that participate in the balancing operation.  NB is the
30943 ** total number of pages that participate, including the target page and
30944 ** NN neighbors on either side.
30945 **
30946 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
30947 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
30948 ** in exchange for a larger degradation in INSERT and UPDATE performance.
30949 ** The value of NN appears to give the best results overall.
30950 */
30951 #define NN 1             /* Number of neighbors on either side of pPage */
30952 #define NB (NN*2+1)      /* Total pages involved in the balance */
30953
30954 /* Forward reference */
30955 static int balance(MemPage*, int);
30956
30957 #ifndef SQLITE_OMIT_QUICKBALANCE
30958 /*
30959 ** This version of balance() handles the common special case where
30960 ** a new entry is being inserted on the extreme right-end of the
30961 ** tree, in other words, when the new entry will become the largest
30962 ** entry in the tree.
30963 **
30964 ** Instead of trying balance the 3 right-most leaf pages, just add
30965 ** a new page to the right-hand side and put the one new entry in
30966 ** that page.  This leaves the right side of the tree somewhat
30967 ** unbalanced.  But odds are that we will be inserting new entries
30968 ** at the end soon afterwards so the nearly empty page will quickly
30969 ** fill up.  On average.
30970 **
30971 ** pPage is the leaf page which is the right-most page in the tree.
30972 ** pParent is its parent.  pPage must have a single overflow entry
30973 ** which is also the right-most entry on the page.
30974 */
30975 static int balance_quick(MemPage *pPage, MemPage *pParent){
30976   int rc;
30977   MemPage *pNew;
30978   Pgno pgnoNew;
30979   u8 *pCell;
30980   int szCell;
30981   CellInfo info;
30982   BtShared *pBt = pPage->pBt;
30983   int parentIdx = pParent->nCell;   /* pParent new divider cell index */
30984   int parentSize;                   /* Size of new divider cell */
30985   u8 parentCell[64];                /* Space for the new divider cell */
30986
30987   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
30988
30989   /* Allocate a new page. Insert the overflow cell from pPage
30990   ** into it. Then remove the overflow cell from pPage.
30991   */
30992   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
30993   if( rc!=SQLITE_OK ){
30994     return rc;
30995   }
30996   pCell = pPage->aOvfl[0].pCell;
30997   szCell = cellSizePtr(pPage, pCell);
30998   zeroPage(pNew, pPage->aData[0]);
30999   assemblePage(pNew, 1, &pCell, &szCell);
31000   pPage->nOverflow = 0;
31001
31002   /* Set the parent of the newly allocated page to pParent. */
31003   pNew->pParent = pParent;
31004   sqlite3PagerRef(pParent->pDbPage);
31005
31006   /* pPage is currently the right-child of pParent. Change this
31007   ** so that the right-child is the new page allocated above and
31008   ** pPage is the next-to-right child. 
31009   */
31010   assert( pPage->nCell>0 );
31011   pCell = findCell(pPage, pPage->nCell-1);
31012   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
31013   rc = fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
31014   if( rc!=SQLITE_OK ){
31015     return rc;
31016   }
31017   assert( parentSize<64 );
31018   rc = insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
31019   if( rc!=SQLITE_OK ){
31020     return rc;
31021   }
31022   put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
31023   put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
31024
31025 #ifndef SQLITE_OMIT_AUTOVACUUM
31026   /* If this is an auto-vacuum database, update the pointer map
31027   ** with entries for the new page, and any pointer from the 
31028   ** cell on the page to an overflow page.
31029   */
31030   if( pBt->autoVacuum ){
31031     rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
31032     if( rc==SQLITE_OK ){
31033       rc = ptrmapPutOvfl(pNew, 0);
31034     }
31035     if( rc!=SQLITE_OK ){
31036       releasePage(pNew);
31037       return rc;
31038     }
31039   }
31040 #endif
31041
31042   /* Release the reference to the new page and balance the parent page,
31043   ** in case the divider cell inserted caused it to become overfull.
31044   */
31045   releasePage(pNew);
31046   return balance(pParent, 0);
31047 }
31048 #endif /* SQLITE_OMIT_QUICKBALANCE */
31049
31050 /*
31051 ** This routine redistributes Cells on pPage and up to NN*2 siblings
31052 ** of pPage so that all pages have about the same amount of free space.
31053 ** Usually NN siblings on either side of pPage is used in the balancing,
31054 ** though more siblings might come from one side if pPage is the first
31055 ** or last child of its parent.  If pPage has fewer than 2*NN siblings
31056 ** (something which can only happen if pPage is the root page or a 
31057 ** child of root) then all available siblings participate in the balancing.
31058 **
31059 ** The number of siblings of pPage might be increased or decreased by one or
31060 ** two in an effort to keep pages nearly full but not over full. The root page
31061 ** is special and is allowed to be nearly empty. If pPage is 
31062 ** the root page, then the depth of the tree might be increased
31063 ** or decreased by one, as necessary, to keep the root page from being
31064 ** overfull or completely empty.
31065 **
31066 ** Note that when this routine is called, some of the Cells on pPage
31067 ** might not actually be stored in pPage->aData[].  This can happen
31068 ** if the page is overfull.  Part of the job of this routine is to
31069 ** make sure all Cells for pPage once again fit in pPage->aData[].
31070 **
31071 ** In the course of balancing the siblings of pPage, the parent of pPage
31072 ** might become overfull or underfull.  If that happens, then this routine
31073 ** is called recursively on the parent.
31074 **
31075 ** If this routine fails for any reason, it might leave the database
31076 ** in a corrupted state.  So if this routine fails, the database should
31077 ** be rolled back.
31078 */
31079 static int balance_nonroot(MemPage *pPage){
31080   MemPage *pParent;            /* The parent of pPage */
31081   BtShared *pBt;               /* The whole database */
31082   int nCell = 0;               /* Number of cells in apCell[] */
31083   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
31084   int nOld;                    /* Number of pages in apOld[] */
31085   int nNew;                    /* Number of pages in apNew[] */
31086   int nDiv;                    /* Number of cells in apDiv[] */
31087   int i, j, k;                 /* Loop counters */
31088   int idx;                     /* Index of pPage in pParent->aCell[] */
31089   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
31090   int rc;                      /* The return code */
31091   int leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
31092   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
31093   int usableSpace;             /* Bytes in pPage beyond the header */
31094   int pageFlags;               /* Value of pPage->aData[0] */
31095   int subtotal;                /* Subtotal of bytes in cells on one page */
31096   int iSpace = 0;              /* First unused byte of aSpace[] */
31097   MemPage *apOld[NB];          /* pPage and up to two siblings */
31098   Pgno pgnoOld[NB];            /* Page numbers for each page in apOld[] */
31099   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
31100   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
31101   Pgno pgnoNew[NB+2];          /* Page numbers for each page in apNew[] */
31102   u8 *apDiv[NB];               /* Divider cells in pParent */
31103   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
31104   int szNew[NB+2];             /* Combined size of cells place on i-th page */
31105   u8 **apCell = 0;             /* All cells begin balanced */
31106   int *szCell;                 /* Local size of all cells in apCell[] */
31107   u8 *aCopy[NB];               /* Space for holding data of apCopy[] */
31108   u8 *aSpace;                  /* Space to hold copies of dividers cells */
31109 #ifndef SQLITE_OMIT_AUTOVACUUM
31110   u8 *aFrom = 0;
31111 #endif
31112
31113   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
31114
31115   /* 
31116   ** Find the parent page.
31117   */
31118   assert( pPage->isInit );
31119   assert( sqlite3PagerIswriteable(pPage->pDbPage) || pPage->nOverflow==1 );
31120   pBt = pPage->pBt;
31121   pParent = pPage->pParent;
31122   assert( pParent );
31123   if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
31124     return rc;
31125   }
31126   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
31127
31128 #ifndef SQLITE_OMIT_QUICKBALANCE
31129   /*
31130   ** A special case:  If a new entry has just been inserted into a
31131   ** table (that is, a btree with integer keys and all data at the leaves)
31132   ** and the new entry is the right-most entry in the tree (it has the
31133   ** largest key) then use the special balance_quick() routine for
31134   ** balancing.  balance_quick() is much faster and results in a tighter
31135   ** packing of data in the common case.
31136   */
31137   if( pPage->leaf &&
31138       pPage->intKey &&
31139       pPage->leafData &&
31140       pPage->nOverflow==1 &&
31141       pPage->aOvfl[0].idx==pPage->nCell &&
31142       pPage->pParent->pgno!=1 &&
31143       get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
31144   ){
31145     /*
31146     ** TODO: Check the siblings to the left of pPage. It may be that
31147     ** they are not full and no new page is required.
31148     */
31149     return balance_quick(pPage, pParent);
31150   }
31151 #endif
31152
31153   if( SQLITE_OK!=(rc = sqlite3PagerWrite(pPage->pDbPage)) ){
31154     return rc;
31155   }
31156
31157   /*
31158   ** Find the cell in the parent page whose left child points back
31159   ** to pPage.  The "idx" variable is the index of that cell.  If pPage
31160   ** is the rightmost child of pParent then set idx to pParent->nCell 
31161   */
31162   if( pParent->idxShift ){
31163     Pgno pgno;
31164     pgno = pPage->pgno;
31165     assert( pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
31166     for(idx=0; idx<pParent->nCell; idx++){
31167       if( get4byte(findCell(pParent, idx))==pgno ){
31168         break;
31169       }
31170     }
31171     assert( idx<pParent->nCell
31172              || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
31173   }else{
31174     idx = pPage->idxParent;
31175   }
31176
31177   /*
31178   ** Initialize variables so that it will be safe to jump
31179   ** directly to balance_cleanup at any moment.
31180   */
31181   nOld = nNew = 0;
31182   sqlite3PagerRef(pParent->pDbPage);
31183
31184   /*
31185   ** Find sibling pages to pPage and the cells in pParent that divide
31186   ** the siblings.  An attempt is made to find NN siblings on either
31187   ** side of pPage.  More siblings are taken from one side, however, if
31188   ** pPage there are fewer than NN siblings on the other side.  If pParent
31189   ** has NB or fewer children then all children of pParent are taken.
31190   */
31191   nxDiv = idx - NN;
31192   if( nxDiv + NB > pParent->nCell ){
31193     nxDiv = pParent->nCell - NB + 1;
31194   }
31195   if( nxDiv<0 ){
31196     nxDiv = 0;
31197   }
31198   nDiv = 0;
31199   for(i=0, k=nxDiv; i<NB; i++, k++){
31200     if( k<pParent->nCell ){
31201       apDiv[i] = findCell(pParent, k);
31202       nDiv++;
31203       assert( !pParent->leaf );
31204       pgnoOld[i] = get4byte(apDiv[i]);
31205     }else if( k==pParent->nCell ){
31206       pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
31207     }else{
31208       break;
31209     }
31210     rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
31211     if( rc ) goto balance_cleanup;
31212     apOld[i]->idxParent = k;
31213     apCopy[i] = 0;
31214     assert( i==nOld );
31215     nOld++;
31216     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
31217   }
31218
31219   /* Make nMaxCells a multiple of 2 in order to preserve 8-byte
31220   ** alignment */
31221   nMaxCells = (nMaxCells + 1)&~1;
31222
31223   /*
31224   ** Allocate space for memory structures
31225   */
31226   apCell = sqlite3_malloc( 
31227        nMaxCells*sizeof(u8*)                           /* apCell */
31228      + nMaxCells*sizeof(int)                           /* szCell */
31229      + ROUND8(sizeof(MemPage))*NB                      /* aCopy */
31230      + pBt->pageSize*(5+NB)                            /* aSpace */
31231      + (ISAUTOVACUUM ? nMaxCells : 0)                  /* aFrom */
31232   );
31233   if( apCell==0 ){
31234     rc = SQLITE_NOMEM;
31235     goto balance_cleanup;
31236   }
31237   szCell = (int*)&apCell[nMaxCells];
31238   aCopy[0] = (u8*)&szCell[nMaxCells];
31239   assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
31240   for(i=1; i<NB; i++){
31241     aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
31242     assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
31243   }
31244   aSpace = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
31245   assert( ((aSpace - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
31246 #ifndef SQLITE_OMIT_AUTOVACUUM
31247   if( pBt->autoVacuum ){
31248     aFrom = &aSpace[5*pBt->pageSize];
31249   }
31250 #endif
31251   
31252   /*
31253   ** Make copies of the content of pPage and its siblings into aOld[].
31254   ** The rest of this function will use data from the copies rather
31255   ** that the original pages since the original pages will be in the
31256   ** process of being overwritten.
31257   */
31258   for(i=0; i<nOld; i++){
31259     MemPage *p = apCopy[i] = (MemPage*)aCopy[i];
31260     memcpy(p, apOld[i], sizeof(MemPage));
31261     p->aData = (void*)&p[1];
31262     memcpy(p->aData, apOld[i]->aData, pBt->pageSize);
31263   }
31264
31265   /*
31266   ** Load pointers to all cells on sibling pages and the divider cells
31267   ** into the local apCell[] array.  Make copies of the divider cells
31268   ** into space obtained form aSpace[] and remove the the divider Cells
31269   ** from pParent.
31270   **
31271   ** If the siblings are on leaf pages, then the child pointers of the
31272   ** divider cells are stripped from the cells before they are copied
31273   ** into aSpace[].  In this way, all cells in apCell[] are without
31274   ** child pointers.  If siblings are not leaves, then all cell in
31275   ** apCell[] include child pointers.  Either way, all cells in apCell[]
31276   ** are alike.
31277   **
31278   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
31279   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
31280   */
31281   nCell = 0;
31282   leafCorrection = pPage->leaf*4;
31283   leafData = pPage->leafData && pPage->leaf;
31284   for(i=0; i<nOld; i++){
31285     MemPage *pOld = apCopy[i];
31286     int limit = pOld->nCell+pOld->nOverflow;
31287     for(j=0; j<limit; j++){
31288       assert( nCell<nMaxCells );
31289       apCell[nCell] = findOverflowCell(pOld, j);
31290       szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
31291 #ifndef SQLITE_OMIT_AUTOVACUUM
31292       if( pBt->autoVacuum ){
31293         int a;
31294         aFrom[nCell] = i;
31295         for(a=0; a<pOld->nOverflow; a++){
31296           if( pOld->aOvfl[a].pCell==apCell[nCell] ){
31297             aFrom[nCell] = 0xFF;
31298             break;
31299           }
31300         }
31301       }
31302 #endif
31303       nCell++;
31304     }
31305     if( i<nOld-1 ){
31306       int sz = cellSizePtr(pParent, apDiv[i]);
31307       if( leafData ){
31308         /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
31309         ** are duplicates of keys on the child pages.  We need to remove
31310         ** the divider cells from pParent, but the dividers cells are not
31311         ** added to apCell[] because they are duplicates of child cells.
31312         */
31313         dropCell(pParent, nxDiv, sz);
31314       }else{
31315         u8 *pTemp;
31316         assert( nCell<nMaxCells );
31317         szCell[nCell] = sz;
31318         pTemp = &aSpace[iSpace];
31319         iSpace += sz;
31320         assert( iSpace<=pBt->pageSize*5 );
31321         memcpy(pTemp, apDiv[i], sz);
31322         apCell[nCell] = pTemp+leafCorrection;
31323 #ifndef SQLITE_OMIT_AUTOVACUUM
31324         if( pBt->autoVacuum ){
31325           aFrom[nCell] = 0xFF;
31326         }
31327 #endif
31328         dropCell(pParent, nxDiv, sz);
31329         szCell[nCell] -= leafCorrection;
31330         assert( get4byte(pTemp)==pgnoOld[i] );
31331         if( !pOld->leaf ){
31332           assert( leafCorrection==0 );
31333           /* The right pointer of the child page pOld becomes the left
31334           ** pointer of the divider cell */
31335           memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
31336         }else{
31337           assert( leafCorrection==4 );
31338           if( szCell[nCell]<4 ){
31339             /* Do not allow any cells smaller than 4 bytes. */
31340             szCell[nCell] = 4;
31341           }
31342         }
31343         nCell++;
31344       }
31345     }
31346   }
31347
31348   /*
31349   ** Figure out the number of pages needed to hold all nCell cells.
31350   ** Store this number in "k".  Also compute szNew[] which is the total
31351   ** size of all cells on the i-th page and cntNew[] which is the index
31352   ** in apCell[] of the cell that divides page i from page i+1.  
31353   ** cntNew[k] should equal nCell.
31354   **
31355   ** Values computed by this block:
31356   **
31357   **           k: The total number of sibling pages
31358   **    szNew[i]: Spaced used on the i-th sibling page.
31359   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
31360   **              the right of the i-th sibling page.
31361   ** usableSpace: Number of bytes of space available on each sibling.
31362   ** 
31363   */
31364   usableSpace = pBt->usableSize - 12 + leafCorrection;
31365   for(subtotal=k=i=0; i<nCell; i++){
31366     assert( i<nMaxCells );
31367     subtotal += szCell[i] + 2;
31368     if( subtotal > usableSpace ){
31369       szNew[k] = subtotal - szCell[i];
31370       cntNew[k] = i;
31371       if( leafData ){ i--; }
31372       subtotal = 0;
31373       k++;
31374     }
31375   }
31376   szNew[k] = subtotal;
31377   cntNew[k] = nCell;
31378   k++;
31379
31380   /*
31381   ** The packing computed by the previous block is biased toward the siblings
31382   ** on the left side.  The left siblings are always nearly full, while the
31383   ** right-most sibling might be nearly empty.  This block of code attempts
31384   ** to adjust the packing of siblings to get a better balance.
31385   **
31386   ** This adjustment is more than an optimization.  The packing above might
31387   ** be so out of balance as to be illegal.  For example, the right-most
31388   ** sibling might be completely empty.  This adjustment is not optional.
31389   */
31390   for(i=k-1; i>0; i--){
31391     int szRight = szNew[i];  /* Size of sibling on the right */
31392     int szLeft = szNew[i-1]; /* Size of sibling on the left */
31393     int r;              /* Index of right-most cell in left sibling */
31394     int d;              /* Index of first cell to the left of right sibling */
31395
31396     r = cntNew[i-1] - 1;
31397     d = r + 1 - leafData;
31398     assert( d<nMaxCells );
31399     assert( r<nMaxCells );
31400     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
31401       szRight += szCell[d] + 2;
31402       szLeft -= szCell[r] + 2;
31403       cntNew[i-1]--;
31404       r = cntNew[i-1] - 1;
31405       d = r + 1 - leafData;
31406     }
31407     szNew[i] = szRight;
31408     szNew[i-1] = szLeft;
31409   }
31410
31411   /* Either we found one or more cells (cntnew[0])>0) or we are the
31412   ** a virtual root page.  A virtual root page is when the real root
31413   ** page is page 1 and we are the only child of that page.
31414   */
31415   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
31416
31417   /*
31418   ** Allocate k new pages.  Reuse old pages where possible.
31419   */
31420   assert( pPage->pgno>1 );
31421   pageFlags = pPage->aData[0];
31422   for(i=0; i<k; i++){
31423     MemPage *pNew;
31424     if( i<nOld ){
31425       pNew = apNew[i] = apOld[i];
31426       pgnoNew[i] = pgnoOld[i];
31427       apOld[i] = 0;
31428       rc = sqlite3PagerWrite(pNew->pDbPage);
31429       nNew++;
31430       if( rc ) goto balance_cleanup;
31431     }else{
31432       assert( i>0 );
31433       rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
31434       if( rc ) goto balance_cleanup;
31435       apNew[i] = pNew;
31436       nNew++;
31437     }
31438     zeroPage(pNew, pageFlags);
31439   }
31440
31441   /* Free any old pages that were not reused as new pages.
31442   */
31443   while( i<nOld ){
31444     rc = freePage(apOld[i]);
31445     if( rc ) goto balance_cleanup;
31446     releasePage(apOld[i]);
31447     apOld[i] = 0;
31448     i++;
31449   }
31450
31451   /*
31452   ** Put the new pages in accending order.  This helps to
31453   ** keep entries in the disk file in order so that a scan
31454   ** of the table is a linear scan through the file.  That
31455   ** in turn helps the operating system to deliver pages
31456   ** from the disk more rapidly.
31457   **
31458   ** An O(n^2) insertion sort algorithm is used, but since
31459   ** n is never more than NB (a small constant), that should
31460   ** not be a problem.
31461   **
31462   ** When NB==3, this one optimization makes the database
31463   ** about 25% faster for large insertions and deletions.
31464   */
31465   for(i=0; i<k-1; i++){
31466     int minV = pgnoNew[i];
31467     int minI = i;
31468     for(j=i+1; j<k; j++){
31469       if( pgnoNew[j]<(unsigned)minV ){
31470         minI = j;
31471         minV = pgnoNew[j];
31472       }
31473     }
31474     if( minI>i ){
31475       int t;
31476       MemPage *pT;
31477       t = pgnoNew[i];
31478       pT = apNew[i];
31479       pgnoNew[i] = pgnoNew[minI];
31480       apNew[i] = apNew[minI];
31481       pgnoNew[minI] = t;
31482       apNew[minI] = pT;
31483     }
31484   }
31485   TRACE(("BALANCE: old: %d %d %d  new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
31486     pgnoOld[0], 
31487     nOld>=2 ? pgnoOld[1] : 0,
31488     nOld>=3 ? pgnoOld[2] : 0,
31489     pgnoNew[0], szNew[0],
31490     nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
31491     nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
31492     nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
31493     nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
31494
31495   /*
31496   ** Evenly distribute the data in apCell[] across the new pages.
31497   ** Insert divider cells into pParent as necessary.
31498   */
31499   j = 0;
31500   for(i=0; i<nNew; i++){
31501     /* Assemble the new sibling page. */
31502     MemPage *pNew = apNew[i];
31503     assert( j<nMaxCells );
31504     assert( pNew->pgno==pgnoNew[i] );
31505     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
31506     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
31507     assert( pNew->nOverflow==0 );
31508
31509 #ifndef SQLITE_OMIT_AUTOVACUUM
31510     /* If this is an auto-vacuum database, update the pointer map entries
31511     ** that point to the siblings that were rearranged. These can be: left
31512     ** children of cells, the right-child of the page, or overflow pages
31513     ** pointed to by cells.
31514     */
31515     if( pBt->autoVacuum ){
31516       for(k=j; k<cntNew[i]; k++){
31517         assert( k<nMaxCells );
31518         if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
31519           rc = ptrmapPutOvfl(pNew, k-j);
31520           if( rc!=SQLITE_OK ){
31521             goto balance_cleanup;
31522           }
31523         }
31524       }
31525     }
31526 #endif
31527
31528     j = cntNew[i];
31529
31530     /* If the sibling page assembled above was not the right-most sibling,
31531     ** insert a divider cell into the parent page.
31532     */
31533     if( i<nNew-1 && j<nCell ){
31534       u8 *pCell;
31535       u8 *pTemp;
31536       int sz;
31537
31538       assert( j<nMaxCells );
31539       pCell = apCell[j];
31540       sz = szCell[j] + leafCorrection;
31541       if( !pNew->leaf ){
31542         memcpy(&pNew->aData[8], pCell, 4);
31543         pTemp = 0;
31544       }else if( leafData ){
31545         /* If the tree is a leaf-data tree, and the siblings are leaves, 
31546         ** then there is no divider cell in apCell[]. Instead, the divider 
31547         ** cell consists of the integer key for the right-most cell of 
31548         ** the sibling-page assembled above only.
31549         */
31550         CellInfo info;
31551         j--;
31552         sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
31553         pCell = &aSpace[iSpace];
31554         fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
31555         iSpace += sz;
31556         assert( iSpace<=pBt->pageSize*5 );
31557         pTemp = 0;
31558       }else{
31559         pCell -= 4;
31560         pTemp = &aSpace[iSpace];
31561         iSpace += sz;
31562         assert( iSpace<=pBt->pageSize*5 );
31563         /* Obscure case for non-leaf-data trees: If the cell at pCell was
31564         ** previously stored on a leaf node, and its reported size was 4
31565         ** bytes, then it may actually be smaller than this 
31566         ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
31567         ** any cell). But it is important to pass the correct size to 
31568         ** insertCell(), so reparse the cell now.
31569         **
31570         ** Note that this can never happen in an SQLite data file, as all
31571         ** cells are at least 4 bytes. It only happens in b-trees used
31572         ** to evaluate "IN (SELECT ...)" and similar clauses.
31573         */
31574         if( szCell[j]==4 ){
31575           assert(leafCorrection==4);
31576           sz = cellSizePtr(pParent, pCell);
31577         }
31578       }
31579       rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
31580       if( rc!=SQLITE_OK ) goto balance_cleanup;
31581       put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
31582 #ifndef SQLITE_OMIT_AUTOVACUUM
31583       /* If this is an auto-vacuum database, and not a leaf-data tree,
31584       ** then update the pointer map with an entry for the overflow page
31585       ** that the cell just inserted points to (if any).
31586       */
31587       if( pBt->autoVacuum && !leafData ){
31588         rc = ptrmapPutOvfl(pParent, nxDiv);
31589         if( rc!=SQLITE_OK ){
31590           goto balance_cleanup;
31591         }
31592       }
31593 #endif
31594       j++;
31595       nxDiv++;
31596     }
31597   }
31598   assert( j==nCell );
31599   assert( nOld>0 );
31600   assert( nNew>0 );
31601   if( (pageFlags & PTF_LEAF)==0 ){
31602     memcpy(&apNew[nNew-1]->aData[8], &apCopy[nOld-1]->aData[8], 4);
31603   }
31604   if( nxDiv==pParent->nCell+pParent->nOverflow ){
31605     /* Right-most sibling is the right-most child of pParent */
31606     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
31607   }else{
31608     /* Right-most sibling is the left child of the first entry in pParent
31609     ** past the right-most divider entry */
31610     put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
31611   }
31612
31613   /*
31614   ** Reparent children of all cells.
31615   */
31616   for(i=0; i<nNew; i++){
31617     rc = reparentChildPages(apNew[i]);
31618     if( rc!=SQLITE_OK ) goto balance_cleanup;
31619   }
31620   rc = reparentChildPages(pParent);
31621   if( rc!=SQLITE_OK ) goto balance_cleanup;
31622
31623   /*
31624   ** Balance the parent page.  Note that the current page (pPage) might
31625   ** have been added to the freelist so it might no longer be initialized.
31626   ** But the parent page will always be initialized.
31627   */
31628   assert( pParent->isInit );
31629   rc = balance(pParent, 0);
31630   
31631   /*
31632   ** Cleanup before returning.
31633   */
31634 balance_cleanup:
31635   sqlite3_free(apCell);
31636   for(i=0; i<nOld; i++){
31637     releasePage(apOld[i]);
31638   }
31639   for(i=0; i<nNew; i++){
31640     releasePage(apNew[i]);
31641   }
31642   releasePage(pParent);
31643   TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
31644           pPage->pgno, nOld, nNew, nCell));
31645   return rc;
31646 }
31647
31648 /*
31649 ** This routine is called for the root page of a btree when the root
31650 ** page contains no cells.  This is an opportunity to make the tree
31651 ** shallower by one level.
31652 */
31653 static int balance_shallower(MemPage *pPage){
31654   MemPage *pChild;             /* The only child page of pPage */
31655   Pgno pgnoChild;              /* Page number for pChild */
31656   int rc = SQLITE_OK;          /* Return code from subprocedures */
31657   BtShared *pBt;                  /* The main BTree structure */
31658   int mxCellPerPage;           /* Maximum number of cells per page */
31659   u8 **apCell;                 /* All cells from pages being balanced */
31660   int *szCell;                 /* Local size of all cells */
31661
31662   assert( pPage->pParent==0 );
31663   assert( pPage->nCell==0 );
31664   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
31665   pBt = pPage->pBt;
31666   mxCellPerPage = MX_CELL(pBt);
31667   apCell = sqlite3_malloc( mxCellPerPage*(sizeof(u8*)+sizeof(int)) );
31668   if( apCell==0 ) return SQLITE_NOMEM;
31669   szCell = (int*)&apCell[mxCellPerPage];
31670   if( pPage->leaf ){
31671     /* The table is completely empty */
31672     TRACE(("BALANCE: empty table %d\n", pPage->pgno));
31673   }else{
31674     /* The root page is empty but has one child.  Transfer the
31675     ** information from that one child into the root page if it 
31676     ** will fit.  This reduces the depth of the tree by one.
31677     **
31678     ** If the root page is page 1, it has less space available than
31679     ** its child (due to the 100 byte header that occurs at the beginning
31680     ** of the database fle), so it might not be able to hold all of the 
31681     ** information currently contained in the child.  If this is the 
31682     ** case, then do not do the transfer.  Leave page 1 empty except
31683     ** for the right-pointer to the child page.  The child page becomes
31684     ** the virtual root of the tree.
31685     */
31686     pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
31687     assert( pgnoChild>0 );
31688     assert( pgnoChild<=sqlite3PagerPagecount(pPage->pBt->pPager) );
31689     rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
31690     if( rc ) goto end_shallow_balance;
31691     if( pPage->pgno==1 ){
31692       rc = sqlite3BtreeInitPage(pChild, pPage);
31693       if( rc ) goto end_shallow_balance;
31694       assert( pChild->nOverflow==0 );
31695       if( pChild->nFree>=100 ){
31696         /* The child information will fit on the root page, so do the
31697         ** copy */
31698         int i;
31699         zeroPage(pPage, pChild->aData[0]);
31700         for(i=0; i<pChild->nCell; i++){
31701           apCell[i] = findCell(pChild,i);
31702           szCell[i] = cellSizePtr(pChild, apCell[i]);
31703         }
31704         assemblePage(pPage, pChild->nCell, apCell, szCell);
31705         /* Copy the right-pointer of the child to the parent. */
31706         put4byte(&pPage->aData[pPage->hdrOffset+8], 
31707             get4byte(&pChild->aData[pChild->hdrOffset+8]));
31708         freePage(pChild);
31709         TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
31710       }else{
31711         /* The child has more information that will fit on the root.
31712         ** The tree is already balanced.  Do nothing. */
31713         TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
31714       }
31715     }else{
31716       memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
31717       pPage->isInit = 0;
31718       pPage->pParent = 0;
31719       rc = sqlite3BtreeInitPage(pPage, 0);
31720       assert( rc==SQLITE_OK );
31721       freePage(pChild);
31722       TRACE(("BALANCE: transfer child %d into root %d\n",
31723               pChild->pgno, pPage->pgno));
31724     }
31725     rc = reparentChildPages(pPage);
31726     assert( pPage->nOverflow==0 );
31727 #ifndef SQLITE_OMIT_AUTOVACUUM
31728     if( pBt->autoVacuum ){
31729       int i;
31730       for(i=0; i<pPage->nCell; i++){ 
31731         rc = ptrmapPutOvfl(pPage, i);
31732         if( rc!=SQLITE_OK ){
31733           goto end_shallow_balance;
31734         }
31735       }
31736     }
31737 #endif
31738     releasePage(pChild);
31739   }
31740 end_shallow_balance:
31741   sqlite3_free(apCell);
31742   return rc;
31743 }
31744
31745
31746 /*
31747 ** The root page is overfull
31748 **
31749 ** When this happens, Create a new child page and copy the
31750 ** contents of the root into the child.  Then make the root
31751 ** page an empty page with rightChild pointing to the new
31752 ** child.   Finally, call balance_internal() on the new child
31753 ** to cause it to split.
31754 */
31755 static int balance_deeper(MemPage *pPage){
31756   int rc;             /* Return value from subprocedures */
31757   MemPage *pChild;    /* Pointer to a new child page */
31758   Pgno pgnoChild;     /* Page number of the new child page */
31759   BtShared *pBt;         /* The BTree */
31760   int usableSize;     /* Total usable size of a page */
31761   u8 *data;           /* Content of the parent page */
31762   u8 *cdata;          /* Content of the child page */
31763   int hdr;            /* Offset to page header in parent */
31764   int brk;            /* Offset to content of first cell in parent */
31765
31766   assert( pPage->pParent==0 );
31767   assert( pPage->nOverflow>0 );
31768   pBt = pPage->pBt;
31769   assert( sqlite3_mutex_held(pBt->mutex) );
31770   rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
31771   if( rc ) return rc;
31772   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
31773   usableSize = pBt->usableSize;
31774   data = pPage->aData;
31775   hdr = pPage->hdrOffset;
31776   brk = get2byte(&data[hdr+5]);
31777   cdata = pChild->aData;
31778   memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
31779   memcpy(&cdata[brk], &data[brk], usableSize-brk);
31780   assert( pChild->isInit==0 );
31781   rc = sqlite3BtreeInitPage(pChild, pPage);
31782   if( rc ) goto balancedeeper_out;
31783   memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
31784   pChild->nOverflow = pPage->nOverflow;
31785   if( pChild->nOverflow ){
31786     pChild->nFree = 0;
31787   }
31788   assert( pChild->nCell==pPage->nCell );
31789   zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
31790   put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
31791   TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
31792 #ifndef SQLITE_OMIT_AUTOVACUUM
31793   if( pBt->autoVacuum ){
31794     int i;
31795     rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
31796     if( rc ) goto balancedeeper_out;
31797     for(i=0; i<pChild->nCell; i++){
31798       rc = ptrmapPutOvfl(pChild, i);
31799       if( rc!=SQLITE_OK ){
31800         return rc;
31801       }
31802     }
31803   }
31804 #endif
31805   rc = balance_nonroot(pChild);
31806
31807 balancedeeper_out:
31808   releasePage(pChild);
31809   return rc;
31810 }
31811
31812 /*
31813 ** Decide if the page pPage needs to be balanced.  If balancing is
31814 ** required, call the appropriate balancing routine.
31815 */
31816 static int balance(MemPage *pPage, int insert){
31817   int rc = SQLITE_OK;
31818   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
31819   if( pPage->pParent==0 ){
31820     rc = sqlite3PagerWrite(pPage->pDbPage);
31821     if( rc==SQLITE_OK && pPage->nOverflow>0 ){
31822       rc = balance_deeper(pPage);
31823     }
31824     if( rc==SQLITE_OK && pPage->nCell==0 ){
31825       rc = balance_shallower(pPage);
31826     }
31827   }else{
31828     if( pPage->nOverflow>0 || 
31829         (!insert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
31830       rc = balance_nonroot(pPage);
31831     }
31832   }
31833   return rc;
31834 }
31835
31836 /*
31837 ** This routine checks all cursors that point to table pgnoRoot.
31838 ** If any of those cursors were opened with wrFlag==0 in a different
31839 ** database connection (a database connection that shares the pager
31840 ** cache with the current connection) and that other connection 
31841 ** is not in the ReadUncommmitted state, then this routine returns 
31842 ** SQLITE_LOCKED.
31843 **
31844 ** In addition to checking for read-locks (where a read-lock 
31845 ** means a cursor opened with wrFlag==0) this routine also moves
31846 ** all write cursors so that they are pointing to the 
31847 ** first Cell on the root page.  This is necessary because an insert 
31848 ** or delete might change the number of cells on a page or delete
31849 ** a page entirely and we do not want to leave any cursors 
31850 ** pointing to non-existant pages or cells.
31851 */
31852 static int checkReadLocks(Btree *pBtree, Pgno pgnoRoot, BtCursor *pExclude){
31853   BtCursor *p;
31854   BtShared *pBt = pBtree->pBt;
31855   sqlite3 *db = pBtree->db;
31856   assert( sqlite3BtreeHoldsMutex(pBtree) );
31857   for(p=pBt->pCursor; p; p=p->pNext){
31858     if( p==pExclude ) continue;
31859     if( p->eState!=CURSOR_VALID ) continue;
31860     if( p->pgnoRoot!=pgnoRoot ) continue;
31861     if( p->wrFlag==0 ){
31862       sqlite3 *dbOther = p->pBtree->db;
31863       if( dbOther==0 ||
31864          (dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0) ){
31865         return SQLITE_LOCKED;
31866       }
31867     }else if( p->pPage->pgno!=p->pgnoRoot ){
31868       moveToRoot(p);
31869     }
31870   }
31871   return SQLITE_OK;
31872 }
31873
31874 /*
31875 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
31876 ** and the data is given by (pData,nData).  The cursor is used only to
31877 ** define what table the record should be inserted into.  The cursor
31878 ** is left pointing at a random location.
31879 **
31880 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
31881 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
31882 */
31883 SQLITE_PRIVATE int sqlite3BtreeInsert(
31884   BtCursor *pCur,                /* Insert data into the table of this cursor */
31885   const void *pKey, i64 nKey,    /* The key of the new record */
31886   const void *pData, int nData,  /* The data of the new record */
31887   int nZero,                     /* Number of extra 0 bytes to append to data */
31888   int appendBias                 /* True if this is likely an append */
31889 ){
31890   int rc;
31891   int loc;
31892   int szNew;
31893   MemPage *pPage;
31894   Btree *p = pCur->pBtree;
31895   BtShared *pBt = p->pBt;
31896   unsigned char *oldCell;
31897   unsigned char *newCell = 0;
31898
31899   assert( cursorHoldsMutex(pCur) );
31900   if( pBt->inTransaction!=TRANS_WRITE ){
31901     /* Must start a transaction before doing an insert */
31902     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
31903     return rc;
31904   }
31905   assert( !pBt->readOnly );
31906   if( !pCur->wrFlag ){
31907     return SQLITE_PERM;   /* Cursor not open for writing */
31908   }
31909   if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur) ){
31910     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
31911   }
31912   if( pCur->eState==CURSOR_FAULT ){
31913     return pCur->skip;
31914   }
31915
31916   /* Save the positions of any other cursors open on this table */
31917   clearCursorPosition(pCur);
31918   if( 
31919     SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
31920     SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
31921   ){
31922     return rc;
31923   }
31924
31925   pPage = pCur->pPage;
31926   assert( pPage->intKey || nKey>=0 );
31927   assert( pPage->leaf || !pPage->leafData );
31928   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
31929           pCur->pgnoRoot, nKey, nData, pPage->pgno,
31930           loc==0 ? "overwrite" : "new entry"));
31931   assert( pPage->isInit );
31932   newCell = sqlite3_malloc( MX_CELL_SIZE(pBt) );
31933   if( newCell==0 ) return SQLITE_NOMEM;
31934   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
31935   if( rc ) goto end_insert;
31936   assert( szNew==cellSizePtr(pPage, newCell) );
31937   assert( szNew<=MX_CELL_SIZE(pBt) );
31938   if( loc==0 && CURSOR_VALID==pCur->eState ){
31939     int szOld;
31940     assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
31941     rc = sqlite3PagerWrite(pPage->pDbPage);
31942     if( rc ){
31943       goto end_insert;
31944     }
31945     oldCell = findCell(pPage, pCur->idx);
31946     if( !pPage->leaf ){
31947       memcpy(newCell, oldCell, 4);
31948     }
31949     szOld = cellSizePtr(pPage, oldCell);
31950     rc = clearCell(pPage, oldCell);
31951     if( rc ) goto end_insert;
31952     dropCell(pPage, pCur->idx, szOld);
31953   }else if( loc<0 && pPage->nCell>0 ){
31954     assert( pPage->leaf );
31955     pCur->idx++;
31956     pCur->info.nSize = 0;
31957   }else{
31958     assert( pPage->leaf );
31959   }
31960   rc = insertCell(pPage, pCur->idx, newCell, szNew, 0, 0);
31961   if( rc!=SQLITE_OK ) goto end_insert;
31962   rc = balance(pPage, 1);
31963   /* sqlite3BtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
31964   /* fflush(stdout); */
31965   if( rc==SQLITE_OK ){
31966     moveToRoot(pCur);
31967   }
31968 end_insert:
31969   sqlite3_free(newCell);
31970   return rc;
31971 }
31972
31973 /*
31974 ** Delete the entry that the cursor is pointing to.  The cursor
31975 ** is left pointing at a random location.
31976 */
31977 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
31978   MemPage *pPage = pCur->pPage;
31979   unsigned char *pCell;
31980   int rc;
31981   Pgno pgnoChild = 0;
31982   Btree *p = pCur->pBtree;
31983   BtShared *pBt = p->pBt;
31984
31985   assert( cursorHoldsMutex(pCur) );
31986   assert( pPage->isInit );
31987   if( pBt->inTransaction!=TRANS_WRITE ){
31988     /* Must start a transaction before doing a delete */
31989     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
31990     return rc;
31991   }
31992   assert( !pBt->readOnly );
31993   if( pCur->eState==CURSOR_FAULT ){
31994     return pCur->skip;
31995   }
31996   if( pCur->idx >= pPage->nCell ){
31997     return SQLITE_ERROR;  /* The cursor is not pointing to anything */
31998   }
31999   if( !pCur->wrFlag ){
32000     return SQLITE_PERM;   /* Did not open this cursor for writing */
32001   }
32002   if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur) ){
32003     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
32004   }
32005
32006   /* Restore the current cursor position (a no-op if the cursor is not in 
32007   ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors 
32008   ** open on the same table. Then call sqlite3PagerWrite() on the page
32009   ** that the entry will be deleted from.
32010   */
32011   if( 
32012     (rc = restoreOrClearCursorPosition(pCur))!=0 ||
32013     (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
32014     (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
32015   ){
32016     return rc;
32017   }
32018
32019   /* Locate the cell within its page and leave pCell pointing to the
32020   ** data. The clearCell() call frees any overflow pages associated with the
32021   ** cell. The cell itself is still intact.
32022   */
32023   pCell = findCell(pPage, pCur->idx);
32024   if( !pPage->leaf ){
32025     pgnoChild = get4byte(pCell);
32026   }
32027   rc = clearCell(pPage, pCell);
32028   if( rc ){
32029     return rc;
32030   }
32031
32032   if( !pPage->leaf ){
32033     /*
32034     ** The entry we are about to delete is not a leaf so if we do not
32035     ** do something we will leave a hole on an internal page.
32036     ** We have to fill the hole by moving in a cell from a leaf.  The
32037     ** next Cell after the one to be deleted is guaranteed to exist and
32038     ** to be a leaf so we can use it.
32039     */
32040     BtCursor leafCur;
32041     unsigned char *pNext;
32042     int szNext;  /* The compiler warning is wrong: szNext is always 
32043                  ** initialized before use.  Adding an extra initialization
32044                  ** to silence the compiler slows down the code. */
32045     int notUsed;
32046     unsigned char *tempCell = 0;
32047     assert( !pPage->leafData );
32048     sqlite3BtreeGetTempCursor(pCur, &leafCur);
32049     rc = sqlite3BtreeNext(&leafCur, &notUsed);
32050     if( rc==SQLITE_OK ){
32051       rc = sqlite3PagerWrite(leafCur.pPage->pDbPage);
32052     }
32053     if( rc==SQLITE_OK ){
32054       TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
32055          pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
32056       dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
32057       pNext = findCell(leafCur.pPage, leafCur.idx);
32058       szNext = cellSizePtr(leafCur.pPage, pNext);
32059       assert( MX_CELL_SIZE(pBt)>=szNext+4 );
32060       tempCell = sqlite3_malloc( MX_CELL_SIZE(pBt) );
32061       if( tempCell==0 ){
32062         rc = SQLITE_NOMEM;
32063       }
32064     }
32065     if( rc==SQLITE_OK ){
32066       rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0);
32067     }
32068     if( rc==SQLITE_OK ){
32069       put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
32070       rc = balance(pPage, 0);
32071     }
32072     if( rc==SQLITE_OK ){
32073       dropCell(leafCur.pPage, leafCur.idx, szNext);
32074       rc = balance(leafCur.pPage, 0);
32075     }
32076     sqlite3_free(tempCell);
32077     sqlite3BtreeReleaseTempCursor(&leafCur);
32078   }else{
32079     TRACE(("DELETE: table=%d delete from leaf %d\n",
32080        pCur->pgnoRoot, pPage->pgno));
32081     dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
32082     rc = balance(pPage, 0);
32083   }
32084   if( rc==SQLITE_OK ){
32085     moveToRoot(pCur);
32086   }
32087   return rc;
32088 }
32089
32090 /*
32091 ** Create a new BTree table.  Write into *piTable the page
32092 ** number for the root page of the new table.
32093 **
32094 ** The type of type is determined by the flags parameter.  Only the
32095 ** following values of flags are currently in use.  Other values for
32096 ** flags might not work:
32097 **
32098 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
32099 **     BTREE_ZERODATA                  Used for SQL indices
32100 */
32101 static int btreeCreateTable(Btree *p, int *piTable, int flags){
32102   BtShared *pBt = p->pBt;
32103   MemPage *pRoot;
32104   Pgno pgnoRoot;
32105   int rc;
32106
32107   assert( sqlite3BtreeHoldsMutex(p) );
32108   if( pBt->inTransaction!=TRANS_WRITE ){
32109     /* Must start a transaction first */
32110     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
32111     return rc;
32112   }
32113   assert( !pBt->readOnly );
32114
32115 #ifdef SQLITE_OMIT_AUTOVACUUM
32116   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
32117   if( rc ){
32118     return rc;
32119   }
32120 #else
32121   if( pBt->autoVacuum ){
32122     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
32123     MemPage *pPageMove; /* The page to move to. */
32124
32125     /* Creating a new table may probably require moving an existing database
32126     ** to make room for the new tables root page. In case this page turns
32127     ** out to be an overflow page, delete all overflow page-map caches
32128     ** held by open cursors.
32129     */
32130     invalidateAllOverflowCache(pBt);
32131
32132     /* Read the value of meta[3] from the database to determine where the
32133     ** root page of the new table should go. meta[3] is the largest root-page
32134     ** created so far, so the new root-page is (meta[3]+1).
32135     */
32136     rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
32137     if( rc!=SQLITE_OK ){
32138       return rc;
32139     }
32140     pgnoRoot++;
32141
32142     /* The new root-page may not be allocated on a pointer-map page, or the
32143     ** PENDING_BYTE page.
32144     */
32145     if( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
32146         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
32147       pgnoRoot++;
32148     }
32149     assert( pgnoRoot>=3 );
32150
32151     /* Allocate a page. The page that currently resides at pgnoRoot will
32152     ** be moved to the allocated page (unless the allocated page happens
32153     ** to reside at pgnoRoot).
32154     */
32155     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
32156     if( rc!=SQLITE_OK ){
32157       return rc;
32158     }
32159
32160     if( pgnoMove!=pgnoRoot ){
32161       /* pgnoRoot is the page that will be used for the root-page of
32162       ** the new table (assuming an error did not occur). But we were
32163       ** allocated pgnoMove. If required (i.e. if it was not allocated
32164       ** by extending the file), the current page at position pgnoMove
32165       ** is already journaled.
32166       */
32167       u8 eType;
32168       Pgno iPtrPage;
32169
32170       releasePage(pPageMove);
32171
32172       /* Move the page currently at pgnoRoot to pgnoMove. */
32173       rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
32174       if( rc!=SQLITE_OK ){
32175         return rc;
32176       }
32177       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
32178       if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
32179         releasePage(pRoot);
32180         return rc;
32181       }
32182       assert( eType!=PTRMAP_ROOTPAGE );
32183       assert( eType!=PTRMAP_FREEPAGE );
32184       rc = sqlite3PagerWrite(pRoot->pDbPage);
32185       if( rc!=SQLITE_OK ){
32186         releasePage(pRoot);
32187         return rc;
32188       }
32189       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove);
32190       releasePage(pRoot);
32191
32192       /* Obtain the page at pgnoRoot */
32193       if( rc!=SQLITE_OK ){
32194         return rc;
32195       }
32196       rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
32197       if( rc!=SQLITE_OK ){
32198         return rc;
32199       }
32200       rc = sqlite3PagerWrite(pRoot->pDbPage);
32201       if( rc!=SQLITE_OK ){
32202         releasePage(pRoot);
32203         return rc;
32204       }
32205     }else{
32206       pRoot = pPageMove;
32207     } 
32208
32209     /* Update the pointer-map and meta-data with the new root-page number. */
32210     rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
32211     if( rc ){
32212       releasePage(pRoot);
32213       return rc;
32214     }
32215     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
32216     if( rc ){
32217       releasePage(pRoot);
32218       return rc;
32219     }
32220
32221   }else{
32222     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
32223     if( rc ) return rc;
32224   }
32225 #endif
32226   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
32227   zeroPage(pRoot, flags | PTF_LEAF);
32228   sqlite3PagerUnref(pRoot->pDbPage);
32229   *piTable = (int)pgnoRoot;
32230   return SQLITE_OK;
32231 }
32232 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
32233   int rc;
32234   sqlite3BtreeEnter(p);
32235   p->pBt->db = p->db;
32236   rc = btreeCreateTable(p, piTable, flags);
32237   sqlite3BtreeLeave(p);
32238   return rc;
32239 }
32240
32241 /*
32242 ** Erase the given database page and all its children.  Return
32243 ** the page to the freelist.
32244 */
32245 static int clearDatabasePage(
32246   BtShared *pBt,           /* The BTree that contains the table */
32247   Pgno pgno,            /* Page number to clear */
32248   MemPage *pParent,     /* Parent page.  NULL for the root */
32249   int freePageFlag      /* Deallocate page if true */
32250 ){
32251   MemPage *pPage = 0;
32252   int rc;
32253   unsigned char *pCell;
32254   int i;
32255
32256   assert( sqlite3_mutex_held(pBt->mutex) );
32257   if( pgno>sqlite3PagerPagecount(pBt->pPager) ){
32258     return SQLITE_CORRUPT_BKPT;
32259   }
32260
32261   rc = getAndInitPage(pBt, pgno, &pPage, pParent);
32262   if( rc ) goto cleardatabasepage_out;
32263   for(i=0; i<pPage->nCell; i++){
32264     pCell = findCell(pPage, i);
32265     if( !pPage->leaf ){
32266       rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
32267       if( rc ) goto cleardatabasepage_out;
32268     }
32269     rc = clearCell(pPage, pCell);
32270     if( rc ) goto cleardatabasepage_out;
32271   }
32272   if( !pPage->leaf ){
32273     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
32274     if( rc ) goto cleardatabasepage_out;
32275   }
32276   if( freePageFlag ){
32277     rc = freePage(pPage);
32278   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
32279     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
32280   }
32281
32282 cleardatabasepage_out:
32283   releasePage(pPage);
32284   return rc;
32285 }
32286
32287 /*
32288 ** Delete all information from a single table in the database.  iTable is
32289 ** the page number of the root of the table.  After this routine returns,
32290 ** the root page is empty, but still exists.
32291 **
32292 ** This routine will fail with SQLITE_LOCKED if there are any open
32293 ** read cursors on the table.  Open write cursors are moved to the
32294 ** root of the table.
32295 */
32296 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable){
32297   int rc;
32298   BtShared *pBt = p->pBt;
32299   sqlite3BtreeEnter(p);
32300   pBt->db = p->db;
32301   if( p->inTrans!=TRANS_WRITE ){
32302     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
32303   }else if( (rc = checkReadLocks(p, iTable, 0))!=SQLITE_OK ){
32304     /* nothing to do */
32305   }else if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
32306     /* nothing to do */
32307   }else{
32308     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
32309   }
32310   sqlite3BtreeLeave(p);
32311   return rc;
32312 }
32313
32314 /*
32315 ** Erase all information in a table and add the root of the table to
32316 ** the freelist.  Except, the root of the principle table (the one on
32317 ** page 1) is never added to the freelist.
32318 **
32319 ** This routine will fail with SQLITE_LOCKED if there are any open
32320 ** cursors on the table.
32321 **
32322 ** If AUTOVACUUM is enabled and the page at iTable is not the last
32323 ** root page in the database file, then the last root page 
32324 ** in the database file is moved into the slot formerly occupied by
32325 ** iTable and that last slot formerly occupied by the last root page
32326 ** is added to the freelist instead of iTable.  In this say, all
32327 ** root pages are kept at the beginning of the database file, which
32328 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
32329 ** page number that used to be the last root page in the file before
32330 ** the move.  If no page gets moved, *piMoved is set to 0.
32331 ** The last root page is recorded in meta[3] and the value of
32332 ** meta[3] is updated by this procedure.
32333 */
32334 static int btreeDropTable(Btree *p, int iTable, int *piMoved){
32335   int rc;
32336   MemPage *pPage = 0;
32337   BtShared *pBt = p->pBt;
32338
32339   assert( sqlite3BtreeHoldsMutex(p) );
32340   if( p->inTrans!=TRANS_WRITE ){
32341     return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
32342   }
32343
32344   /* It is illegal to drop a table if any cursors are open on the
32345   ** database. This is because in auto-vacuum mode the backend may
32346   ** need to move another root-page to fill a gap left by the deleted
32347   ** root page. If an open cursor was using this page a problem would 
32348   ** occur.
32349   */
32350   if( pBt->pCursor ){
32351     return SQLITE_LOCKED;
32352   }
32353
32354   rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
32355   if( rc ) return rc;
32356   rc = sqlite3BtreeClearTable(p, iTable);
32357   if( rc ){
32358     releasePage(pPage);
32359     return rc;
32360   }
32361
32362   *piMoved = 0;
32363
32364   if( iTable>1 ){
32365 #ifdef SQLITE_OMIT_AUTOVACUUM
32366     rc = freePage(pPage);
32367     releasePage(pPage);
32368 #else
32369     if( pBt->autoVacuum ){
32370       Pgno maxRootPgno;
32371       rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
32372       if( rc!=SQLITE_OK ){
32373         releasePage(pPage);
32374         return rc;
32375       }
32376
32377       if( iTable==maxRootPgno ){
32378         /* If the table being dropped is the table with the largest root-page
32379         ** number in the database, put the root page on the free list. 
32380         */
32381         rc = freePage(pPage);
32382         releasePage(pPage);
32383         if( rc!=SQLITE_OK ){
32384           return rc;
32385         }
32386       }else{
32387         /* The table being dropped does not have the largest root-page
32388         ** number in the database. So move the page that does into the 
32389         ** gap left by the deleted root-page.
32390         */
32391         MemPage *pMove;
32392         releasePage(pPage);
32393         rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
32394         if( rc!=SQLITE_OK ){
32395           return rc;
32396         }
32397         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable);
32398         releasePage(pMove);
32399         if( rc!=SQLITE_OK ){
32400           return rc;
32401         }
32402         rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
32403         if( rc!=SQLITE_OK ){
32404           return rc;
32405         }
32406         rc = freePage(pMove);
32407         releasePage(pMove);
32408         if( rc!=SQLITE_OK ){
32409           return rc;
32410         }
32411         *piMoved = maxRootPgno;
32412       }
32413
32414       /* Set the new 'max-root-page' value in the database header. This
32415       ** is the old value less one, less one more if that happens to
32416       ** be a root-page number, less one again if that is the
32417       ** PENDING_BYTE_PAGE.
32418       */
32419       maxRootPgno--;
32420       if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
32421         maxRootPgno--;
32422       }
32423       if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
32424         maxRootPgno--;
32425       }
32426       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
32427
32428       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
32429     }else{
32430       rc = freePage(pPage);
32431       releasePage(pPage);
32432     }
32433 #endif
32434   }else{
32435     /* If sqlite3BtreeDropTable was called on page 1. */
32436     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
32437     releasePage(pPage);
32438   }
32439   return rc;  
32440 }
32441 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
32442   int rc;
32443   sqlite3BtreeEnter(p);
32444   p->pBt->db = p->db;
32445   rc = btreeDropTable(p, iTable, piMoved);
32446   sqlite3BtreeLeave(p);
32447   return rc;
32448 }
32449
32450
32451 /*
32452 ** Read the meta-information out of a database file.  Meta[0]
32453 ** is the number of free pages currently in the database.  Meta[1]
32454 ** through meta[15] are available for use by higher layers.  Meta[0]
32455 ** is read-only, the others are read/write.
32456 ** 
32457 ** The schema layer numbers meta values differently.  At the schema
32458 ** layer (and the SetCookie and ReadCookie opcodes) the number of
32459 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
32460 */
32461 SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
32462   DbPage *pDbPage;
32463   int rc;
32464   unsigned char *pP1;
32465   BtShared *pBt = p->pBt;
32466
32467   sqlite3BtreeEnter(p);
32468   pBt->db = p->db;
32469
32470   /* Reading a meta-data value requires a read-lock on page 1 (and hence
32471   ** the sqlite_master table. We grab this lock regardless of whether or
32472   ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
32473   ** 1 is treated as a special case by queryTableLock() and lockTable()).
32474   */
32475   rc = queryTableLock(p, 1, READ_LOCK);
32476   if( rc!=SQLITE_OK ){
32477     sqlite3BtreeLeave(p);
32478     return rc;
32479   }
32480
32481   assert( idx>=0 && idx<=15 );
32482   rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
32483   if( rc ){
32484     sqlite3BtreeLeave(p);
32485     return rc;
32486   }
32487   pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
32488   *pMeta = get4byte(&pP1[36 + idx*4]);
32489   sqlite3PagerUnref(pDbPage);
32490
32491   /* If autovacuumed is disabled in this build but we are trying to 
32492   ** access an autovacuumed database, then make the database readonly. 
32493   */
32494 #ifdef SQLITE_OMIT_AUTOVACUUM
32495   if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
32496 #endif
32497
32498   /* Grab the read-lock on page 1. */
32499   rc = lockTable(p, 1, READ_LOCK);
32500   sqlite3BtreeLeave(p);
32501   return rc;
32502 }
32503
32504 /*
32505 ** Write meta-information back into the database.  Meta[0] is
32506 ** read-only and may not be written.
32507 */
32508 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
32509   BtShared *pBt = p->pBt;
32510   unsigned char *pP1;
32511   int rc;
32512   assert( idx>=1 && idx<=15 );
32513   sqlite3BtreeEnter(p);
32514   pBt->db = p->db;
32515   if( p->inTrans!=TRANS_WRITE ){
32516     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
32517   }else{
32518     assert( pBt->pPage1!=0 );
32519     pP1 = pBt->pPage1->aData;
32520     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
32521     if( rc==SQLITE_OK ){
32522       put4byte(&pP1[36 + idx*4], iMeta);
32523 #ifndef SQLITE_OMIT_AUTOVACUUM
32524       if( idx==7 ){
32525         assert( pBt->autoVacuum || iMeta==0 );
32526         assert( iMeta==0 || iMeta==1 );
32527         pBt->incrVacuum = iMeta;
32528       }
32529 #endif
32530     }
32531   }
32532   sqlite3BtreeLeave(p);
32533   return rc;
32534 }
32535
32536 /*
32537 ** Return the flag byte at the beginning of the page that the cursor
32538 ** is currently pointing to.
32539 */
32540 SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor *pCur){
32541   /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
32542   ** restoreOrClearCursorPosition() here.
32543   */
32544   MemPage *pPage = pCur->pPage;
32545   assert( cursorHoldsMutex(pCur) );
32546   assert( pPage->pBt==pCur->pBt );
32547   return pPage ? pPage->aData[pPage->hdrOffset] : 0;
32548 }
32549
32550
32551 /*
32552 ** Return the pager associated with a BTree.  This routine is used for
32553 ** testing and debugging only.
32554 */
32555 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
32556   return p->pBt->pPager;
32557 }
32558
32559 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
32560 /*
32561 ** Append a message to the error message string.
32562 */
32563 static void checkAppendMsg(
32564   IntegrityCk *pCheck,
32565   char *zMsg1,
32566   const char *zFormat,
32567   ...
32568 ){
32569   va_list ap;
32570   char *zMsg2;
32571   if( !pCheck->mxErr ) return;
32572   pCheck->mxErr--;
32573   pCheck->nErr++;
32574   va_start(ap, zFormat);
32575   zMsg2 = sqlite3VMPrintf(0, zFormat, ap);
32576   va_end(ap);
32577   if( zMsg1==0 ) zMsg1 = "";
32578   if( pCheck->zErrMsg ){
32579     char *zOld = pCheck->zErrMsg;
32580     pCheck->zErrMsg = 0;
32581     sqlite3SetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
32582     sqlite3_free(zOld);
32583   }else{
32584     sqlite3SetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
32585   }
32586   sqlite3_free(zMsg2);
32587 }
32588 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
32589
32590 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
32591 /*
32592 ** Add 1 to the reference count for page iPage.  If this is the second
32593 ** reference to the page, add an error message to pCheck->zErrMsg.
32594 ** Return 1 if there are 2 ore more references to the page and 0 if
32595 ** if this is the first reference to the page.
32596 **
32597 ** Also check that the page number is in bounds.
32598 */
32599 static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
32600   if( iPage==0 ) return 1;
32601   if( iPage>pCheck->nPage || iPage<0 ){
32602     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
32603     return 1;
32604   }
32605   if( pCheck->anRef[iPage]==1 ){
32606     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
32607     return 1;
32608   }
32609   return  (pCheck->anRef[iPage]++)>1;
32610 }
32611
32612 #ifndef SQLITE_OMIT_AUTOVACUUM
32613 /*
32614 ** Check that the entry in the pointer-map for page iChild maps to 
32615 ** page iParent, pointer type ptrType. If not, append an error message
32616 ** to pCheck.
32617 */
32618 static void checkPtrmap(
32619   IntegrityCk *pCheck,   /* Integrity check context */
32620   Pgno iChild,           /* Child page number */
32621   u8 eType,              /* Expected pointer map type */
32622   Pgno iParent,          /* Expected pointer map parent page number */
32623   char *zContext         /* Context description (used for error msg) */
32624 ){
32625   int rc;
32626   u8 ePtrmapType;
32627   Pgno iPtrmapParent;
32628
32629   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
32630   if( rc!=SQLITE_OK ){
32631     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
32632     return;
32633   }
32634
32635   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
32636     checkAppendMsg(pCheck, zContext, 
32637       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
32638       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
32639   }
32640 }
32641 #endif
32642
32643 /*
32644 ** Check the integrity of the freelist or of an overflow page list.
32645 ** Verify that the number of pages on the list is N.
32646 */
32647 static void checkList(
32648   IntegrityCk *pCheck,  /* Integrity checking context */
32649   int isFreeList,       /* True for a freelist.  False for overflow page list */
32650   int iPage,            /* Page number for first page in the list */
32651   int N,                /* Expected number of pages in the list */
32652   char *zContext        /* Context for error messages */
32653 ){
32654   int i;
32655   int expected = N;
32656   int iFirst = iPage;
32657   while( N-- > 0 && pCheck->mxErr ){
32658     DbPage *pOvflPage;
32659     unsigned char *pOvflData;
32660     if( iPage<1 ){
32661       checkAppendMsg(pCheck, zContext,
32662          "%d of %d pages missing from overflow list starting at %d",
32663           N+1, expected, iFirst);
32664       break;
32665     }
32666     if( checkRef(pCheck, iPage, zContext) ) break;
32667     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
32668       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
32669       break;
32670     }
32671     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
32672     if( isFreeList ){
32673       int n = get4byte(&pOvflData[4]);
32674 #ifndef SQLITE_OMIT_AUTOVACUUM
32675       if( pCheck->pBt->autoVacuum ){
32676         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
32677       }
32678 #endif
32679       if( n>pCheck->pBt->usableSize/4-8 ){
32680         checkAppendMsg(pCheck, zContext,
32681            "freelist leaf count too big on page %d", iPage);
32682         N--;
32683       }else{
32684         for(i=0; i<n; i++){
32685           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
32686 #ifndef SQLITE_OMIT_AUTOVACUUM
32687           if( pCheck->pBt->autoVacuum ){
32688             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
32689           }
32690 #endif
32691           checkRef(pCheck, iFreePage, zContext);
32692         }
32693         N -= n;
32694       }
32695     }
32696 #ifndef SQLITE_OMIT_AUTOVACUUM
32697     else{
32698       /* If this database supports auto-vacuum and iPage is not the last
32699       ** page in this overflow list, check that the pointer-map entry for
32700       ** the following page matches iPage.
32701       */
32702       if( pCheck->pBt->autoVacuum && N>0 ){
32703         i = get4byte(pOvflData);
32704         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
32705       }
32706     }
32707 #endif
32708     iPage = get4byte(pOvflData);
32709     sqlite3PagerUnref(pOvflPage);
32710   }
32711 }
32712 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
32713
32714 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
32715 /*
32716 ** Do various sanity checks on a single page of a tree.  Return
32717 ** the tree depth.  Root pages return 0.  Parents of root pages
32718 ** return 1, and so forth.
32719 ** 
32720 ** These checks are done:
32721 **
32722 **      1.  Make sure that cells and freeblocks do not overlap
32723 **          but combine to completely cover the page.
32724 **  NO  2.  Make sure cell keys are in order.
32725 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
32726 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
32727 **      5.  Check the integrity of overflow pages.
32728 **      6.  Recursively call checkTreePage on all children.
32729 **      7.  Verify that the depth of all children is the same.
32730 **      8.  Make sure this page is at least 33% full or else it is
32731 **          the root of the tree.
32732 */
32733 static int checkTreePage(
32734   IntegrityCk *pCheck,  /* Context for the sanity check */
32735   int iPage,            /* Page number of the page to check */
32736   MemPage *pParent,     /* Parent page */
32737   char *zParentContext  /* Parent context */
32738 ){
32739   MemPage *pPage;
32740   int i, rc, depth, d2, pgno, cnt;
32741   int hdr, cellStart;
32742   int nCell;
32743   u8 *data;
32744   BtShared *pBt;
32745   int usableSize;
32746   char zContext[100];
32747   char *hit;
32748
32749   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
32750
32751   /* Check that the page exists
32752   */
32753   pBt = pCheck->pBt;
32754   usableSize = pBt->usableSize;
32755   if( iPage==0 ) return 0;
32756   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
32757   if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
32758     checkAppendMsg(pCheck, zContext,
32759        "unable to get the page. error code=%d", rc);
32760     return 0;
32761   }
32762   if( (rc = sqlite3BtreeInitPage(pPage, pParent))!=0 ){
32763     checkAppendMsg(pCheck, zContext, 
32764                    "sqlite3BtreeInitPage() returns error code %d", rc);
32765     releasePage(pPage);
32766     return 0;
32767   }
32768
32769   /* Check out all the cells.
32770   */
32771   depth = 0;
32772   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
32773     u8 *pCell;
32774     int sz;
32775     CellInfo info;
32776
32777     /* Check payload overflow pages
32778     */
32779     sqlite3_snprintf(sizeof(zContext), zContext,
32780              "On tree page %d cell %d: ", iPage, i);
32781     pCell = findCell(pPage,i);
32782     sqlite3BtreeParseCellPtr(pPage, pCell, &info);
32783     sz = info.nData;
32784     if( !pPage->intKey ) sz += info.nKey;
32785     assert( sz==info.nPayload );
32786     if( sz>info.nLocal ){
32787       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
32788       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
32789 #ifndef SQLITE_OMIT_AUTOVACUUM
32790       if( pBt->autoVacuum ){
32791         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
32792       }
32793 #endif
32794       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
32795     }
32796
32797     /* Check sanity of left child page.
32798     */
32799     if( !pPage->leaf ){
32800       pgno = get4byte(pCell);
32801 #ifndef SQLITE_OMIT_AUTOVACUUM
32802       if( pBt->autoVacuum ){
32803         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
32804       }
32805 #endif
32806       d2 = checkTreePage(pCheck,pgno,pPage,zContext);
32807       if( i>0 && d2!=depth ){
32808         checkAppendMsg(pCheck, zContext, "Child page depth differs");
32809       }
32810       depth = d2;
32811     }
32812   }
32813   if( !pPage->leaf ){
32814     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
32815     sqlite3_snprintf(sizeof(zContext), zContext, 
32816                      "On page %d at right child: ", iPage);
32817 #ifndef SQLITE_OMIT_AUTOVACUUM
32818     if( pBt->autoVacuum ){
32819       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
32820     }
32821 #endif
32822     checkTreePage(pCheck, pgno, pPage, zContext);
32823   }
32824  
32825   /* Check for complete coverage of the page
32826   */
32827   data = pPage->aData;
32828   hdr = pPage->hdrOffset;
32829   hit = sqlite3MallocZero( usableSize );
32830   if( hit ){
32831     memset(hit, 1, get2byte(&data[hdr+5]));
32832     nCell = get2byte(&data[hdr+3]);
32833     cellStart = hdr + 12 - 4*pPage->leaf;
32834     for(i=0; i<nCell; i++){
32835       int pc = get2byte(&data[cellStart+i*2]);
32836       int size = cellSizePtr(pPage, &data[pc]);
32837       int j;
32838       if( (pc+size-1)>=usableSize || pc<0 ){
32839         checkAppendMsg(pCheck, 0, 
32840             "Corruption detected in cell %d on page %d",i,iPage,0);
32841       }else{
32842         for(j=pc+size-1; j>=pc; j--) hit[j]++;
32843       }
32844     }
32845     for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000; 
32846            cnt++){
32847       int size = get2byte(&data[i+2]);
32848       int j;
32849       if( (i+size-1)>=usableSize || i<0 ){
32850         checkAppendMsg(pCheck, 0,  
32851             "Corruption detected in cell %d on page %d",i,iPage,0);
32852       }else{
32853         for(j=i+size-1; j>=i; j--) hit[j]++;
32854       }
32855       i = get2byte(&data[i]);
32856     }
32857     for(i=cnt=0; i<usableSize; i++){
32858       if( hit[i]==0 ){
32859         cnt++;
32860       }else if( hit[i]>1 ){
32861         checkAppendMsg(pCheck, 0,
32862           "Multiple uses for byte %d of page %d", i, iPage);
32863         break;
32864       }
32865     }
32866     if( cnt!=data[hdr+7] ){
32867       checkAppendMsg(pCheck, 0, 
32868           "Fragmented space is %d byte reported as %d on page %d",
32869           cnt, data[hdr+7], iPage);
32870     }
32871   }
32872   sqlite3_free(hit);
32873
32874   releasePage(pPage);
32875   return depth+1;
32876 }
32877 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
32878
32879 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
32880 /*
32881 ** This routine does a complete check of the given BTree file.  aRoot[] is
32882 ** an array of pages numbers were each page number is the root page of
32883 ** a table.  nRoot is the number of entries in aRoot.
32884 **
32885 ** If everything checks out, this routine returns NULL.  If something is
32886 ** amiss, an error message is written into memory obtained from malloc()
32887 ** and a pointer to that error message is returned.  The calling function
32888 ** is responsible for freeing the error message when it is done.
32889 */
32890 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
32891   Btree *p,     /* The btree to be checked */
32892   int *aRoot,   /* An array of root pages numbers for individual trees */
32893   int nRoot,    /* Number of entries in aRoot[] */
32894   int mxErr,    /* Stop reporting errors after this many */
32895   int *pnErr    /* Write number of errors seen to this variable */
32896 ){
32897   int i;
32898   int nRef;
32899   IntegrityCk sCheck;
32900   BtShared *pBt = p->pBt;
32901
32902   sqlite3BtreeEnter(p);
32903   pBt->db = p->db;
32904   nRef = sqlite3PagerRefcount(pBt->pPager);
32905   if( lockBtreeWithRetry(p)!=SQLITE_OK ){
32906     sqlite3BtreeLeave(p);
32907     return sqlite3StrDup("Unable to acquire a read lock on the database");
32908   }
32909   sCheck.pBt = pBt;
32910   sCheck.pPager = pBt->pPager;
32911   sCheck.nPage = sqlite3PagerPagecount(sCheck.pPager);
32912   sCheck.mxErr = mxErr;
32913   sCheck.nErr = 0;
32914   *pnErr = 0;
32915 #ifndef SQLITE_OMIT_AUTOVACUUM
32916   if( pBt->nTrunc!=0 ){
32917     sCheck.nPage = pBt->nTrunc;
32918   }
32919 #endif
32920   if( sCheck.nPage==0 ){
32921     unlockBtreeIfUnused(pBt);
32922     sqlite3BtreeLeave(p);
32923     return 0;
32924   }
32925   sCheck.anRef = sqlite3_malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
32926   if( !sCheck.anRef ){
32927     unlockBtreeIfUnused(pBt);
32928     *pnErr = 1;
32929     sqlite3BtreeLeave(p);
32930     return sqlite3MPrintf(p->db, "Unable to malloc %d bytes", 
32931         (sCheck.nPage+1)*sizeof(sCheck.anRef[0]));
32932   }
32933   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
32934   i = PENDING_BYTE_PAGE(pBt);
32935   if( i<=sCheck.nPage ){
32936     sCheck.anRef[i] = 1;
32937   }
32938   sCheck.zErrMsg = 0;
32939
32940   /* Check the integrity of the freelist
32941   */
32942   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
32943             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
32944
32945   /* Check all the tables.
32946   */
32947   for(i=0; i<nRoot && sCheck.mxErr; i++){
32948     if( aRoot[i]==0 ) continue;
32949 #ifndef SQLITE_OMIT_AUTOVACUUM
32950     if( pBt->autoVacuum && aRoot[i]>1 ){
32951       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
32952     }
32953 #endif
32954     checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ");
32955   }
32956
32957   /* Make sure every page in the file is referenced
32958   */
32959   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
32960 #ifdef SQLITE_OMIT_AUTOVACUUM
32961     if( sCheck.anRef[i]==0 ){
32962       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
32963     }
32964 #else
32965     /* If the database supports auto-vacuum, make sure no tables contain
32966     ** references to pointer-map pages.
32967     */
32968     if( sCheck.anRef[i]==0 && 
32969        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
32970       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
32971     }
32972     if( sCheck.anRef[i]!=0 && 
32973        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
32974       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
32975     }
32976 #endif
32977   }
32978
32979   /* Make sure this analysis did not leave any unref() pages
32980   */
32981   unlockBtreeIfUnused(pBt);
32982   if( nRef != sqlite3PagerRefcount(pBt->pPager) ){
32983     checkAppendMsg(&sCheck, 0, 
32984       "Outstanding page count goes from %d to %d during this analysis",
32985       nRef, sqlite3PagerRefcount(pBt->pPager)
32986     );
32987   }
32988
32989   /* Clean  up and report errors.
32990   */
32991   sqlite3BtreeLeave(p);
32992   sqlite3_free(sCheck.anRef);
32993   *pnErr = sCheck.nErr;
32994   return sCheck.zErrMsg;
32995 }
32996 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
32997
32998 /*
32999 ** Return the full pathname of the underlying database file.
33000 **
33001 ** The pager filename is invariant as long as the pager is
33002 ** open so it is safe to access without the BtShared mutex.
33003 */
33004 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
33005   assert( p->pBt->pPager!=0 );
33006   return sqlite3PagerFilename(p->pBt->pPager);
33007 }
33008
33009 /*
33010 ** Return the pathname of the directory that contains the database file.
33011 **
33012 ** The pager directory name is invariant as long as the pager is
33013 ** open so it is safe to access without the BtShared mutex.
33014 */
33015 SQLITE_PRIVATE const char *sqlite3BtreeGetDirname(Btree *p){
33016   assert( p->pBt->pPager!=0 );
33017   return sqlite3PagerDirname(p->pBt->pPager);
33018 }
33019
33020 /*
33021 ** Return the pathname of the journal file for this database. The return
33022 ** value of this routine is the same regardless of whether the journal file
33023 ** has been created or not.
33024 **
33025 ** The pager journal filename is invariant as long as the pager is
33026 ** open so it is safe to access without the BtShared mutex.
33027 */
33028 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
33029   assert( p->pBt->pPager!=0 );
33030   return sqlite3PagerJournalname(p->pBt->pPager);
33031 }
33032
33033 #ifndef SQLITE_OMIT_VACUUM
33034 /*
33035 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
33036 ** must be active for both files.
33037 **
33038 ** The size of file pBtFrom may be reduced by this operation.
33039 ** If anything goes wrong, the transaction on pBtFrom is rolled back.
33040 */
33041 static int btreeCopyFile(Btree *pTo, Btree *pFrom){
33042   int rc = SQLITE_OK;
33043   Pgno i, nPage, nToPage, iSkip;
33044
33045   BtShared *pBtTo = pTo->pBt;
33046   BtShared *pBtFrom = pFrom->pBt;
33047   pBtTo->db = pTo->db;
33048   pBtFrom->db = pFrom->db;
33049   
33050
33051   if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
33052     return SQLITE_ERROR;
33053   }
33054   if( pBtTo->pCursor ) return SQLITE_BUSY;
33055   nToPage = sqlite3PagerPagecount(pBtTo->pPager);
33056   nPage = sqlite3PagerPagecount(pBtFrom->pPager);
33057   iSkip = PENDING_BYTE_PAGE(pBtTo);
33058   for(i=1; rc==SQLITE_OK && i<=nPage; i++){
33059     DbPage *pDbPage;
33060     if( i==iSkip ) continue;
33061     rc = sqlite3PagerGet(pBtFrom->pPager, i, &pDbPage);
33062     if( rc ) break;
33063     rc = sqlite3PagerOverwrite(pBtTo->pPager, i, sqlite3PagerGetData(pDbPage));
33064     sqlite3PagerUnref(pDbPage);
33065   }
33066
33067   /* If the file is shrinking, journal the pages that are being truncated
33068   ** so that they can be rolled back if the commit fails.
33069   */
33070   for(i=nPage+1; rc==SQLITE_OK && i<=nToPage; i++){
33071     DbPage *pDbPage;
33072     if( i==iSkip ) continue;
33073     rc = sqlite3PagerGet(pBtTo->pPager, i, &pDbPage);
33074     if( rc ) break;
33075     rc = sqlite3PagerWrite(pDbPage);
33076     sqlite3PagerDontWrite(pDbPage);
33077     /* Yeah.  It seems wierd to call DontWrite() right after Write().  But
33078     ** that is because the names of those procedures do not exactly 
33079     ** represent what they do.  Write() really means "put this page in the
33080     ** rollback journal and mark it as dirty so that it will be written
33081     ** to the database file later."  DontWrite() undoes the second part of
33082     ** that and prevents the page from being written to the database.  The
33083     ** page is still on the rollback journal, though.  And that is the whole
33084     ** point of this loop: to put pages on the rollback journal. */
33085     sqlite3PagerUnref(pDbPage);
33086   }
33087   if( !rc && nPage<nToPage ){
33088     rc = sqlite3PagerTruncate(pBtTo->pPager, nPage);
33089   }
33090
33091   if( rc ){
33092     sqlite3BtreeRollback(pTo);
33093   }
33094   return rc;  
33095 }
33096 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
33097   int rc;
33098   sqlite3BtreeEnter(pTo);
33099   sqlite3BtreeEnter(pFrom);
33100   rc = btreeCopyFile(pTo, pFrom);
33101   sqlite3BtreeLeave(pFrom);
33102   sqlite3BtreeLeave(pTo);
33103   return rc;
33104 }
33105
33106 #endif /* SQLITE_OMIT_VACUUM */
33107
33108 /*
33109 ** Return non-zero if a transaction is active.
33110 */
33111 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
33112   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
33113   return (p && (p->inTrans==TRANS_WRITE));
33114 }
33115
33116 /*
33117 ** Return non-zero if a statement transaction is active.
33118 */
33119 SQLITE_PRIVATE int sqlite3BtreeIsInStmt(Btree *p){
33120   assert( sqlite3BtreeHoldsMutex(p) );
33121   return (p->pBt && p->pBt->inStmt);
33122 }
33123
33124 /*
33125 ** Return non-zero if a read (or write) transaction is active.
33126 */
33127 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
33128   assert( sqlite3_mutex_held(p->db->mutex) );
33129   return (p && (p->inTrans!=TRANS_NONE));
33130 }
33131
33132 /*
33133 ** This function returns a pointer to a blob of memory associated with
33134 ** a single shared-btree. The memory is used by client code for its own
33135 ** purposes (for example, to store a high-level schema associated with 
33136 ** the shared-btree). The btree layer manages reference counting issues.
33137 **
33138 ** The first time this is called on a shared-btree, nBytes bytes of memory
33139 ** are allocated, zeroed, and returned to the caller. For each subsequent 
33140 ** call the nBytes parameter is ignored and a pointer to the same blob
33141 ** of memory returned. 
33142 **
33143 ** Just before the shared-btree is closed, the function passed as the 
33144 ** xFree argument when the memory allocation was made is invoked on the 
33145 ** blob of allocated memory. This function should not call sqlite3_free()
33146 ** on the memory, the btree layer does that.
33147 */
33148 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
33149   BtShared *pBt = p->pBt;
33150   sqlite3BtreeEnter(p);
33151   if( !pBt->pSchema ){
33152     pBt->pSchema = sqlite3MallocZero(nBytes);
33153     pBt->xFreeSchema = xFree;
33154   }
33155   sqlite3BtreeLeave(p);
33156   return pBt->pSchema;
33157 }
33158
33159 /*
33160 ** Return true if another user of the same shared btree as the argument
33161 ** handle holds an exclusive lock on the sqlite_master table.
33162 */
33163 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
33164   int rc;
33165   assert( sqlite3_mutex_held(p->db->mutex) );
33166   sqlite3BtreeEnter(p);
33167   rc = (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
33168   sqlite3BtreeLeave(p);
33169   return rc;
33170 }
33171
33172
33173 #ifndef SQLITE_OMIT_SHARED_CACHE
33174 /*
33175 ** Obtain a lock on the table whose root page is iTab.  The
33176 ** lock is a write lock if isWritelock is true or a read lock
33177 ** if it is false.
33178 */
33179 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
33180   int rc = SQLITE_OK;
33181   u8 lockType = (isWriteLock?WRITE_LOCK:READ_LOCK);
33182   sqlite3BtreeEnter(p);
33183   rc = queryTableLock(p, iTab, lockType);
33184   if( rc==SQLITE_OK ){
33185     rc = lockTable(p, iTab, lockType);
33186   }
33187   sqlite3BtreeLeave(p);
33188   return rc;
33189 }
33190 #endif
33191
33192 #ifndef SQLITE_OMIT_INCRBLOB
33193 /*
33194 ** Argument pCsr must be a cursor opened for writing on an 
33195 ** INTKEY table currently pointing at a valid table entry. 
33196 ** This function modifies the data stored as part of that entry.
33197 ** Only the data content may only be modified, it is not possible
33198 ** to change the length of the data stored.
33199 */
33200 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
33201   assert( cursorHoldsMutex(pCsr) );
33202   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
33203   assert(pCsr->isIncrblobHandle);
33204   if( pCsr->eState>=CURSOR_REQUIRESEEK ){
33205     if( pCsr->eState==CURSOR_FAULT ){
33206       return pCsr->skip;
33207     }else{
33208       return SQLITE_ABORT;
33209     }
33210   }
33211
33212   /* Check some preconditions: 
33213   **   (a) the cursor is open for writing,
33214   **   (b) there is no read-lock on the table being modified and
33215   **   (c) the cursor points at a valid row of an intKey table.
33216   */
33217   if( !pCsr->wrFlag ){
33218     return SQLITE_READONLY;
33219   }
33220   assert( !pCsr->pBt->readOnly 
33221           && pCsr->pBt->inTransaction==TRANS_WRITE );
33222   if( checkReadLocks(pCsr->pBtree, pCsr->pgnoRoot, pCsr) ){
33223     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
33224   }
33225   if( pCsr->eState==CURSOR_INVALID || !pCsr->pPage->intKey ){
33226     return SQLITE_ERROR;
33227   }
33228
33229   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
33230 }
33231
33232 /* 
33233 ** Set a flag on this cursor to cache the locations of pages from the 
33234 ** overflow list for the current row. This is used by cursors opened
33235 ** for incremental blob IO only.
33236 **
33237 ** This function sets a flag only. The actual page location cache
33238 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
33239 ** accessPayload() (the worker function for sqlite3BtreeData() and
33240 ** sqlite3BtreePutData()).
33241 */
33242 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
33243   assert( cursorHoldsMutex(pCur) );
33244   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
33245   assert(!pCur->isIncrblobHandle);
33246   assert(!pCur->aOverflow);
33247   pCur->isIncrblobHandle = 1;
33248 }
33249 #endif
33250
33251 /************** End of btree.c ***********************************************/
33252 /************** Begin file vdbefifo.c ****************************************/
33253 /*
33254 ** 2005 June 16
33255 **
33256 ** The author disclaims copyright to this source code.  In place of
33257 ** a legal notice, here is a blessing:
33258 **
33259 **    May you do good and not evil.
33260 **    May you find forgiveness for yourself and forgive others.
33261 **    May you share freely, never taking more than you give.
33262 **
33263 *************************************************************************
33264 ** This file implements a FIFO queue of rowids used for processing
33265 ** UPDATE and DELETE statements.
33266 */
33267
33268 /*
33269 ** Allocate a new FifoPage and return a pointer to it.  Return NULL if
33270 ** we run out of memory.  Leave space on the page for nEntry entries.
33271 */
33272 static FifoPage *allocateFifoPage(int nEntry){
33273   FifoPage *pPage;
33274   if( nEntry>32767 ){
33275     nEntry = 32767;
33276   }
33277   pPage = sqlite3_malloc( sizeof(FifoPage) + sizeof(i64)*(nEntry-1) );
33278   if( pPage ){
33279     pPage->nSlot = nEntry;
33280     pPage->iWrite = 0;
33281     pPage->iRead = 0;
33282     pPage->pNext = 0;
33283   }
33284   return pPage;
33285 }
33286
33287 /*
33288 ** Initialize a Fifo structure.
33289 */
33290 SQLITE_PRIVATE void sqlite3VdbeFifoInit(Fifo *pFifo){
33291   memset(pFifo, 0, sizeof(*pFifo));
33292 }
33293
33294 /*
33295 ** Push a single 64-bit integer value into the Fifo.  Return SQLITE_OK
33296 ** normally.   SQLITE_NOMEM is returned if we are unable to allocate
33297 ** memory.
33298 */
33299 SQLITE_PRIVATE int sqlite3VdbeFifoPush(Fifo *pFifo, i64 val){
33300   FifoPage *pPage;
33301   pPage = pFifo->pLast;
33302   if( pPage==0 ){
33303     pPage = pFifo->pLast = pFifo->pFirst = allocateFifoPage(20);
33304     if( pPage==0 ){
33305       return SQLITE_NOMEM;
33306     }
33307   }else if( pPage->iWrite>=pPage->nSlot ){
33308     pPage->pNext = allocateFifoPage(pFifo->nEntry);
33309     if( pPage->pNext==0 ){
33310       return SQLITE_NOMEM;
33311     }
33312     pPage = pFifo->pLast = pPage->pNext;
33313   }
33314   pPage->aSlot[pPage->iWrite++] = val;
33315   pFifo->nEntry++;
33316   return SQLITE_OK;
33317 }
33318
33319 /*
33320 ** Extract a single 64-bit integer value from the Fifo.  The integer
33321 ** extracted is the one least recently inserted.  If the Fifo is empty
33322 ** return SQLITE_DONE.
33323 */
33324 SQLITE_PRIVATE int sqlite3VdbeFifoPop(Fifo *pFifo, i64 *pVal){
33325   FifoPage *pPage;
33326   if( pFifo->nEntry==0 ){
33327     return SQLITE_DONE;
33328   }
33329   assert( pFifo->nEntry>0 );
33330   pPage = pFifo->pFirst;
33331   assert( pPage!=0 );
33332   assert( pPage->iWrite>pPage->iRead );
33333   assert( pPage->iWrite<=pPage->nSlot );
33334   assert( pPage->iRead<pPage->nSlot );
33335   assert( pPage->iRead>=0 );
33336   *pVal = pPage->aSlot[pPage->iRead++];
33337   pFifo->nEntry--;
33338   if( pPage->iRead>=pPage->iWrite ){
33339     pFifo->pFirst = pPage->pNext;
33340     sqlite3_free(pPage);
33341     if( pFifo->nEntry==0 ){
33342       assert( pFifo->pLast==pPage );
33343       pFifo->pLast = 0;
33344     }else{
33345       assert( pFifo->pFirst!=0 );
33346     }
33347   }else{
33348     assert( pFifo->nEntry>0 );
33349   }
33350   return SQLITE_OK;
33351 }
33352
33353 /*
33354 ** Delete all information from a Fifo object.   Free all memory held
33355 ** by the Fifo.
33356 */
33357 SQLITE_PRIVATE void sqlite3VdbeFifoClear(Fifo *pFifo){
33358   FifoPage *pPage, *pNextPage;
33359   for(pPage=pFifo->pFirst; pPage; pPage=pNextPage){
33360     pNextPage = pPage->pNext;
33361     sqlite3_free(pPage);
33362   }
33363   sqlite3VdbeFifoInit(pFifo);
33364 }
33365
33366 /************** End of vdbefifo.c ********************************************/
33367 /************** Begin file vdbemem.c *****************************************/
33368 /*
33369 ** 2004 May 26
33370 **
33371 ** The author disclaims copyright to this source code.  In place of
33372 ** a legal notice, here is a blessing:
33373 **
33374 **    May you do good and not evil.
33375 **    May you find forgiveness for yourself and forgive others.
33376 **    May you share freely, never taking more than you give.
33377 **
33378 *************************************************************************
33379 **
33380 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
33381 ** stores a single value in the VDBE.  Mem is an opaque structure visible
33382 ** only within the VDBE.  Interface routines refer to a Mem using the
33383 ** name sqlite_value
33384 */
33385
33386 /*
33387 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
33388 ** P if required.
33389 */
33390 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
33391
33392 /*
33393 ** If pMem is an object with a valid string representation, this routine
33394 ** ensures the internal encoding for the string representation is
33395 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
33396 **
33397 ** If pMem is not a string object, or the encoding of the string
33398 ** representation is already stored using the requested encoding, then this
33399 ** routine is a no-op.
33400 **
33401 ** SQLITE_OK is returned if the conversion is successful (or not required).
33402 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
33403 ** between formats.
33404 */
33405 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
33406   int rc;
33407   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
33408     return SQLITE_OK;
33409   }
33410   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
33411 #ifdef SQLITE_OMIT_UTF16
33412   return SQLITE_ERROR;
33413 #else
33414
33415   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
33416   ** then the encoding of the value may not have changed.
33417   */
33418   rc = sqlite3VdbeMemTranslate(pMem, desiredEnc);
33419   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
33420   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
33421   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
33422   return rc;
33423 #endif
33424 }
33425
33426 /*
33427 ** Make the given Mem object MEM_Dyn.
33428 **
33429 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
33430 */
33431 SQLITE_PRIVATE int sqlite3VdbeMemDynamicify(Mem *pMem){
33432   int n;
33433   u8 *z;
33434   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
33435   expandBlob(pMem);
33436   if( (pMem->flags & (MEM_Ephem|MEM_Static|MEM_Short))==0 ){
33437     return SQLITE_OK;
33438   }
33439   assert( (pMem->flags & MEM_Dyn)==0 );
33440   n = pMem->n;
33441   assert( pMem->flags & (MEM_Str|MEM_Blob) );
33442   z = sqlite3DbMallocRaw(pMem->db, n+2 );
33443   if( z==0 ){
33444     return SQLITE_NOMEM;
33445   }
33446   pMem->flags |= MEM_Dyn|MEM_Term;
33447   pMem->xDel = 0;
33448   memcpy(z, pMem->z, n );
33449   z[n] = 0;
33450   z[n+1] = 0;
33451   pMem->z = (char*)z;
33452   pMem->flags &= ~(MEM_Ephem|MEM_Static|MEM_Short);
33453   return SQLITE_OK;
33454 }
33455
33456 /*
33457 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
33458 ** blob stored in dynamically allocated space.
33459 */
33460 #ifndef SQLITE_OMIT_INCRBLOB
33461 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
33462   if( pMem->flags & MEM_Zero ){
33463     char *pNew;
33464     int nByte;
33465     assert( (pMem->flags & MEM_Blob)!=0 );
33466     nByte = pMem->n + pMem->u.i;
33467     if( nByte<=0 ) nByte = 1;
33468     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
33469     pNew = sqlite3DbMallocRaw(pMem->db, nByte);
33470     if( pNew==0 ){
33471       return SQLITE_NOMEM;
33472     }
33473     memcpy(pNew, pMem->z, pMem->n);
33474     memset(&pNew[pMem->n], 0, pMem->u.i);
33475     sqlite3VdbeMemRelease(pMem);
33476     pMem->z = pNew;
33477     pMem->n += pMem->u.i;
33478     pMem->u.i = 0;
33479     pMem->flags &= ~(MEM_Zero|MEM_Static|MEM_Ephem|MEM_Short|MEM_Term);
33480     pMem->flags |= MEM_Dyn;
33481   }
33482   return SQLITE_OK;
33483 }
33484 #endif
33485
33486
33487 /*
33488 ** Make the given Mem object either MEM_Short or MEM_Dyn so that bytes
33489 ** of the Mem.z[] array can be modified.
33490 **
33491 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
33492 */
33493 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
33494   int n;
33495   u8 *z;
33496   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
33497   expandBlob(pMem);
33498   if( (pMem->flags & (MEM_Ephem|MEM_Static))==0 ){
33499     return SQLITE_OK;
33500   }
33501   assert( (pMem->flags & MEM_Dyn)==0 );
33502   assert( pMem->flags & (MEM_Str|MEM_Blob) );
33503   if( (n = pMem->n)+2<sizeof(pMem->zShort) ){
33504     z = (u8*)pMem->zShort;
33505     pMem->flags |= MEM_Short|MEM_Term;
33506   }else{
33507     z = sqlite3DbMallocRaw(pMem->db, n+2 );
33508     if( z==0 ){
33509       return SQLITE_NOMEM;
33510     }
33511     pMem->flags |= MEM_Dyn|MEM_Term;
33512     pMem->xDel = 0;
33513   }
33514   memcpy(z, pMem->z, n );
33515   z[n] = 0;
33516   z[n+1] = 0;
33517   pMem->z = (char*)z;
33518   pMem->flags &= ~(MEM_Ephem|MEM_Static);
33519   assert(0==(1&(int)pMem->z));
33520   return SQLITE_OK;
33521 }
33522
33523 /*
33524 ** Make sure the given Mem is \u0000 terminated.
33525 */
33526 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
33527   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
33528   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
33529     return SQLITE_OK;   /* Nothing to do */
33530   }
33531   if( pMem->flags & (MEM_Static|MEM_Ephem) ){
33532     return sqlite3VdbeMemMakeWriteable(pMem);
33533   }else{
33534     char *z; 
33535     sqlite3VdbeMemExpandBlob(pMem);
33536     z = sqlite3DbMallocRaw(pMem->db, pMem->n+2);
33537     if( !z ){
33538        return SQLITE_NOMEM;
33539     }
33540     memcpy(z, pMem->z, pMem->n);
33541     z[pMem->n] = 0;
33542     z[pMem->n+1] = 0;
33543     if( pMem->xDel ){
33544       pMem->xDel(pMem->z);
33545     }else{
33546       sqlite3_free(pMem->z);
33547     }
33548     pMem->xDel = 0;
33549     pMem->z = z;
33550     pMem->flags |= MEM_Term;
33551   }
33552   return SQLITE_OK;
33553 }
33554
33555 /*
33556 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
33557 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
33558 ** is a no-op.
33559 **
33560 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
33561 **
33562 ** A MEM_Null value will never be passed to this function. This function is
33563 ** used for converting values to text for returning to the user (i.e. via
33564 ** sqlite3_value_text()), or for ensuring that values to be used as btree
33565 ** keys are strings. In the former case a NULL pointer is returned the
33566 ** user and the later is an internal programming error.
33567 */
33568 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
33569   int rc = SQLITE_OK;
33570   int fg = pMem->flags;
33571   char *z = pMem->zShort;
33572
33573   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
33574   assert( !(fg&MEM_Zero) );
33575   assert( !(fg&(MEM_Str|MEM_Blob)) );
33576   assert( fg&(MEM_Int|MEM_Real) );
33577
33578   /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
33579   ** string representation of the value. Then, if the required encoding
33580   ** is UTF-16le or UTF-16be do a translation.
33581   ** 
33582   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
33583   */
33584   if( fg & MEM_Int ){
33585     sqlite3_snprintf(NBFS, z, "%lld", pMem->u.i);
33586   }else{
33587     assert( fg & MEM_Real );
33588     sqlite3_snprintf(NBFS, z, "%!.15g", pMem->r);
33589   }
33590   pMem->n = strlen(z);
33591   pMem->z = z;
33592   pMem->enc = SQLITE_UTF8;
33593   pMem->flags |= MEM_Str | MEM_Short | MEM_Term;
33594   sqlite3VdbeChangeEncoding(pMem, enc);
33595   return rc;
33596 }
33597
33598 /*
33599 ** Memory cell pMem contains the context of an aggregate function.
33600 ** This routine calls the finalize method for that function.  The
33601 ** result of the aggregate is stored back into pMem.
33602 **
33603 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
33604 ** otherwise.
33605 */
33606 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
33607   int rc = SQLITE_OK;
33608   if( pFunc && pFunc->xFinalize ){
33609     sqlite3_context ctx;
33610     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
33611     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
33612     ctx.s.flags = MEM_Null;
33613     ctx.s.z = pMem->zShort;
33614     ctx.s.db = pMem->db;
33615     ctx.pMem = pMem;
33616     ctx.pFunc = pFunc;
33617     ctx.isError = 0;
33618     pFunc->xFinalize(&ctx);
33619     if( pMem->z && pMem->z!=pMem->zShort ){
33620       sqlite3_free( pMem->z );
33621     }
33622     *pMem = ctx.s;
33623     if( pMem->flags & MEM_Short ){
33624       pMem->z = pMem->zShort;
33625     }
33626     rc = (ctx.isError?SQLITE_ERROR:SQLITE_OK);
33627   }
33628   return rc;
33629 }
33630
33631 /*
33632 ** Release any memory held by the Mem. This may leave the Mem in an
33633 ** inconsistent state, for example with (Mem.z==0) and
33634 ** (Mem.type==SQLITE_TEXT).
33635 */
33636 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
33637   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
33638   if( p->flags & (MEM_Dyn|MEM_Agg) ){
33639     if( p->xDel ){
33640       if( p->flags & MEM_Agg ){
33641         sqlite3VdbeMemFinalize(p, p->u.pDef);
33642         assert( (p->flags & MEM_Agg)==0 );
33643         sqlite3VdbeMemRelease(p);
33644       }else{
33645         p->xDel((void *)p->z);
33646       }
33647     }else{
33648       sqlite3_free(p->z);
33649     }
33650     p->z = 0;
33651     p->xDel = 0;
33652   }
33653 }
33654
33655 /*
33656 ** Return some kind of integer value which is the best we can do
33657 ** at representing the value that *pMem describes as an integer.
33658 ** If pMem is an integer, then the value is exact.  If pMem is
33659 ** a floating-point then the value returned is the integer part.
33660 ** If pMem is a string or blob, then we make an attempt to convert
33661 ** it into a integer and return that.  If pMem is NULL, return 0.
33662 **
33663 ** If pMem is a string, its encoding might be changed.
33664 */
33665 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
33666   int flags;
33667   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
33668   flags = pMem->flags;
33669   if( flags & MEM_Int ){
33670     return pMem->u.i;
33671   }else if( flags & MEM_Real ){
33672     return (i64)pMem->r;
33673   }else if( flags & (MEM_Str|MEM_Blob) ){
33674     i64 value;
33675     pMem->flags |= MEM_Str;
33676     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
33677        || sqlite3VdbeMemNulTerminate(pMem) ){
33678       return 0;
33679     }
33680     assert( pMem->z );
33681     sqlite3Atoi64(pMem->z, &value);
33682     return value;
33683   }else{
33684     return 0;
33685   }
33686 }
33687
33688 /*
33689 ** Return the best representation of pMem that we can get into a
33690 ** double.  If pMem is already a double or an integer, return its
33691 ** value.  If it is a string or blob, try to convert it to a double.
33692 ** If it is a NULL, return 0.0.
33693 */
33694 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
33695   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
33696   if( pMem->flags & MEM_Real ){
33697     return pMem->r;
33698   }else if( pMem->flags & MEM_Int ){
33699     return (double)pMem->u.i;
33700   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
33701     double val = 0.0;
33702     pMem->flags |= MEM_Str;
33703     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
33704        || sqlite3VdbeMemNulTerminate(pMem) ){
33705       return 0.0;
33706     }
33707     assert( pMem->z );
33708     sqlite3AtoF(pMem->z, &val);
33709     return val;
33710   }else{
33711     return 0.0;
33712   }
33713 }
33714
33715 /*
33716 ** The MEM structure is already a MEM_Real.  Try to also make it a
33717 ** MEM_Int if we can.
33718 */
33719 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
33720   assert( pMem->flags & MEM_Real );
33721   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
33722   pMem->u.i = pMem->r;
33723   if( ((double)pMem->u.i)==pMem->r ){
33724     pMem->flags |= MEM_Int;
33725   }
33726 }
33727
33728 /*
33729 ** Convert pMem to type integer.  Invalidate any prior representations.
33730 */
33731 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
33732   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
33733   pMem->u.i = sqlite3VdbeIntValue(pMem);
33734   sqlite3VdbeMemRelease(pMem);
33735   pMem->flags = MEM_Int;
33736   return SQLITE_OK;
33737 }
33738
33739 /*
33740 ** Convert pMem so that it is of type MEM_Real.
33741 ** Invalidate any prior representations.
33742 */
33743 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
33744   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
33745   pMem->r = sqlite3VdbeRealValue(pMem);
33746   sqlite3VdbeMemRelease(pMem);
33747   pMem->flags = MEM_Real;
33748   return SQLITE_OK;
33749 }
33750
33751 /*
33752 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
33753 ** Invalidate any prior representations.
33754 */
33755 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
33756   double r1, r2;
33757   i64 i;
33758   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
33759   assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
33760   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
33761   r1 = sqlite3VdbeRealValue(pMem);
33762   i = (i64)r1;
33763   r2 = (double)i;
33764   if( r1==r2 ){
33765     sqlite3VdbeMemIntegerify(pMem);
33766   }else{
33767     pMem->r = r1;
33768     pMem->flags = MEM_Real;
33769     sqlite3VdbeMemRelease(pMem);
33770   }
33771   return SQLITE_OK;
33772 }
33773
33774 /*
33775 ** Delete any previous value and set the value stored in *pMem to NULL.
33776 */
33777 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
33778   sqlite3VdbeMemRelease(pMem);
33779   pMem->flags = MEM_Null;
33780   pMem->type = SQLITE_NULL;
33781   pMem->n = 0;
33782 }
33783
33784 /*
33785 ** Delete any previous value and set the value to be a BLOB of length
33786 ** n containing all zeros.
33787 */
33788 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
33789   sqlite3VdbeMemRelease(pMem);
33790   pMem->flags = MEM_Blob|MEM_Zero|MEM_Short;
33791   pMem->type = SQLITE_BLOB;
33792   pMem->n = 0;
33793   if( n<0 ) n = 0;
33794   pMem->u.i = n;
33795   pMem->z = pMem->zShort;
33796   pMem->enc = SQLITE_UTF8;
33797 }
33798
33799 /*
33800 ** Delete any previous value and set the value stored in *pMem to val,
33801 ** manifest type INTEGER.
33802 */
33803 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
33804   sqlite3VdbeMemRelease(pMem);
33805   pMem->u.i = val;
33806   pMem->flags = MEM_Int;
33807   pMem->type = SQLITE_INTEGER;
33808 }
33809
33810 /*
33811 ** Delete any previous value and set the value stored in *pMem to val,
33812 ** manifest type REAL.
33813 */
33814 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
33815   if( sqlite3_isnan(val) ){
33816     sqlite3VdbeMemSetNull(pMem);
33817   }else{
33818     sqlite3VdbeMemRelease(pMem);
33819     pMem->r = val;
33820     pMem->flags = MEM_Real;
33821     pMem->type = SQLITE_FLOAT;
33822   }
33823 }
33824
33825 /*
33826 ** Return true if the Mem object contains a TEXT or BLOB that is
33827 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
33828 */
33829 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
33830   if( p->flags & (MEM_Str|MEM_Blob) ){
33831     int n = p->n;
33832     if( p->flags & MEM_Zero ){
33833       n += p->u.i;
33834     }
33835     return n>SQLITE_MAX_LENGTH;
33836   }
33837   return 0; 
33838 }
33839
33840 /*
33841 ** Make an shallow copy of pFrom into pTo.  Prior contents of
33842 ** pTo are overwritten.  The pFrom->z field is not duplicated.  If
33843 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
33844 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
33845 */
33846 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
33847   memcpy(pTo, pFrom, sizeof(*pFrom)-sizeof(pFrom->zShort));
33848   pTo->xDel = 0;
33849   if( pTo->flags & (MEM_Str|MEM_Blob) ){
33850     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Short|MEM_Ephem);
33851     assert( srcType==MEM_Ephem || srcType==MEM_Static );
33852     pTo->flags |= srcType;
33853   }
33854 }
33855
33856 /*
33857 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
33858 ** freed before the copy is made.
33859 */
33860 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
33861   int rc;
33862   if( pTo->flags & MEM_Dyn ){
33863     sqlite3VdbeMemRelease(pTo);
33864   }
33865   sqlite3VdbeMemShallowCopy(pTo, pFrom, MEM_Ephem);
33866   if( pTo->flags & MEM_Ephem ){
33867     rc = sqlite3VdbeMemMakeWriteable(pTo);
33868   }else{
33869     rc = SQLITE_OK;
33870   }
33871   return rc;
33872 }
33873
33874 /*
33875 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
33876 ** freed. If pFrom contains ephemeral data, a copy is made.
33877 **
33878 ** pFrom contains an SQL NULL when this routine returns.  SQLITE_NOMEM
33879 ** might be returned if pFrom held ephemeral data and we were unable
33880 ** to allocate enough space to make a copy.
33881 */
33882 SQLITE_PRIVATE int sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
33883   int rc;
33884   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
33885   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
33886   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
33887   if( pTo->flags & MEM_Dyn ){
33888     sqlite3VdbeMemRelease(pTo);
33889   }
33890   memcpy(pTo, pFrom, sizeof(Mem));
33891   if( pFrom->flags & MEM_Short ){
33892     pTo->z = pTo->zShort;
33893   }
33894   pFrom->flags = MEM_Null;
33895   pFrom->xDel = 0;
33896   if( pTo->flags & MEM_Ephem ){
33897     rc = sqlite3VdbeMemMakeWriteable(pTo);
33898   }else{
33899     rc = SQLITE_OK;
33900   }
33901   return rc;
33902 }
33903
33904 /*
33905 ** Change the value of a Mem to be a string or a BLOB.
33906 */
33907 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
33908   Mem *pMem,          /* Memory cell to set to string value */
33909   const char *z,      /* String pointer */
33910   int n,              /* Bytes in string, or negative */
33911   u8 enc,             /* Encoding of z.  0 for BLOBs */
33912   void (*xDel)(void*) /* Destructor function */
33913 ){
33914   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
33915   sqlite3VdbeMemRelease(pMem);
33916   if( !z ){
33917     pMem->flags = MEM_Null;
33918     pMem->type = SQLITE_NULL;
33919     return SQLITE_OK;
33920   }
33921   pMem->z = (char *)z;
33922   if( xDel==SQLITE_STATIC ){
33923     pMem->flags = MEM_Static;
33924   }else if( xDel==SQLITE_TRANSIENT ){
33925     pMem->flags = MEM_Ephem;
33926   }else{
33927     pMem->flags = MEM_Dyn;
33928     pMem->xDel = xDel;
33929   }
33930
33931   pMem->enc = enc;
33932   pMem->type = enc==0 ? SQLITE_BLOB : SQLITE_TEXT;
33933   pMem->n = n;
33934
33935   assert( enc==0 || enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE 
33936       || enc==SQLITE_UTF16BE );
33937   switch( enc ){
33938     case 0:
33939       pMem->flags |= MEM_Blob;
33940       pMem->enc = SQLITE_UTF8;
33941       break;
33942
33943     case SQLITE_UTF8:
33944       pMem->flags |= MEM_Str;
33945       if( n<0 ){
33946         pMem->n = strlen(z);
33947         pMem->flags |= MEM_Term;
33948       }
33949       break;
33950
33951 #ifndef SQLITE_OMIT_UTF16
33952     case SQLITE_UTF16LE:
33953     case SQLITE_UTF16BE:
33954       pMem->flags |= MEM_Str;
33955       if( pMem->n<0 ){
33956         pMem->n = sqlite3Utf16ByteLen(pMem->z,-1);
33957         pMem->flags |= MEM_Term;
33958       }
33959       if( sqlite3VdbeMemHandleBom(pMem) ){
33960         return SQLITE_NOMEM;
33961       }
33962 #endif /* SQLITE_OMIT_UTF16 */
33963   }
33964   if( pMem->flags&MEM_Ephem ){
33965     return sqlite3VdbeMemMakeWriteable(pMem);
33966   }
33967   return SQLITE_OK;
33968 }
33969
33970 /*
33971 ** Compare the values contained by the two memory cells, returning
33972 ** negative, zero or positive if pMem1 is less than, equal to, or greater
33973 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
33974 ** and reals) sorted numerically, followed by text ordered by the collating
33975 ** sequence pColl and finally blob's ordered by memcmp().
33976 **
33977 ** Two NULL values are considered equal by this function.
33978 */
33979 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
33980   int rc;
33981   int f1, f2;
33982   int combined_flags;
33983
33984   /* Interchange pMem1 and pMem2 if the collating sequence specifies
33985   ** DESC order.
33986   */
33987   f1 = pMem1->flags;
33988   f2 = pMem2->flags;
33989   combined_flags = f1|f2;
33990  
33991   /* If one value is NULL, it is less than the other. If both values
33992   ** are NULL, return 0.
33993   */
33994   if( combined_flags&MEM_Null ){
33995     return (f2&MEM_Null) - (f1&MEM_Null);
33996   }
33997
33998   /* If one value is a number and the other is not, the number is less.
33999   ** If both are numbers, compare as reals if one is a real, or as integers
34000   ** if both values are integers.
34001   */
34002   if( combined_flags&(MEM_Int|MEM_Real) ){
34003     if( !(f1&(MEM_Int|MEM_Real)) ){
34004       return 1;
34005     }
34006     if( !(f2&(MEM_Int|MEM_Real)) ){
34007       return -1;
34008     }
34009     if( (f1 & f2 & MEM_Int)==0 ){
34010       double r1, r2;
34011       if( (f1&MEM_Real)==0 ){
34012         r1 = pMem1->u.i;
34013       }else{
34014         r1 = pMem1->r;
34015       }
34016       if( (f2&MEM_Real)==0 ){
34017         r2 = pMem2->u.i;
34018       }else{
34019         r2 = pMem2->r;
34020       }
34021       if( r1<r2 ) return -1;
34022       if( r1>r2 ) return 1;
34023       return 0;
34024     }else{
34025       assert( f1&MEM_Int );
34026       assert( f2&MEM_Int );
34027       if( pMem1->u.i < pMem2->u.i ) return -1;
34028       if( pMem1->u.i > pMem2->u.i ) return 1;
34029       return 0;
34030     }
34031   }
34032
34033   /* If one value is a string and the other is a blob, the string is less.
34034   ** If both are strings, compare using the collating functions.
34035   */
34036   if( combined_flags&MEM_Str ){
34037     if( (f1 & MEM_Str)==0 ){
34038       return 1;
34039     }
34040     if( (f2 & MEM_Str)==0 ){
34041       return -1;
34042     }
34043
34044     assert( pMem1->enc==pMem2->enc );
34045     assert( pMem1->enc==SQLITE_UTF8 || 
34046             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
34047
34048     /* The collation sequence must be defined at this point, even if
34049     ** the user deletes the collation sequence after the vdbe program is
34050     ** compiled (this was not always the case).
34051     */
34052     assert( !pColl || pColl->xCmp );
34053
34054     if( pColl ){
34055       if( pMem1->enc==pColl->enc ){
34056         /* The strings are already in the correct encoding.  Call the
34057         ** comparison function directly */
34058         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
34059       }else{
34060         u8 origEnc = pMem1->enc;
34061         const void *v1, *v2;
34062         int n1, n2;
34063         /* Convert the strings into the encoding that the comparison
34064         ** function expects */
34065         v1 = sqlite3ValueText((sqlite3_value*)pMem1, pColl->enc);
34066         n1 = v1==0 ? 0 : pMem1->n;
34067         assert( n1==sqlite3ValueBytes((sqlite3_value*)pMem1, pColl->enc) );
34068         v2 = sqlite3ValueText((sqlite3_value*)pMem2, pColl->enc);
34069         n2 = v2==0 ? 0 : pMem2->n;
34070         assert( n2==sqlite3ValueBytes((sqlite3_value*)pMem2, pColl->enc) );
34071         /* Do the comparison */
34072         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
34073         /* Convert the strings back into the database encoding */
34074         sqlite3ValueText((sqlite3_value*)pMem1, origEnc);
34075         sqlite3ValueText((sqlite3_value*)pMem2, origEnc);
34076         return rc;
34077       }
34078     }
34079     /* If a NULL pointer was passed as the collate function, fall through
34080     ** to the blob case and use memcmp().  */
34081   }
34082  
34083   /* Both values must be blobs.  Compare using memcmp().  */
34084   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
34085   if( rc==0 ){
34086     rc = pMem1->n - pMem2->n;
34087   }
34088   return rc;
34089 }
34090
34091 /*
34092 ** Move data out of a btree key or data field and into a Mem structure.
34093 ** The data or key is taken from the entry that pCur is currently pointing
34094 ** to.  offset and amt determine what portion of the data or key to retrieve.
34095 ** key is true to get the key or false to get data.  The result is written
34096 ** into the pMem element.
34097 **
34098 ** The pMem structure is assumed to be uninitialized.  Any prior content
34099 ** is overwritten without being freed.
34100 **
34101 ** If this routine fails for any reason (malloc returns NULL or unable
34102 ** to read from the disk) then the pMem is left in an inconsistent state.
34103 */
34104 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
34105   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
34106   int offset,       /* Offset from the start of data to return bytes from. */
34107   int amt,          /* Number of bytes to return. */
34108   int key,          /* If true, retrieve from the btree key, not data. */
34109   Mem *pMem         /* OUT: Return data in this Mem structure. */
34110 ){
34111   char *zData;       /* Data from the btree layer */
34112   int available = 0; /* Number of bytes available on the local btree page */
34113   sqlite3 *db;       /* Database connection */
34114
34115   db = sqlite3BtreeCursorDb(pCur);
34116   assert( sqlite3_mutex_held(db->mutex) );
34117   if( key ){
34118     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
34119   }else{
34120     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
34121   }
34122   assert( zData!=0 );
34123
34124   pMem->db = db;
34125   pMem->n = amt;
34126   if( offset+amt<=available ){
34127     pMem->z = &zData[offset];
34128     pMem->flags = MEM_Blob|MEM_Ephem;
34129   }else{
34130     int rc;
34131     if( amt>NBFS-2 ){
34132       zData = (char *)sqlite3DbMallocRaw(db, amt+2);
34133       if( !zData ){
34134         return SQLITE_NOMEM;
34135       }
34136       pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
34137       pMem->xDel = 0;
34138     }else{
34139       zData = &(pMem->zShort[0]);
34140       pMem->flags = MEM_Blob|MEM_Short|MEM_Term;
34141     }
34142     pMem->z = zData;
34143     pMem->enc = 0;
34144     pMem->type = SQLITE_BLOB;
34145
34146     if( key ){
34147       rc = sqlite3BtreeKey(pCur, offset, amt, zData);
34148     }else{
34149       rc = sqlite3BtreeData(pCur, offset, amt, zData);
34150     }
34151     zData[amt] = 0;
34152     zData[amt+1] = 0;
34153     if( rc!=SQLITE_OK ){
34154       if( amt>NBFS-2 ){
34155         assert( zData!=pMem->zShort );
34156         assert( pMem->flags & MEM_Dyn );
34157         sqlite3_free(zData);
34158       } else {
34159         assert( zData==pMem->zShort );
34160         assert( pMem->flags & MEM_Short );
34161       }
34162       return rc;
34163     }
34164   }
34165
34166   return SQLITE_OK;
34167 }
34168
34169 #ifndef NDEBUG
34170 /*
34171 ** Perform various checks on the memory cell pMem. An assert() will
34172 ** fail if pMem is internally inconsistent.
34173 */
34174 SQLITE_PRIVATE void sqlite3VdbeMemSanity(Mem *pMem){
34175   int flags = pMem->flags;
34176   assert( flags!=0 );  /* Must define some type */
34177   if( flags & (MEM_Str|MEM_Blob) ){
34178     int x = flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short);
34179     assert( x!=0 );            /* Strings must define a string subtype */
34180     assert( (x & (x-1))==0 );  /* Only one string subtype can be defined */
34181     assert( pMem->z!=0 );      /* Strings must have a value */
34182     /* Mem.z points to Mem.zShort iff the subtype is MEM_Short */
34183     assert( (x & MEM_Short)==0 || pMem->z==pMem->zShort );
34184     assert( (x & MEM_Short)!=0 || pMem->z!=pMem->zShort );
34185     /* No destructor unless there is MEM_Dyn */
34186     assert( pMem->xDel==0 || (pMem->flags & MEM_Dyn)!=0 );
34187
34188     if( (flags & MEM_Str) ){
34189       assert( pMem->enc==SQLITE_UTF8 || 
34190               pMem->enc==SQLITE_UTF16BE ||
34191               pMem->enc==SQLITE_UTF16LE 
34192       );
34193       /* If the string is UTF-8 encoded and nul terminated, then pMem->n
34194       ** must be the length of the string.  (Later:)  If the database file
34195       ** has been corrupted, '\000' characters might have been inserted
34196       ** into the middle of the string.  In that case, the strlen() might
34197       ** be less.
34198       */
34199       if( pMem->enc==SQLITE_UTF8 && (flags & MEM_Term) ){ 
34200         assert( strlen(pMem->z)<=pMem->n );
34201         assert( pMem->z[pMem->n]==0 );
34202       }
34203     }
34204   }else{
34205     /* Cannot define a string subtype for non-string objects */
34206     assert( (pMem->flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short))==0 );
34207     assert( pMem->xDel==0 );
34208   }
34209   /* MEM_Null excludes all other types */
34210   assert( (pMem->flags&(MEM_Str|MEM_Int|MEM_Real|MEM_Blob))==0
34211           || (pMem->flags&MEM_Null)==0 );
34212   /* If the MEM is both real and integer, the values are equal */
34213   assert( (pMem->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) 
34214           || pMem->r==pMem->u.i );
34215 }
34216 #endif
34217
34218 /* This function is only available internally, it is not part of the
34219 ** external API. It works in a similar way to sqlite3_value_text(),
34220 ** except the data returned is in the encoding specified by the second
34221 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
34222 ** SQLITE_UTF8.
34223 **
34224 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
34225 ** If that is the case, then the result must be aligned on an even byte
34226 ** boundary.
34227 */
34228 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
34229   if( !pVal ) return 0;
34230
34231   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
34232   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
34233
34234   if( pVal->flags&MEM_Null ){
34235     return 0;
34236   }
34237   assert( (MEM_Blob>>3) == MEM_Str );
34238   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
34239   expandBlob(pVal);
34240   if( pVal->flags&MEM_Str ){
34241     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
34242     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&(int)pVal->z) ){
34243       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
34244       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
34245         return 0;
34246       }
34247     }
34248     sqlite3VdbeMemNulTerminate(pVal);
34249   }else{
34250     assert( (pVal->flags&MEM_Blob)==0 );
34251     sqlite3VdbeMemStringify(pVal, enc);
34252     assert( 0==(1&(int)pVal->z) );
34253   }
34254   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
34255               || pVal->db->mallocFailed );
34256   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
34257     return pVal->z;
34258   }else{
34259     return 0;
34260   }
34261 }
34262
34263 /*
34264 ** Create a new sqlite3_value object.
34265 */
34266 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
34267   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
34268   if( p ){
34269     p->flags = MEM_Null;
34270     p->type = SQLITE_NULL;
34271     p->db = db;
34272   }
34273   return p;
34274 }
34275
34276 /*
34277 ** Create a new sqlite3_value object, containing the value of pExpr.
34278 **
34279 ** This only works for very simple expressions that consist of one constant
34280 ** token (i.e. "5", "5.1", "NULL", "'a string'"). If the expression can
34281 ** be converted directly into a value, then the value is allocated and
34282 ** a pointer written to *ppVal. The caller is responsible for deallocating
34283 ** the value by passing it to sqlite3ValueFree() later on. If the expression
34284 ** cannot be converted to a value, then *ppVal is set to NULL.
34285 */
34286 SQLITE_PRIVATE int sqlite3ValueFromExpr(
34287   sqlite3 *db,              /* The database connection */
34288   Expr *pExpr,              /* The expression to evaluate */
34289   u8 enc,                   /* Encoding to use */
34290   u8 affinity,              /* Affinity to use */
34291   sqlite3_value **ppVal     /* Write the new value here */
34292 ){
34293   int op;
34294   char *zVal = 0;
34295   sqlite3_value *pVal = 0;
34296
34297   if( !pExpr ){
34298     *ppVal = 0;
34299     return SQLITE_OK;
34300   }
34301   op = pExpr->op;
34302
34303   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
34304     zVal = sqlite3StrNDup((char*)pExpr->token.z, pExpr->token.n);
34305     pVal = sqlite3ValueNew(db);
34306     if( !zVal || !pVal ) goto no_mem;
34307     sqlite3Dequote(zVal);
34308     sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, sqlite3_free);
34309     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
34310       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, enc);
34311     }else{
34312       sqlite3ValueApplyAffinity(pVal, affinity, enc);
34313     }
34314   }else if( op==TK_UMINUS ) {
34315     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
34316       pVal->u.i = -1 * pVal->u.i;
34317       pVal->r = -1.0 * pVal->r;
34318     }
34319   }
34320 #ifndef SQLITE_OMIT_BLOB_LITERAL
34321   else if( op==TK_BLOB ){
34322     int nVal;
34323     pVal = sqlite3ValueNew(db);
34324     zVal = sqlite3StrNDup((char*)pExpr->token.z+1, pExpr->token.n-1);
34325     if( !zVal || !pVal ) goto no_mem;
34326     sqlite3Dequote(zVal);
34327     nVal = strlen(zVal)/2;
34328     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal), nVal,0,sqlite3_free);
34329     sqlite3_free(zVal);
34330   }
34331 #endif
34332
34333   *ppVal = pVal;
34334   return SQLITE_OK;
34335
34336 no_mem:
34337   db->mallocFailed = 1;
34338   sqlite3_free(zVal);
34339   sqlite3ValueFree(pVal);
34340   *ppVal = 0;
34341   return SQLITE_NOMEM;
34342 }
34343
34344 /*
34345 ** Change the string value of an sqlite3_value object
34346 */
34347 SQLITE_PRIVATE void sqlite3ValueSetStr(
34348   sqlite3_value *v,     /* Value to be set */
34349   int n,                /* Length of string z */
34350   const void *z,        /* Text of the new string */
34351   u8 enc,               /* Encoding to use */
34352   void (*xDel)(void*)   /* Destructor for the string */
34353 ){
34354   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
34355 }
34356
34357 /*
34358 ** Free an sqlite3_value object
34359 */
34360 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
34361   if( !v ) return;
34362   sqlite3ValueSetStr(v, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
34363   sqlite3_free(v);
34364 }
34365
34366 /*
34367 ** Return the number of bytes in the sqlite3_value object assuming
34368 ** that it uses the encoding "enc"
34369 */
34370 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
34371   Mem *p = (Mem*)pVal;
34372   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
34373     if( p->flags & MEM_Zero ){
34374       return p->n+p->u.i;
34375     }else{
34376       return p->n;
34377     }
34378   }
34379   return 0;
34380 }
34381
34382 /************** End of vdbemem.c *********************************************/
34383 /************** Begin file vdbeaux.c *****************************************/
34384 /*
34385 ** 2003 September 6
34386 **
34387 ** The author disclaims copyright to this source code.  In place of
34388 ** a legal notice, here is a blessing:
34389 **
34390 **    May you do good and not evil.
34391 **    May you find forgiveness for yourself and forgive others.
34392 **    May you share freely, never taking more than you give.
34393 **
34394 *************************************************************************
34395 ** This file contains code used for creating, destroying, and populating
34396 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
34397 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
34398 ** But that file was getting too big so this subroutines were split out.
34399 */
34400
34401
34402
34403 /*
34404 ** When debugging the code generator in a symbolic debugger, one can
34405 ** set the sqlite3_vdbe_addop_trace to 1 and all opcodes will be printed
34406 ** as they are added to the instruction stream.
34407 */
34408 #ifdef SQLITE_DEBUG
34409 SQLITE_API int sqlite3_vdbe_addop_trace = 0;
34410 #endif
34411
34412
34413 /*
34414 ** Create a new virtual database engine.
34415 */
34416 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
34417   Vdbe *p;
34418   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
34419   if( p==0 ) return 0;
34420   p->db = db;
34421   if( db->pVdbe ){
34422     db->pVdbe->pPrev = p;
34423   }
34424   p->pNext = db->pVdbe;
34425   p->pPrev = 0;
34426   db->pVdbe = p;
34427   p->magic = VDBE_MAGIC_INIT;
34428   return p;
34429 }
34430
34431 /*
34432 ** Remember the SQL string for a prepared statement.
34433 */
34434 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n){
34435   if( p==0 ) return;
34436   assert( p->zSql==0 );
34437   p->zSql = sqlite3DbStrNDup(p->db, z, n);
34438 }
34439
34440 /*
34441 ** Return the SQL associated with a prepared statement
34442 */
34443 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
34444   return ((Vdbe *)pStmt)->zSql;
34445 }
34446
34447 /*
34448 ** Swap all content between two VDBE structures.
34449 */
34450 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
34451   Vdbe tmp, *pTmp;
34452   char *zTmp;
34453   int nTmp;
34454   tmp = *pA;
34455   *pA = *pB;
34456   *pB = tmp;
34457   pTmp = pA->pNext;
34458   pA->pNext = pB->pNext;
34459   pB->pNext = pTmp;
34460   pTmp = pA->pPrev;
34461   pA->pPrev = pB->pPrev;
34462   pB->pPrev = pTmp;
34463   zTmp = pA->zSql;
34464   pA->zSql = pB->zSql;
34465   pB->zSql = zTmp;
34466   nTmp = pA->nSql;
34467   pA->nSql = pB->nSql;
34468   pB->nSql = nTmp;
34469 }
34470
34471 #ifdef SQLITE_DEBUG
34472 /*
34473 ** Turn tracing on or off
34474 */
34475 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
34476   p->trace = trace;
34477 }
34478 #endif
34479
34480 /*
34481 ** Resize the Vdbe.aOp array so that it contains at least N
34482 ** elements.
34483 **
34484 ** If an out-of-memory error occurs while resizing the array,
34485 ** Vdbe.aOp and Vdbe.nOpAlloc remain unchanged (this is so that
34486 ** any opcodes already allocated can be correctly deallocated
34487 ** along with the rest of the Vdbe).
34488 */
34489 static void resizeOpArray(Vdbe *p, int N){
34490   VdbeOp *pNew;
34491   int oldSize = p->nOpAlloc;
34492   pNew = sqlite3DbRealloc(p->db, p->aOp, N*sizeof(Op));
34493   if( pNew ){
34494     p->nOpAlloc = N;
34495     p->aOp = pNew;
34496     if( N>oldSize ){
34497       memset(&p->aOp[oldSize], 0, (N-oldSize)*sizeof(Op));
34498     }
34499   }
34500 }
34501
34502 /*
34503 ** Add a new instruction to the list of instructions current in the
34504 ** VDBE.  Return the address of the new instruction.
34505 **
34506 ** Parameters:
34507 **
34508 **    p               Pointer to the VDBE
34509 **
34510 **    op              The opcode for this instruction
34511 **
34512 **    p1, p2          First two of the three possible operands.
34513 **
34514 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
34515 ** the sqlite3VdbeChangeP3() function to change the value of the P3
34516 ** operand.
34517 */
34518 SQLITE_PRIVATE int sqlite3VdbeAddOp(Vdbe *p, int op, int p1, int p2){
34519   int i;
34520   VdbeOp *pOp;
34521
34522   i = p->nOp;
34523   assert( p->magic==VDBE_MAGIC_INIT );
34524   if( p->nOpAlloc<=i ){
34525     resizeOpArray(p, p->nOpAlloc*2 + 100);
34526     if( p->db->mallocFailed ){
34527       return 0;
34528     }
34529   }
34530   p->nOp++;
34531   pOp = &p->aOp[i];
34532   pOp->opcode = op;
34533   pOp->p1 = p1;
34534   pOp->p2 = p2;
34535   pOp->p3 = 0;
34536   pOp->p3type = P3_NOTUSED;
34537   p->expired = 0;
34538 #ifdef SQLITE_DEBUG
34539   if( sqlite3_vdbe_addop_trace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
34540 #endif
34541   return i;
34542 }
34543
34544 /*
34545 ** Add an opcode that includes the p3 value.
34546 */
34547 SQLITE_PRIVATE int sqlite3VdbeOp3(Vdbe *p, int op, int p1, int p2, const char *zP3,int p3type){
34548   int addr = sqlite3VdbeAddOp(p, op, p1, p2);
34549   sqlite3VdbeChangeP3(p, addr, zP3, p3type);
34550   return addr;
34551 }
34552
34553 /*
34554 ** Create a new symbolic label for an instruction that has yet to be
34555 ** coded.  The symbolic label is really just a negative number.  The
34556 ** label can be used as the P2 value of an operation.  Later, when
34557 ** the label is resolved to a specific address, the VDBE will scan
34558 ** through its operation list and change all values of P2 which match
34559 ** the label into the resolved address.
34560 **
34561 ** The VDBE knows that a P2 value is a label because labels are
34562 ** always negative and P2 values are suppose to be non-negative.
34563 ** Hence, a negative P2 value is a label that has yet to be resolved.
34564 **
34565 ** Zero is returned if a malloc() fails.
34566 */
34567 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
34568   int i;
34569   i = p->nLabel++;
34570   assert( p->magic==VDBE_MAGIC_INIT );
34571   if( i>=p->nLabelAlloc ){
34572     p->nLabelAlloc = p->nLabelAlloc*2 + 10;
34573     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
34574                                     p->nLabelAlloc*sizeof(p->aLabel[0]));
34575   }
34576   if( p->aLabel ){
34577     p->aLabel[i] = -1;
34578   }
34579   return -1-i;
34580 }
34581
34582 /*
34583 ** Resolve label "x" to be the address of the next instruction to
34584 ** be inserted.  The parameter "x" must have been obtained from
34585 ** a prior call to sqlite3VdbeMakeLabel().
34586 */
34587 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
34588   int j = -1-x;
34589   assert( p->magic==VDBE_MAGIC_INIT );
34590   assert( j>=0 && j<p->nLabel );
34591   if( p->aLabel ){
34592     p->aLabel[j] = p->nOp;
34593   }
34594 }
34595
34596 /*
34597 ** Return non-zero if opcode 'op' is guarenteed not to push more values
34598 ** onto the VDBE stack than it pops off.
34599 */
34600 static int opcodeNoPush(u8 op){
34601   /* The 10 NOPUSH_MASK_n constants are defined in the automatically
34602   ** generated header file opcodes.h. Each is a 16-bit bitmask, one
34603   ** bit corresponding to each opcode implemented by the virtual
34604   ** machine in vdbe.c. The bit is true if the word "no-push" appears
34605   ** in a comment on the same line as the "case OP_XXX:" in 
34606   ** sqlite3VdbeExec() in vdbe.c.
34607   **
34608   ** If the bit is true, then the corresponding opcode is guarenteed not
34609   ** to grow the stack when it is executed. Otherwise, it may grow the
34610   ** stack by at most one entry.
34611   **
34612   ** NOPUSH_MASK_0 corresponds to opcodes 0 to 15. NOPUSH_MASK_1 contains
34613   ** one bit for opcodes 16 to 31, and so on.
34614   **
34615   ** 16-bit bitmasks (rather than 32-bit) are specified in opcodes.h 
34616   ** because the file is generated by an awk program. Awk manipulates
34617   ** all numbers as floating-point and we don't want to risk a rounding
34618   ** error if someone builds with an awk that uses (for example) 32-bit 
34619   ** IEEE floats.
34620   */ 
34621   static const u32 masks[5] = {
34622     NOPUSH_MASK_0 + (((unsigned)NOPUSH_MASK_1)<<16),
34623     NOPUSH_MASK_2 + (((unsigned)NOPUSH_MASK_3)<<16),
34624     NOPUSH_MASK_4 + (((unsigned)NOPUSH_MASK_5)<<16),
34625     NOPUSH_MASK_6 + (((unsigned)NOPUSH_MASK_7)<<16),
34626     NOPUSH_MASK_8 + (((unsigned)NOPUSH_MASK_9)<<16)
34627   };
34628   assert( op<32*5 );
34629   return (masks[op>>5] & (1<<(op&0x1F)));
34630 }
34631
34632 #ifndef NDEBUG
34633 SQLITE_PRIVATE int sqlite3VdbeOpcodeNoPush(u8 op){
34634   return opcodeNoPush(op);
34635 }
34636 #endif
34637
34638 /*
34639 ** Loop through the program looking for P2 values that are negative.
34640 ** Each such value is a label.  Resolve the label by setting the P2
34641 ** value to its correct non-zero value.
34642 **
34643 ** This routine is called once after all opcodes have been inserted.
34644 **
34645 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
34646 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
34647 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
34648 **
34649 ** The integer *pMaxStack is set to the maximum number of vdbe stack
34650 ** entries that static analysis reveals this program might need.
34651 **
34652 ** This routine also does the following optimization:  It scans for
34653 ** instructions that might cause a statement rollback.  Such instructions
34654 ** are:
34655 **
34656 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
34657 **   *  OP_Destroy
34658 **   *  OP_VUpdate
34659 **   *  OP_VRename
34660 **
34661 ** If no such instruction is found, then every Statement instruction 
34662 ** is changed to a Noop.  In this way, we avoid creating the statement 
34663 ** journal file unnecessarily.
34664 */
34665 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs, int *pMaxStack){
34666   int i;
34667   int nMaxArgs = 0;
34668   int nMaxStack = p->nOp;
34669   Op *pOp;
34670   int *aLabel = p->aLabel;
34671   int doesStatementRollback = 0;
34672   int hasStatementBegin = 0;
34673   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
34674     u8 opcode = pOp->opcode;
34675
34676     if( opcode==OP_Function || opcode==OP_AggStep 
34677 #ifndef SQLITE_OMIT_VIRTUALTABLE
34678         || opcode==OP_VUpdate
34679 #endif
34680     ){
34681       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
34682     }
34683     if( opcode==OP_Halt ){
34684       if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){
34685         doesStatementRollback = 1;
34686       }
34687     }else if( opcode==OP_Statement ){
34688       hasStatementBegin = 1;
34689     }else if( opcode==OP_Destroy ){
34690       doesStatementRollback = 1;
34691 #ifndef SQLITE_OMIT_VIRTUALTABLE
34692     }else if( opcode==OP_VUpdate || opcode==OP_VRename ){
34693       doesStatementRollback = 1;
34694     }else if( opcode==OP_VFilter ){
34695       int n;
34696       assert( p->nOp - i >= 3 );
34697       assert( pOp[-2].opcode==OP_Integer );
34698       n = pOp[-2].p1;
34699       if( n>nMaxArgs ) nMaxArgs = n;
34700 #endif
34701     }
34702     if( opcodeNoPush(opcode) ){
34703       nMaxStack--;
34704     }
34705
34706     if( pOp->p2>=0 ) continue;
34707     assert( -1-pOp->p2<p->nLabel );
34708     pOp->p2 = aLabel[-1-pOp->p2];
34709   }
34710   sqlite3_free(p->aLabel);
34711   p->aLabel = 0;
34712
34713   *pMaxFuncArgs = nMaxArgs;
34714   *pMaxStack = nMaxStack;
34715
34716   /* If we never rollback a statement transaction, then statement
34717   ** transactions are not needed.  So change every OP_Statement
34718   ** opcode into an OP_Noop.  This avoid a call to sqlite3OsOpenExclusive()
34719   ** which can be expensive on some platforms.
34720   */
34721   if( hasStatementBegin && !doesStatementRollback ){
34722     for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
34723       if( pOp->opcode==OP_Statement ){
34724         pOp->opcode = OP_Noop;
34725       }
34726     }
34727   }
34728 }
34729
34730 /*
34731 ** Return the address of the next instruction to be inserted.
34732 */
34733 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
34734   assert( p->magic==VDBE_MAGIC_INIT );
34735   return p->nOp;
34736 }
34737
34738 /*
34739 ** Add a whole list of operations to the operation stack.  Return the
34740 ** address of the first operation added.
34741 */
34742 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
34743   int addr;
34744   assert( p->magic==VDBE_MAGIC_INIT );
34745   if( p->nOp + nOp > p->nOpAlloc ){
34746     resizeOpArray(p, p->nOp*2 + nOp);
34747   }
34748   if( p->db->mallocFailed ){
34749     return 0;
34750   }
34751   addr = p->nOp;
34752   if( nOp>0 ){
34753     int i;
34754     VdbeOpList const *pIn = aOp;
34755     for(i=0; i<nOp; i++, pIn++){
34756       int p2 = pIn->p2;
34757       VdbeOp *pOut = &p->aOp[i+addr];
34758       pOut->opcode = pIn->opcode;
34759       pOut->p1 = pIn->p1;
34760       pOut->p2 = p2<0 ? addr + ADDR(p2) : p2;
34761       pOut->p3 = pIn->p3;
34762       pOut->p3type = pIn->p3 ? P3_STATIC : P3_NOTUSED;
34763 #ifdef SQLITE_DEBUG
34764       if( sqlite3_vdbe_addop_trace ){
34765         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
34766       }
34767 #endif
34768     }
34769     p->nOp += nOp;
34770   }
34771   return addr;
34772 }
34773
34774 /*
34775 ** Change the value of the P1 operand for a specific instruction.
34776 ** This routine is useful when a large program is loaded from a
34777 ** static array using sqlite3VdbeAddOpList but we want to make a
34778 ** few minor changes to the program.
34779 */
34780 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
34781   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
34782   if( p && addr>=0 && p->nOp>addr && p->aOp ){
34783     p->aOp[addr].p1 = val;
34784   }
34785 }
34786
34787 /*
34788 ** Change the value of the P2 operand for a specific instruction.
34789 ** This routine is useful for setting a jump destination.
34790 */
34791 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
34792   assert( val>=0 );
34793   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
34794   if( p && addr>=0 && p->nOp>addr && p->aOp ){
34795     p->aOp[addr].p2 = val;
34796   }
34797 }
34798
34799 /*
34800 ** Change the P2 operand of instruction addr so that it points to
34801 ** the address of the next instruction to be coded.
34802 */
34803 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
34804   sqlite3VdbeChangeP2(p, addr, p->nOp);
34805 }
34806
34807
34808 /*
34809 ** If the input FuncDef structure is ephemeral, then free it.  If
34810 ** the FuncDef is not ephermal, then do nothing.
34811 */
34812 static void freeEphemeralFunction(FuncDef *pDef){
34813   if( pDef && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
34814     sqlite3_free(pDef);
34815   }
34816 }
34817
34818 /*
34819 ** Delete a P3 value if necessary.
34820 */
34821 static void freeP3(int p3type, void *p3){
34822   if( p3 ){
34823     switch( p3type ){
34824       case P3_REAL:
34825       case P3_INT64:
34826       case P3_MPRINTF:
34827       case P3_DYNAMIC:
34828       case P3_KEYINFO:
34829       case P3_KEYINFO_HANDOFF: {
34830         sqlite3_free(p3);
34831         break;
34832       }
34833       case P3_VDBEFUNC: {
34834         VdbeFunc *pVdbeFunc = (VdbeFunc *)p3;
34835         freeEphemeralFunction(pVdbeFunc->pFunc);
34836         sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
34837         sqlite3_free(pVdbeFunc);
34838         break;
34839       }
34840       case P3_FUNCDEF: {
34841         freeEphemeralFunction((FuncDef*)p3);
34842         break;
34843       }
34844       case P3_MEM: {
34845         sqlite3ValueFree((sqlite3_value*)p3);
34846         break;
34847       }
34848     }
34849   }
34850 }
34851
34852
34853 /*
34854 ** Change N opcodes starting at addr to No-ops.
34855 */
34856 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
34857   if( p && p->aOp ){
34858     VdbeOp *pOp = &p->aOp[addr];
34859     while( N-- ){
34860       freeP3(pOp->p3type, pOp->p3);
34861       memset(pOp, 0, sizeof(pOp[0]));
34862       pOp->opcode = OP_Noop;
34863       pOp++;
34864     }
34865   }
34866 }
34867
34868 /*
34869 ** Change the value of the P3 operand for a specific instruction.
34870 ** This routine is useful when a large program is loaded from a
34871 ** static array using sqlite3VdbeAddOpList but we want to make a
34872 ** few minor changes to the program.
34873 **
34874 ** If n>=0 then the P3 operand is dynamic, meaning that a copy of
34875 ** the string is made into memory obtained from sqlite3_malloc().
34876 ** A value of n==0 means copy bytes of zP3 up to and including the
34877 ** first null byte.  If n>0 then copy n+1 bytes of zP3.
34878 **
34879 ** If n==P3_KEYINFO it means that zP3 is a pointer to a KeyInfo structure.
34880 ** A copy is made of the KeyInfo structure into memory obtained from
34881 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
34882 ** n==P3_KEYINFO_HANDOFF indicates that zP3 points to a KeyInfo structure
34883 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
34884 ** caller should not free the allocation, it will be freed when the Vdbe is
34885 ** finalized.
34886 ** 
34887 ** Other values of n (P3_STATIC, P3_COLLSEQ etc.) indicate that zP3 points
34888 ** to a string or structure that is guaranteed to exist for the lifetime of
34889 ** the Vdbe. In these cases we can just copy the pointer.
34890 **
34891 ** If addr<0 then change P3 on the most recently inserted instruction.
34892 */
34893 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
34894   Op *pOp;
34895   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
34896   if( p==0 || p->aOp==0 || p->db->mallocFailed ){
34897     if (n != P3_KEYINFO) {
34898       freeP3(n, (void*)*(char**)&zP3);
34899     }
34900     return;
34901   }
34902   if( addr<0 || addr>=p->nOp ){
34903     addr = p->nOp - 1;
34904     if( addr<0 ) return;
34905   }
34906   pOp = &p->aOp[addr];
34907   freeP3(pOp->p3type, pOp->p3);
34908   pOp->p3 = 0;
34909   if( zP3==0 ){
34910     pOp->p3 = 0;
34911     pOp->p3type = P3_NOTUSED;
34912   }else if( n==P3_KEYINFO ){
34913     KeyInfo *pKeyInfo;
34914     int nField, nByte;
34915
34916     nField = ((KeyInfo*)zP3)->nField;
34917     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
34918     pKeyInfo = sqlite3_malloc( nByte );
34919     pOp->p3 = (char*)pKeyInfo;
34920     if( pKeyInfo ){
34921       unsigned char *aSortOrder;
34922       memcpy(pKeyInfo, zP3, nByte);
34923       aSortOrder = pKeyInfo->aSortOrder;
34924       if( aSortOrder ){
34925         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
34926         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
34927       }
34928       pOp->p3type = P3_KEYINFO;
34929     }else{
34930       p->db->mallocFailed = 1;
34931       pOp->p3type = P3_NOTUSED;
34932     }
34933   }else if( n==P3_KEYINFO_HANDOFF ){
34934     pOp->p3 = (char*)zP3;
34935     pOp->p3type = P3_KEYINFO;
34936   }else if( n<0 ){
34937     pOp->p3 = (char*)zP3;
34938     pOp->p3type = n;
34939   }else{
34940     if( n==0 ) n = strlen(zP3);
34941     pOp->p3 = sqlite3DbStrNDup(p->db, zP3, n);
34942     pOp->p3type = P3_DYNAMIC;
34943   }
34944 }
34945
34946 #ifndef NDEBUG
34947 /*
34948 ** Replace the P3 field of the most recently coded instruction with
34949 ** comment text.
34950 */
34951 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
34952   va_list ap;
34953   assert( p->nOp>0 || p->aOp==0 );
34954   assert( p->aOp==0 || p->aOp[p->nOp-1].p3==0 || p->db->mallocFailed );
34955   va_start(ap, zFormat);
34956   sqlite3VdbeChangeP3(p, -1, sqlite3VMPrintf(p->db, zFormat, ap), P3_DYNAMIC);
34957   va_end(ap);
34958 }
34959 #endif
34960
34961 /*
34962 ** Return the opcode for a given address.
34963 */
34964 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
34965   assert( p->magic==VDBE_MAGIC_INIT );
34966   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
34967   return ((addr>=0 && addr<p->nOp)?(&p->aOp[addr]):0);
34968 }
34969
34970 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
34971      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
34972 /*
34973 ** Compute a string that describes the P3 parameter for an opcode.
34974 ** Use zTemp for any required temporary buffer space.
34975 */
34976 static char *displayP3(Op *pOp, char *zTemp, int nTemp){
34977   char *zP3;
34978   assert( nTemp>=20 );
34979   switch( pOp->p3type ){
34980     case P3_KEYINFO: {
34981       int i, j;
34982       KeyInfo *pKeyInfo = (KeyInfo*)pOp->p3;
34983       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
34984       i = strlen(zTemp);
34985       for(j=0; j<pKeyInfo->nField; j++){
34986         CollSeq *pColl = pKeyInfo->aColl[j];
34987         if( pColl ){
34988           int n = strlen(pColl->zName);
34989           if( i+n>nTemp-6 ){
34990             memcpy(&zTemp[i],",...",4);
34991             break;
34992           }
34993           zTemp[i++] = ',';
34994           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
34995             zTemp[i++] = '-';
34996           }
34997           memcpy(&zTemp[i], pColl->zName,n+1);
34998           i += n;
34999         }else if( i+4<nTemp-6 ){
35000           memcpy(&zTemp[i],",nil",4);
35001           i += 4;
35002         }
35003       }
35004       zTemp[i++] = ')';
35005       zTemp[i] = 0;
35006       assert( i<nTemp );
35007       zP3 = zTemp;
35008       break;
35009     }
35010     case P3_COLLSEQ: {
35011       CollSeq *pColl = (CollSeq*)pOp->p3;
35012       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
35013       zP3 = zTemp;
35014       break;
35015     }
35016     case P3_FUNCDEF: {
35017       FuncDef *pDef = (FuncDef*)pOp->p3;
35018       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
35019       zP3 = zTemp;
35020       break;
35021     }
35022     case P3_INT64: {
35023       sqlite3_snprintf(nTemp, zTemp, "%lld", *(sqlite3_int64*)pOp->p3);
35024       zP3 = zTemp;
35025       break;
35026     }
35027     case P3_REAL: {
35028       sqlite3_snprintf(nTemp, zTemp, "%.16g", *(double*)pOp->p3);
35029       zP3 = zTemp;
35030       break;
35031     }
35032 #ifndef SQLITE_OMIT_VIRTUALTABLE
35033     case P3_VTAB: {
35034       sqlite3_vtab *pVtab = (sqlite3_vtab*)pOp->p3;
35035       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
35036       zP3 = zTemp;
35037       break;
35038     }
35039 #endif
35040     default: {
35041       zP3 = pOp->p3;
35042       if( zP3==0 || pOp->opcode==OP_Noop ){
35043         zP3 = "";
35044       }
35045     }
35046   }
35047   assert( zP3!=0 );
35048   return zP3;
35049 }
35050 #endif
35051
35052 /*
35053 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
35054 **
35055 */
35056 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
35057   int mask;
35058   assert( i>=0 && i<p->db->nDb );
35059   assert( i<sizeof(p->btreeMask)*8 );
35060   mask = 1<<i;
35061   if( (p->btreeMask & mask)==0 ){
35062     p->btreeMask |= mask;
35063     sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
35064   }
35065 }
35066
35067
35068 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
35069 /*
35070 ** Print a single opcode.  This routine is used for debugging only.
35071 */
35072 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
35073   char *zP3;
35074   char zPtr[50];
35075   static const char *zFormat1 = "%4d %-13s %4d %4d %s\n";
35076   if( pOut==0 ) pOut = stdout;
35077   zP3 = displayP3(pOp, zPtr, sizeof(zPtr));
35078   fprintf(pOut, zFormat1,
35079       pc, sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, zP3);
35080   fflush(pOut);
35081 }
35082 #endif
35083
35084 /*
35085 ** Release an array of N Mem elements
35086 */
35087 static void releaseMemArray(Mem *p, int N){
35088   if( p ){
35089     while( N-->0 ){
35090       assert( N<2 || p[0].db==p[1].db );
35091       sqlite3VdbeMemRelease(p++);
35092     }
35093   }
35094 }
35095
35096 #ifndef SQLITE_OMIT_EXPLAIN
35097 /*
35098 ** Give a listing of the program in the virtual machine.
35099 **
35100 ** The interface is the same as sqlite3VdbeExec().  But instead of
35101 ** running the code, it invokes the callback once for each instruction.
35102 ** This feature is used to implement "EXPLAIN".
35103 */
35104 SQLITE_PRIVATE int sqlite3VdbeList(
35105   Vdbe *p                   /* The VDBE */
35106 ){
35107   sqlite3 *db = p->db;
35108   int i;
35109   int rc = SQLITE_OK;
35110
35111   assert( p->explain );
35112   if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
35113   assert( db->magic==SQLITE_MAGIC_BUSY );
35114   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
35115
35116   /* Even though this opcode does not put dynamic strings onto the
35117   ** the stack, they may become dynamic if the user calls
35118   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
35119   */
35120   if( p->pTos==&p->aStack[4] ){
35121     releaseMemArray(p->aStack, 5);
35122   }
35123   p->resOnStack = 0;
35124
35125   do{
35126     i = p->pc++;
35127   }while( i<p->nOp && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
35128   if( i>=p->nOp ){
35129     p->rc = SQLITE_OK;
35130     rc = SQLITE_DONE;
35131   }else if( db->u1.isInterrupted ){
35132     p->rc = SQLITE_INTERRUPT;
35133     rc = SQLITE_ERROR;
35134     sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(p->rc), (char*)0);
35135   }else{
35136     Op *pOp = &p->aOp[i];
35137     Mem *pMem = p->aStack;
35138     pMem->flags = MEM_Int;
35139     pMem->type = SQLITE_INTEGER;
35140     pMem->u.i = i;                                /* Program counter */
35141     pMem++;
35142
35143     pMem->flags = MEM_Static|MEM_Str|MEM_Term;
35144     pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
35145     assert( pMem->z!=0 );
35146     pMem->n = strlen(pMem->z);
35147     pMem->type = SQLITE_TEXT;
35148     pMem->enc = SQLITE_UTF8;
35149     pMem++;
35150
35151     pMem->flags = MEM_Int;
35152     pMem->u.i = pOp->p1;                          /* P1 */
35153     pMem->type = SQLITE_INTEGER;
35154     pMem++;
35155
35156     pMem->flags = MEM_Int;
35157     pMem->u.i = pOp->p2;                          /* P2 */
35158     pMem->type = SQLITE_INTEGER;
35159     pMem++;
35160
35161     pMem->flags = MEM_Ephem|MEM_Str|MEM_Term;   /* P3 */
35162     pMem->z = displayP3(pOp, pMem->zShort, sizeof(pMem->zShort));
35163     assert( pMem->z!=0 );
35164     pMem->n = strlen(pMem->z);
35165     pMem->type = SQLITE_TEXT;
35166     pMem->enc = SQLITE_UTF8;
35167
35168     p->nResColumn = 5 - 2*(p->explain-1);
35169     p->pTos = pMem;
35170     p->rc = SQLITE_OK;
35171     p->resOnStack = 1;
35172     rc = SQLITE_ROW;
35173   }
35174   return rc;
35175 }
35176 #endif /* SQLITE_OMIT_EXPLAIN */
35177
35178 #ifdef SQLITE_DEBUG
35179 /*
35180 ** Print the SQL that was used to generate a VDBE program.
35181 */
35182 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
35183   int nOp = p->nOp;
35184   VdbeOp *pOp;
35185   if( nOp<1 ) return;
35186   pOp = &p->aOp[nOp-1];
35187   if( pOp->opcode==OP_Noop && pOp->p3!=0 ){
35188     const char *z = pOp->p3;
35189     while( isspace(*(u8*)z) ) z++;
35190     printf("SQL: [%s]\n", z);
35191   }
35192 }
35193 #endif
35194
35195 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
35196 /*
35197 ** Print an IOTRACE message showing SQL content.
35198 */
35199 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
35200   int nOp = p->nOp;
35201   VdbeOp *pOp;
35202   if( sqlite3_io_trace==0 ) return;
35203   if( nOp<1 ) return;
35204   pOp = &p->aOp[nOp-1];
35205   if( pOp->opcode==OP_Noop && pOp->p3!=0 ){
35206     int i, j;
35207     char z[1000];
35208     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p3);
35209     for(i=0; isspace((unsigned char)z[i]); i++){}
35210     for(j=0; z[i]; i++){
35211       if( isspace((unsigned char)z[i]) ){
35212         if( z[i-1]!=' ' ){
35213           z[j++] = ' ';
35214         }
35215       }else{
35216         z[j++] = z[i];
35217       }
35218     }
35219     z[j] = 0;
35220     sqlite3_io_trace("SQL %s\n", z);
35221   }
35222 }
35223 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
35224
35225
35226 /*
35227 ** Prepare a virtual machine for execution.  This involves things such
35228 ** as allocating stack space and initializing the program counter.
35229 ** After the VDBE has be prepped, it can be executed by one or more
35230 ** calls to sqlite3VdbeExec().  
35231 **
35232 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
35233 ** VDBE_MAGIC_RUN.
35234 */
35235 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
35236   Vdbe *p,                       /* The VDBE */
35237   int nVar,                      /* Number of '?' see in the SQL statement */
35238   int nMem,                      /* Number of memory cells to allocate */
35239   int nCursor,                   /* Number of cursors to allocate */
35240   int isExplain                  /* True if the EXPLAIN keywords is present */
35241 ){
35242   int n;
35243   sqlite3 *db = p->db;
35244
35245   assert( p!=0 );
35246   assert( p->magic==VDBE_MAGIC_INIT );
35247
35248   /* There should be at least one opcode.
35249   */
35250   assert( p->nOp>0 );
35251
35252   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. This
35253    * is because the call to resizeOpArray() below may shrink the
35254    * p->aOp[] array to save memory if called when in VDBE_MAGIC_RUN 
35255    * state.
35256    */
35257   p->magic = VDBE_MAGIC_RUN;
35258
35259   /* No instruction ever pushes more than a single element onto the
35260   ** stack.  And the stack never grows on successive executions of the
35261   ** same loop.  So the total number of instructions is an upper bound
35262   ** on the maximum stack depth required.  (Added later:)  The
35263   ** resolveP2Values() call computes a tighter upper bound on the
35264   ** stack size.
35265   **
35266   ** Allocation all the stack space we will ever need.
35267   */
35268   if( p->aStack==0 ){
35269     int nArg;       /* Maximum number of args passed to a user function. */
35270     int nStack;     /* Maximum number of stack entries required */
35271     resolveP2Values(p, &nArg, &nStack);
35272     resizeOpArray(p, p->nOp);
35273     assert( nVar>=0 );
35274     assert( nStack<p->nOp );
35275     if( isExplain ){
35276       nStack = 10;
35277     }
35278     p->aStack = sqlite3DbMallocZero(db,
35279         nStack*sizeof(p->aStack[0])    /* aStack */
35280       + nArg*sizeof(Mem*)              /* apArg */
35281       + nVar*sizeof(Mem)               /* aVar */
35282       + nVar*sizeof(char*)             /* azVar */
35283       + nMem*sizeof(Mem)               /* aMem */
35284       + nCursor*sizeof(Cursor*)        /* apCsr */
35285     );
35286     if( !db->mallocFailed ){
35287       p->aMem = &p->aStack[nStack];
35288       p->nMem = nMem;
35289       p->aVar = &p->aMem[nMem];
35290       p->nVar = nVar;
35291       p->okVar = 0;
35292       p->apArg = (Mem**)&p->aVar[nVar];
35293       p->azVar = (char**)&p->apArg[nArg];
35294       p->apCsr = (Cursor**)&p->azVar[nVar];
35295       p->nCursor = nCursor;
35296       for(n=0; n<nVar; n++){
35297         p->aVar[n].flags = MEM_Null;
35298         p->aVar[n].db = db;
35299       }
35300       for(n=0; n<nStack; n++){
35301         p->aStack[n].db = db;
35302       }
35303     }
35304   }
35305   for(n=0; n<p->nMem; n++){
35306     p->aMem[n].flags = MEM_Null;
35307     p->aMem[n].db = db;
35308   }
35309
35310   p->pTos = &p->aStack[-1];
35311   p->pc = -1;
35312   p->rc = SQLITE_OK;
35313   p->uniqueCnt = 0;
35314   p->returnDepth = 0;
35315   p->errorAction = OE_Abort;
35316   p->popStack =  0;
35317   p->explain |= isExplain;
35318   p->magic = VDBE_MAGIC_RUN;
35319   p->nChange = 0;
35320   p->cacheCtr = 1;
35321   p->minWriteFileFormat = 255;
35322   p->openedStatement = 0;
35323 #ifdef VDBE_PROFILE
35324   {
35325     int i;
35326     for(i=0; i<p->nOp; i++){
35327       p->aOp[i].cnt = 0;
35328       p->aOp[i].cycles = 0;
35329     }
35330   }
35331 #endif
35332 }
35333
35334 /*
35335 ** Close a VDBE cursor and release all the resources that cursor happens
35336 ** to hold.
35337 */
35338 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, Cursor *pCx){
35339   if( pCx==0 ){
35340     return;
35341   }
35342   if( pCx->pCursor ){
35343     sqlite3BtreeCloseCursor(pCx->pCursor);
35344   }
35345   if( pCx->pBt ){
35346     sqlite3BtreeClose(pCx->pBt);
35347   }
35348 #ifndef SQLITE_OMIT_VIRTUALTABLE
35349   if( pCx->pVtabCursor ){
35350     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
35351     const sqlite3_module *pModule = pCx->pModule;
35352     p->inVtabMethod = 1;
35353     sqlite3SafetyOff(p->db);
35354     pModule->xClose(pVtabCursor);
35355     sqlite3SafetyOn(p->db);
35356     p->inVtabMethod = 0;
35357   }
35358 #endif
35359   sqlite3_free(pCx->pData);
35360   sqlite3_free(pCx->aType);
35361   sqlite3_free(pCx);
35362 }
35363
35364 /*
35365 ** Close all cursors except for VTab cursors that are currently
35366 ** in use.
35367 */
35368 static void closeAllCursorsExceptActiveVtabs(Vdbe *p){
35369   int i;
35370   if( p->apCsr==0 ) return;
35371   for(i=0; i<p->nCursor; i++){
35372     Cursor *pC = p->apCsr[i];
35373     if( pC && (!p->inVtabMethod || !pC->pVtabCursor) ){
35374       sqlite3VdbeFreeCursor(p, pC);
35375       p->apCsr[i] = 0;
35376     }
35377   }
35378 }
35379
35380 /*
35381 ** Clean up the VM after execution.
35382 **
35383 ** This routine will automatically close any cursors, lists, and/or
35384 ** sorters that were left open.  It also deletes the values of
35385 ** variables in the aVar[] array.
35386 */
35387 static void Cleanup(Vdbe *p){
35388   int i;
35389   if( p->aStack ){
35390     releaseMemArray(p->aStack, 1 + (p->pTos - p->aStack));
35391     p->pTos = &p->aStack[-1];
35392   }
35393   closeAllCursorsExceptActiveVtabs(p);
35394   releaseMemArray(p->aMem, p->nMem);
35395   sqlite3VdbeFifoClear(&p->sFifo);
35396   if( p->contextStack ){
35397     for(i=0; i<p->contextStackTop; i++){
35398       sqlite3VdbeFifoClear(&p->contextStack[i].sFifo);
35399     }
35400     sqlite3_free(p->contextStack);
35401   }
35402   p->contextStack = 0;
35403   p->contextStackDepth = 0;
35404   p->contextStackTop = 0;
35405   sqlite3_free(p->zErrMsg);
35406   p->zErrMsg = 0;
35407   p->resOnStack = 0;
35408 }
35409
35410 /*
35411 ** Set the number of result columns that will be returned by this SQL
35412 ** statement. This is now set at compile time, rather than during
35413 ** execution of the vdbe program so that sqlite3_column_count() can
35414 ** be called on an SQL statement before sqlite3_step().
35415 */
35416 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
35417   Mem *pColName;
35418   int n;
35419
35420   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
35421   sqlite3_free(p->aColName);
35422   n = nResColumn*COLNAME_N;
35423   p->nResColumn = nResColumn;
35424   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(p->db, sizeof(Mem)*n );
35425   if( p->aColName==0 ) return;
35426   while( n-- > 0 ){
35427     pColName->flags = MEM_Null;
35428     pColName->db = p->db;
35429     pColName++;
35430   }
35431 }
35432
35433 /*
35434 ** Set the name of the idx'th column to be returned by the SQL statement.
35435 ** zName must be a pointer to a nul terminated string.
35436 **
35437 ** This call must be made after a call to sqlite3VdbeSetNumCols().
35438 **
35439 ** If N==P3_STATIC  it means that zName is a pointer to a constant static
35440 ** string and we can just copy the pointer. If it is P3_DYNAMIC, then 
35441 ** the string is freed using sqlite3_free() when the vdbe is finished with
35442 ** it. Otherwise, N bytes of zName are copied.
35443 */
35444 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe *p, int idx, int var, const char *zName, int N){
35445   int rc;
35446   Mem *pColName;
35447   assert( idx<p->nResColumn );
35448   assert( var<COLNAME_N );
35449   if( p->db->mallocFailed ) return SQLITE_NOMEM;
35450   assert( p->aColName!=0 );
35451   pColName = &(p->aColName[idx+var*p->nResColumn]);
35452   if( N==P3_DYNAMIC || N==P3_STATIC ){
35453     rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, SQLITE_STATIC);
35454   }else{
35455     rc = sqlite3VdbeMemSetStr(pColName, zName, N, SQLITE_UTF8,SQLITE_TRANSIENT);
35456   }
35457   if( rc==SQLITE_OK && N==P3_DYNAMIC ){
35458     pColName->flags = (pColName->flags&(~MEM_Static))|MEM_Dyn;
35459     pColName->xDel = 0;
35460   }
35461   return rc;
35462 }
35463
35464 /*
35465 ** A read or write transaction may or may not be active on database handle
35466 ** db. If a transaction is active, commit it. If there is a
35467 ** write-transaction spanning more than one database file, this routine
35468 ** takes care of the master journal trickery.
35469 */
35470 static int vdbeCommit(sqlite3 *db){
35471   int i;
35472   int nTrans = 0;  /* Number of databases with an active write-transaction */
35473   int rc = SQLITE_OK;
35474   int needXcommit = 0;
35475
35476   /* Before doing anything else, call the xSync() callback for any
35477   ** virtual module tables written in this transaction. This has to
35478   ** be done before determining whether a master journal file is 
35479   ** required, as an xSync() callback may add an attached database
35480   ** to the transaction.
35481   */
35482   rc = sqlite3VtabSync(db, rc);
35483   if( rc!=SQLITE_OK ){
35484     return rc;
35485   }
35486
35487   /* This loop determines (a) if the commit hook should be invoked and
35488   ** (b) how many database files have open write transactions, not 
35489   ** including the temp database. (b) is important because if more than 
35490   ** one database file has an open write transaction, a master journal
35491   ** file is required for an atomic commit.
35492   */ 
35493   for(i=0; i<db->nDb; i++){ 
35494     Btree *pBt = db->aDb[i].pBt;
35495     if( sqlite3BtreeIsInTrans(pBt) ){
35496       needXcommit = 1;
35497       if( i!=1 ) nTrans++;
35498     }
35499   }
35500
35501   /* If there are any write-transactions at all, invoke the commit hook */
35502   if( needXcommit && db->xCommitCallback ){
35503     sqlite3SafetyOff(db);
35504     rc = db->xCommitCallback(db->pCommitArg);
35505     sqlite3SafetyOn(db);
35506     if( rc ){
35507       return SQLITE_CONSTRAINT;
35508     }
35509   }
35510
35511   /* The simple case - no more than one database file (not counting the
35512   ** TEMP database) has a transaction active.   There is no need for the
35513   ** master-journal.
35514   **
35515   ** If the return value of sqlite3BtreeGetFilename() is a zero length
35516   ** string, it means the main database is :memory:.  In that case we do
35517   ** not support atomic multi-file commits, so use the simple case then
35518   ** too.
35519   */
35520   if( 0==strlen(sqlite3BtreeGetFilename(db->aDb[0].pBt)) || nTrans<=1 ){
35521     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
35522       Btree *pBt = db->aDb[i].pBt;
35523       if( pBt ){
35524         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
35525       }
35526     }
35527
35528     /* Do the commit only if all databases successfully complete phase 1. 
35529     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
35530     ** IO error while deleting or truncating a journal file. It is unlikely,
35531     ** but could happen. In this case abandon processing and return the error.
35532     */
35533     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
35534       Btree *pBt = db->aDb[i].pBt;
35535       if( pBt ){
35536         rc = sqlite3BtreeCommitPhaseTwo(pBt);
35537       }
35538     }
35539     if( rc==SQLITE_OK ){
35540       sqlite3VtabCommit(db);
35541     }
35542   }
35543
35544   /* The complex case - There is a multi-file write-transaction active.
35545   ** This requires a master journal file to ensure the transaction is
35546   ** committed atomicly.
35547   */
35548 #ifndef SQLITE_OMIT_DISKIO
35549   else{
35550     sqlite3_vfs *pVfs = db->pVfs;
35551     int needSync = 0;
35552     char *zMaster = 0;   /* File-name for the master journal */
35553     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
35554     sqlite3_file *pMaster = 0;
35555     i64 offset = 0;
35556
35557     /* Select a master journal file name */
35558     do {
35559       u32 random;
35560       sqlite3_free(zMaster);
35561       sqlite3Randomness(sizeof(random), &random);
35562       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, random&0x7fffffff);
35563       if( !zMaster ){
35564         return SQLITE_NOMEM;
35565       }
35566     }while( sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS) );
35567
35568     /* Open the master journal. */
35569     rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
35570         SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
35571         SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
35572     );
35573     if( rc!=SQLITE_OK ){
35574       sqlite3_free(zMaster);
35575       return rc;
35576     }
35577  
35578     /* Write the name of each database file in the transaction into the new
35579     ** master journal file. If an error occurs at this point close
35580     ** and delete the master journal file. All the individual journal files
35581     ** still have 'null' as the master journal pointer, so they will roll
35582     ** back independently if a failure occurs.
35583     */
35584     for(i=0; i<db->nDb; i++){
35585       Btree *pBt = db->aDb[i].pBt;
35586       if( i==1 ) continue;   /* Ignore the TEMP database */
35587       if( sqlite3BtreeIsInTrans(pBt) ){
35588         char const *zFile = sqlite3BtreeGetJournalname(pBt);
35589         if( zFile[0]==0 ) continue;  /* Ignore :memory: databases */
35590         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
35591           needSync = 1;
35592         }
35593         rc = sqlite3OsWrite(pMaster, zFile, strlen(zFile)+1, offset);
35594         offset += strlen(zFile)+1;
35595         if( rc!=SQLITE_OK ){
35596           sqlite3OsCloseFree(pMaster);
35597           sqlite3OsDelete(pVfs, zMaster, 0);
35598           sqlite3_free(zMaster);
35599           return rc;
35600         }
35601       }
35602     }
35603
35604     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
35605     ** flag is set this is not required.
35606     */
35607     zMainFile = sqlite3BtreeGetDirname(db->aDb[0].pBt);
35608     if( (needSync 
35609      && (0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL))
35610      && (rc=sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))!=SQLITE_OK) ){
35611       sqlite3OsCloseFree(pMaster);
35612       sqlite3OsDelete(pVfs, zMaster, 0);
35613       sqlite3_free(zMaster);
35614       return rc;
35615     }
35616
35617     /* Sync all the db files involved in the transaction. The same call
35618     ** sets the master journal pointer in each individual journal. If
35619     ** an error occurs here, do not delete the master journal file.
35620     **
35621     ** If the error occurs during the first call to
35622     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
35623     ** master journal file will be orphaned. But we cannot delete it,
35624     ** in case the master journal file name was written into the journal
35625     ** file before the failure occured.
35626     */
35627     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
35628       Btree *pBt = db->aDb[i].pBt;
35629       if( pBt ){
35630         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
35631       }
35632     }
35633     sqlite3OsCloseFree(pMaster);
35634     if( rc!=SQLITE_OK ){
35635       sqlite3_free(zMaster);
35636       return rc;
35637     }
35638
35639     /* Delete the master journal file. This commits the transaction. After
35640     ** doing this the directory is synced again before any individual
35641     ** transaction files are deleted.
35642     */
35643     rc = sqlite3OsDelete(pVfs, zMaster, 1);
35644     sqlite3_free(zMaster);
35645     zMaster = 0;
35646     if( rc ){
35647       return rc;
35648     }
35649
35650     /* All files and directories have already been synced, so the following
35651     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
35652     ** deleting or truncating journals. If something goes wrong while
35653     ** this is happening we don't really care. The integrity of the
35654     ** transaction is already guaranteed, but some stray 'cold' journals
35655     ** may be lying around. Returning an error code won't help matters.
35656     */
35657     disable_simulated_io_errors();
35658     for(i=0; i<db->nDb; i++){ 
35659       Btree *pBt = db->aDb[i].pBt;
35660       if( pBt ){
35661         sqlite3BtreeCommitPhaseTwo(pBt);
35662       }
35663     }
35664     enable_simulated_io_errors();
35665
35666     sqlite3VtabCommit(db);
35667   }
35668 #endif
35669
35670   return rc;
35671 }
35672
35673 /* 
35674 ** This routine checks that the sqlite3.activeVdbeCnt count variable
35675 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
35676 ** currently active. An assertion fails if the two counts do not match.
35677 ** This is an internal self-check only - it is not an essential processing
35678 ** step.
35679 **
35680 ** This is a no-op if NDEBUG is defined.
35681 */
35682 #ifndef NDEBUG
35683 static void checkActiveVdbeCnt(sqlite3 *db){
35684   Vdbe *p;
35685   int cnt = 0;
35686   p = db->pVdbe;
35687   while( p ){
35688     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
35689       cnt++;
35690     }
35691     p = p->pNext;
35692   }
35693   assert( cnt==db->activeVdbeCnt );
35694 }
35695 #else
35696 #define checkActiveVdbeCnt(x)
35697 #endif
35698
35699 /*
35700 ** For every Btree that in database connection db which 
35701 ** has been modified, "trip" or invalidate each cursor in
35702 ** that Btree might have been modified so that the cursor
35703 ** can never be used again.  This happens when a rollback
35704 *** occurs.  We have to trip all the other cursors, even
35705 ** cursor from other VMs in different database connections,
35706 ** so that none of them try to use the data at which they
35707 ** were pointing and which now may have been changed due
35708 ** to the rollback.
35709 **
35710 ** Remember that a rollback can delete tables complete and
35711 ** reorder rootpages.  So it is not sufficient just to save
35712 ** the state of the cursor.  We have to invalidate the cursor
35713 ** so that it is never used again.
35714 */
35715 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
35716   int i;
35717   for(i=0; i<db->nDb; i++){
35718     Btree *p = db->aDb[i].pBt;
35719     if( p && sqlite3BtreeIsInTrans(p) ){
35720       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
35721     }
35722   }
35723 }
35724
35725 /*
35726 ** This routine is called the when a VDBE tries to halt.  If the VDBE
35727 ** has made changes and is in autocommit mode, then commit those
35728 ** changes.  If a rollback is needed, then do the rollback.
35729 **
35730 ** This routine is the only way to move the state of a VM from
35731 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
35732 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
35733 **
35734 ** Return an error code.  If the commit could not complete because of
35735 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
35736 ** means the close did not happen and needs to be repeated.
35737 */
35738 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
35739   sqlite3 *db = p->db;
35740   int i;
35741   int (*xFunc)(Btree *pBt) = 0;  /* Function to call on each btree backend */
35742   int isSpecialError;            /* Set to true if SQLITE_NOMEM or IOERR */
35743
35744   /* This function contains the logic that determines if a statement or
35745   ** transaction will be committed or rolled back as a result of the
35746   ** execution of this virtual machine. 
35747   **
35748   ** If any of the following errors occur:
35749   **
35750   **     SQLITE_NOMEM
35751   **     SQLITE_IOERR
35752   **     SQLITE_FULL
35753   **     SQLITE_INTERRUPT
35754   **
35755   ** Then the internal cache might have been left in an inconsistent
35756   ** state.  We need to rollback the statement transaction, if there is
35757   ** one, or the complete transaction if there is no statement transaction.
35758   */
35759
35760   if( p->db->mallocFailed ){
35761     p->rc = SQLITE_NOMEM;
35762   }
35763   closeAllCursorsExceptActiveVtabs(p);
35764   if( p->magic!=VDBE_MAGIC_RUN ){
35765     return SQLITE_OK;
35766   }
35767   checkActiveVdbeCnt(db);
35768
35769   /* No commit or rollback needed if the program never started */
35770   if( p->pc>=0 ){
35771     int mrc;   /* Primary error code from p->rc */
35772
35773     /* Lock all btrees used by the statement */
35774     sqlite3BtreeMutexArrayEnter(&p->aMutex);
35775
35776     /* Check for one of the special errors */
35777     mrc = p->rc & 0xff;
35778     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
35779                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
35780     if( isSpecialError ){
35781       /* This loop does static analysis of the query to see which of the
35782       ** following three categories it falls into:
35783       **
35784       **     Read-only
35785       **     Query with statement journal
35786       **     Query without statement journal
35787       **
35788       ** We could do something more elegant than this static analysis (i.e.
35789       ** store the type of query as part of the compliation phase), but 
35790       ** handling malloc() or IO failure is a fairly obscure edge case so 
35791       ** this is probably easier. Todo: Might be an opportunity to reduce 
35792       ** code size a very small amount though...
35793       */
35794       int notReadOnly = 0;
35795       int isStatement = 0;
35796       assert(p->aOp || p->nOp==0);
35797       for(i=0; i<p->nOp; i++){ 
35798         switch( p->aOp[i].opcode ){
35799           case OP_Transaction:
35800             notReadOnly |= p->aOp[i].p2;
35801             break;
35802           case OP_Statement:
35803             isStatement = 1;
35804             break;
35805         }
35806       }
35807
35808    
35809       /* If the query was read-only, we need do no rollback at all. Otherwise,
35810       ** proceed with the special handling.
35811       */
35812       if( notReadOnly || mrc!=SQLITE_INTERRUPT ){
35813         if( p->rc==SQLITE_IOERR_BLOCKED && isStatement ){
35814           xFunc = sqlite3BtreeRollbackStmt;
35815           p->rc = SQLITE_BUSY;
35816         } else if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && isStatement ){
35817           xFunc = sqlite3BtreeRollbackStmt;
35818         }else{
35819           /* We are forced to roll back the active transaction. Before doing
35820           ** so, abort any other statements this handle currently has active.
35821           */
35822           invalidateCursorsOnModifiedBtrees(db);
35823           sqlite3RollbackAll(db);
35824           db->autoCommit = 1;
35825         }
35826       }
35827     }
35828   
35829     /* If the auto-commit flag is set and this is the only active vdbe, then
35830     ** we do either a commit or rollback of the current transaction. 
35831     **
35832     ** Note: This block also runs if one of the special errors handled 
35833     ** above has occured. 
35834     */
35835     if( db->autoCommit && db->activeVdbeCnt==1 ){
35836       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
35837         /* The auto-commit flag is true, and the vdbe program was 
35838         ** successful or hit an 'OR FAIL' constraint. This means a commit 
35839         ** is required.
35840         */
35841         int rc = vdbeCommit(db);
35842         if( rc==SQLITE_BUSY ){
35843           sqlite3BtreeMutexArrayLeave(&p->aMutex);
35844           return SQLITE_BUSY;
35845         }else if( rc!=SQLITE_OK ){
35846           p->rc = rc;
35847           sqlite3RollbackAll(db);
35848         }else{
35849           sqlite3CommitInternalChanges(db);
35850         }
35851       }else{
35852         sqlite3RollbackAll(db);
35853       }
35854     }else if( !xFunc ){
35855       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
35856         if( p->openedStatement ){
35857           xFunc = sqlite3BtreeCommitStmt;
35858         } 
35859       }else if( p->errorAction==OE_Abort ){
35860         xFunc = sqlite3BtreeRollbackStmt;
35861       }else{
35862         invalidateCursorsOnModifiedBtrees(db);
35863         sqlite3RollbackAll(db);
35864         db->autoCommit = 1;
35865       }
35866     }
35867   
35868     /* If xFunc is not NULL, then it is one of sqlite3BtreeRollbackStmt or
35869     ** sqlite3BtreeCommitStmt. Call it once on each backend. If an error occurs
35870     ** and the return code is still SQLITE_OK, set the return code to the new
35871     ** error value.
35872     */
35873     assert(!xFunc ||
35874       xFunc==sqlite3BtreeCommitStmt ||
35875       xFunc==sqlite3BtreeRollbackStmt
35876     );
35877     for(i=0; xFunc && i<db->nDb; i++){ 
35878       int rc;
35879       Btree *pBt = db->aDb[i].pBt;
35880       if( pBt ){
35881         rc = xFunc(pBt);
35882         if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
35883           p->rc = rc;
35884           sqlite3SetString(&p->zErrMsg, 0);
35885         }
35886       }
35887     }
35888   
35889     /* If this was an INSERT, UPDATE or DELETE and the statement was committed, 
35890     ** set the change counter. 
35891     */
35892     if( p->changeCntOn && p->pc>=0 ){
35893       if( !xFunc || xFunc==sqlite3BtreeCommitStmt ){
35894         sqlite3VdbeSetChanges(db, p->nChange);
35895       }else{
35896         sqlite3VdbeSetChanges(db, 0);
35897       }
35898       p->nChange = 0;
35899     }
35900   
35901     /* Rollback or commit any schema changes that occurred. */
35902     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
35903       sqlite3ResetInternalSchema(db, 0);
35904       db->flags = (db->flags | SQLITE_InternChanges);
35905     }
35906
35907     /* Release the locks */
35908     sqlite3BtreeMutexArrayLeave(&p->aMutex);
35909   }
35910
35911   /* We have successfully halted and closed the VM.  Record this fact. */
35912   if( p->pc>=0 ){
35913     db->activeVdbeCnt--;
35914   }
35915   p->magic = VDBE_MAGIC_HALT;
35916   checkActiveVdbeCnt(db);
35917   if( p->db->mallocFailed ){
35918     p->rc = SQLITE_NOMEM;
35919   }
35920   checkActiveVdbeCnt(db);
35921
35922   return SQLITE_OK;
35923 }
35924
35925
35926 /*
35927 ** Each VDBE holds the result of the most recent sqlite3_step() call
35928 ** in p->rc.  This routine sets that result back to SQLITE_OK.
35929 */
35930 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
35931   p->rc = SQLITE_OK;
35932 }
35933
35934 /*
35935 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
35936 ** Write any error messages into *pzErrMsg.  Return the result code.
35937 **
35938 ** After this routine is run, the VDBE should be ready to be executed
35939 ** again.
35940 **
35941 ** To look at it another way, this routine resets the state of the
35942 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
35943 ** VDBE_MAGIC_INIT.
35944 */
35945 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
35946   sqlite3 *db;
35947   db = p->db;
35948
35949   /* If the VM did not run to completion or if it encountered an
35950   ** error, then it might not have been halted properly.  So halt
35951   ** it now.
35952   */
35953   sqlite3SafetyOn(db);
35954   sqlite3VdbeHalt(p);
35955   sqlite3SafetyOff(db);
35956
35957   /* If the VDBE has be run even partially, then transfer the error code
35958   ** and error message from the VDBE into the main database structure.  But
35959   ** if the VDBE has just been set to run but has not actually executed any
35960   ** instructions yet, leave the main database error information unchanged.
35961   */
35962   if( p->pc>=0 ){
35963     if( p->zErrMsg ){
35964       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,sqlite3_free);
35965       db->errCode = p->rc;
35966       p->zErrMsg = 0;
35967     }else if( p->rc ){
35968       sqlite3Error(db, p->rc, 0);
35969     }else{
35970       sqlite3Error(db, SQLITE_OK, 0);
35971     }
35972   }else if( p->rc && p->expired ){
35973     /* The expired flag was set on the VDBE before the first call
35974     ** to sqlite3_step(). For consistency (since sqlite3_step() was
35975     ** called), set the database error in this case as well.
35976     */
35977     sqlite3Error(db, p->rc, 0);
35978     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, sqlite3_free);
35979     p->zErrMsg = 0;
35980   }
35981
35982   /* Reclaim all memory used by the VDBE
35983   */
35984   Cleanup(p);
35985
35986   /* Save profiling information from this VDBE run.
35987   */
35988   assert( p->pTos<&p->aStack[p->pc<0?0:p->pc] || !p->aStack );
35989 #ifdef VDBE_PROFILE
35990   {
35991     FILE *out = fopen("vdbe_profile.out", "a");
35992     if( out ){
35993       int i;
35994       fprintf(out, "---- ");
35995       for(i=0; i<p->nOp; i++){
35996         fprintf(out, "%02x", p->aOp[i].opcode);
35997       }
35998       fprintf(out, "\n");
35999       for(i=0; i<p->nOp; i++){
36000         fprintf(out, "%6d %10lld %8lld ",
36001            p->aOp[i].cnt,
36002            p->aOp[i].cycles,
36003            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
36004         );
36005         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
36006       }
36007       fclose(out);
36008     }
36009   }
36010 #endif
36011   p->magic = VDBE_MAGIC_INIT;
36012   p->aborted = 0;
36013   return p->rc & db->errMask;
36014 }
36015  
36016 /*
36017 ** Clean up and delete a VDBE after execution.  Return an integer which is
36018 ** the result code.  Write any error message text into *pzErrMsg.
36019 */
36020 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
36021   int rc = SQLITE_OK;
36022   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
36023     rc = sqlite3VdbeReset(p);
36024     assert( (rc & p->db->errMask)==rc );
36025   }else if( p->magic!=VDBE_MAGIC_INIT ){
36026     return SQLITE_MISUSE;
36027   }
36028   sqlite3VdbeDelete(p);
36029   return rc;
36030 }
36031
36032 /*
36033 ** Call the destructor for each auxdata entry in pVdbeFunc for which
36034 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
36035 ** are always destroyed.  To destroy all auxdata entries, call this
36036 ** routine with mask==0.
36037 */
36038 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
36039   int i;
36040   for(i=0; i<pVdbeFunc->nAux; i++){
36041     struct AuxData *pAux = &pVdbeFunc->apAux[i];
36042     if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
36043       if( pAux->xDelete ){
36044         pAux->xDelete(pAux->pAux);
36045       }
36046       pAux->pAux = 0;
36047     }
36048   }
36049 }
36050
36051 /*
36052 ** Delete an entire VDBE.
36053 */
36054 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
36055   int i;
36056   if( p==0 ) return;
36057   Cleanup(p);
36058   if( p->pPrev ){
36059     p->pPrev->pNext = p->pNext;
36060   }else{
36061     assert( p->db->pVdbe==p );
36062     p->db->pVdbe = p->pNext;
36063   }
36064   if( p->pNext ){
36065     p->pNext->pPrev = p->pPrev;
36066   }
36067   if( p->aOp ){
36068     for(i=0; i<p->nOp; i++){
36069       Op *pOp = &p->aOp[i];
36070       freeP3(pOp->p3type, pOp->p3);
36071     }
36072     sqlite3_free(p->aOp);
36073   }
36074   releaseMemArray(p->aVar, p->nVar);
36075   sqlite3_free(p->aLabel);
36076   sqlite3_free(p->aStack);
36077   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
36078   sqlite3_free(p->aColName);
36079   sqlite3_free(p->zSql);
36080   p->magic = VDBE_MAGIC_DEAD;
36081   sqlite3_free(p);
36082 }
36083
36084 /*
36085 ** If a MoveTo operation is pending on the given cursor, then do that
36086 ** MoveTo now.  Return an error code.  If no MoveTo is pending, this
36087 ** routine does nothing and returns SQLITE_OK.
36088 */
36089 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(Cursor *p){
36090   if( p->deferredMoveto ){
36091     int res, rc;
36092 #ifdef SQLITE_TEST
36093     extern int sqlite3_search_count;
36094 #endif
36095     assert( p->isTable );
36096     rc = sqlite3BtreeMoveto(p->pCursor, 0, p->movetoTarget, 0, &res);
36097     if( rc ) return rc;
36098     *p->pIncrKey = 0;
36099     p->lastRowid = keyToInt(p->movetoTarget);
36100     p->rowidIsValid = res==0;
36101     if( res<0 ){
36102       rc = sqlite3BtreeNext(p->pCursor, &res);
36103       if( rc ) return rc;
36104     }
36105 #ifdef SQLITE_TEST
36106     sqlite3_search_count++;
36107 #endif
36108     p->deferredMoveto = 0;
36109     p->cacheStatus = CACHE_STALE;
36110   }
36111   return SQLITE_OK;
36112 }
36113
36114 /*
36115 ** The following functions:
36116 **
36117 ** sqlite3VdbeSerialType()
36118 ** sqlite3VdbeSerialTypeLen()
36119 ** sqlite3VdbeSerialRead()
36120 ** sqlite3VdbeSerialLen()
36121 ** sqlite3VdbeSerialWrite()
36122 **
36123 ** encapsulate the code that serializes values for storage in SQLite
36124 ** data and index records. Each serialized value consists of a
36125 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
36126 ** integer, stored as a varint.
36127 **
36128 ** In an SQLite index record, the serial type is stored directly before
36129 ** the blob of data that it corresponds to. In a table record, all serial
36130 ** types are stored at the start of the record, and the blobs of data at
36131 ** the end. Hence these functions allow the caller to handle the
36132 ** serial-type and data blob seperately.
36133 **
36134 ** The following table describes the various storage classes for data:
36135 **
36136 **   serial type        bytes of data      type
36137 **   --------------     ---------------    ---------------
36138 **      0                     0            NULL
36139 **      1                     1            signed integer
36140 **      2                     2            signed integer
36141 **      3                     3            signed integer
36142 **      4                     4            signed integer
36143 **      5                     6            signed integer
36144 **      6                     8            signed integer
36145 **      7                     8            IEEE float
36146 **      8                     0            Integer constant 0
36147 **      9                     0            Integer constant 1
36148 **     10,11                               reserved for expansion
36149 **    N>=12 and even       (N-12)/2        BLOB
36150 **    N>=13 and odd        (N-13)/2        text
36151 **
36152 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
36153 ** of SQLite will not understand those serial types.
36154 */
36155
36156 /*
36157 ** Return the serial-type for the value stored in pMem.
36158 */
36159 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
36160   int flags = pMem->flags;
36161   int n;
36162
36163   if( flags&MEM_Null ){
36164     return 0;
36165   }
36166   if( flags&MEM_Int ){
36167     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
36168 #   define MAX_6BYTE ((((i64)0x00001000)<<32)-1)
36169     i64 i = pMem->u.i;
36170     u64 u;
36171     if( file_format>=4 && (i&1)==i ){
36172       return 8+i;
36173     }
36174     u = i<0 ? -i : i;
36175     if( u<=127 ) return 1;
36176     if( u<=32767 ) return 2;
36177     if( u<=8388607 ) return 3;
36178     if( u<=2147483647 ) return 4;
36179     if( u<=MAX_6BYTE ) return 5;
36180     return 6;
36181   }
36182   if( flags&MEM_Real ){
36183     return 7;
36184   }
36185   assert( flags&(MEM_Str|MEM_Blob) );
36186   n = pMem->n;
36187   if( flags & MEM_Zero ){
36188     n += pMem->u.i;
36189   }
36190   assert( n>=0 );
36191   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
36192 }
36193
36194 /*
36195 ** Return the length of the data corresponding to the supplied serial-type.
36196 */
36197 SQLITE_PRIVATE int sqlite3VdbeSerialTypeLen(u32 serial_type){
36198   if( serial_type>=12 ){
36199     return (serial_type-12)/2;
36200   }else{
36201     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
36202     return aSize[serial_type];
36203   }
36204 }
36205
36206 /*
36207 ** If we are on an architecture with mixed-endian floating 
36208 ** points (ex: ARM7) then swap the lower 4 bytes with the 
36209 ** upper 4 bytes.  Return the result.
36210 **
36211 ** For most architectures, this is a no-op.
36212 **
36213 ** (later):  It is reported to me that the mixed-endian problem
36214 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
36215 ** that early versions of GCC stored the two words of a 64-bit
36216 ** float in the wrong order.  And that error has been propagated
36217 ** ever since.  The blame is not necessarily with GCC, though.
36218 ** GCC might have just copying the problem from a prior compiler.
36219 ** I am also told that newer versions of GCC that follow a different
36220 ** ABI get the byte order right.
36221 **
36222 ** Developers using SQLite on an ARM7 should compile and run their
36223 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
36224 ** enabled, some asserts below will ensure that the byte order of
36225 ** floating point values is correct.
36226 **
36227 ** (2007-08-30)  Frank van Vugt has studied this problem closely
36228 ** and has send his findings to the SQLite developers.  Frank
36229 ** writes that some Linux kernels offer floating point hardware
36230 ** emulation that uses only 32-bit mantissas instead of a full 
36231 ** 48-bits as required by the IEEE standard.  (This is the
36232 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
36233 ** byte swapping becomes very complicated.  To avoid problems,
36234 ** the necessary byte swapping is carried out using a 64-bit integer
36235 ** rather than a 64-bit float.  Frank assures us that the code here
36236 ** works for him.  We, the developers, have no way to independently
36237 ** verify this, but Frank seems to know what he is talking about
36238 ** so we trust him.
36239 */
36240 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
36241 static u64 floatSwap(u64 in){
36242   union {
36243     u64 r;
36244     u32 i[2];
36245   } u;
36246   u32 t;
36247
36248   u.r = in;
36249   t = u.i[0];
36250   u.i[0] = u.i[1];
36251   u.i[1] = t;
36252   return u.r;
36253 }
36254 # define swapMixedEndianFloat(X)  X = floatSwap(X)
36255 #else
36256 # define swapMixedEndianFloat(X)
36257 #endif
36258
36259 /*
36260 ** Write the serialized data blob for the value stored in pMem into 
36261 ** buf. It is assumed that the caller has allocated sufficient space.
36262 ** Return the number of bytes written.
36263 **
36264 ** nBuf is the amount of space left in buf[].  nBuf must always be
36265 ** large enough to hold the entire field.  Except, if the field is
36266 ** a blob with a zero-filled tail, then buf[] might be just the right
36267 ** size to hold everything except for the zero-filled tail.  If buf[]
36268 ** is only big enough to hold the non-zero prefix, then only write that
36269 ** prefix into buf[].  But if buf[] is large enough to hold both the
36270 ** prefix and the tail then write the prefix and set the tail to all
36271 ** zeros.
36272 **
36273 ** Return the number of bytes actually written into buf[].  The number
36274 ** of bytes in the zero-filled tail is included in the return value only
36275 ** if those bytes were zeroed in buf[].
36276 */ 
36277 SQLITE_PRIVATE int sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
36278   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
36279   int len;
36280
36281   /* Integer and Real */
36282   if( serial_type<=7 && serial_type>0 ){
36283     u64 v;
36284     int i;
36285     if( serial_type==7 ){
36286       assert( sizeof(v)==sizeof(pMem->r) );
36287       memcpy(&v, &pMem->r, sizeof(v));
36288       swapMixedEndianFloat(v);
36289     }else{
36290       v = pMem->u.i;
36291     }
36292     len = i = sqlite3VdbeSerialTypeLen(serial_type);
36293     assert( len<=nBuf );
36294     while( i-- ){
36295       buf[i] = (v&0xFF);
36296       v >>= 8;
36297     }
36298     return len;
36299   }
36300
36301   /* String or blob */
36302   if( serial_type>=12 ){
36303     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.i:0)
36304              == sqlite3VdbeSerialTypeLen(serial_type) );
36305     assert( pMem->n<=nBuf );
36306     len = pMem->n;
36307     memcpy(buf, pMem->z, len);
36308     if( pMem->flags & MEM_Zero ){
36309       len += pMem->u.i;
36310       if( len>nBuf ){
36311         len = nBuf;
36312       }
36313       memset(&buf[pMem->n], 0, len-pMem->n);
36314     }
36315     return len;
36316   }
36317
36318   /* NULL or constants 0 or 1 */
36319   return 0;
36320 }
36321
36322 /*
36323 ** Deserialize the data blob pointed to by buf as serial type serial_type
36324 ** and store the result in pMem.  Return the number of bytes read.
36325 */ 
36326 SQLITE_PRIVATE int sqlite3VdbeSerialGet(
36327   const unsigned char *buf,     /* Buffer to deserialize from */
36328   u32 serial_type,              /* Serial type to deserialize */
36329   Mem *pMem                     /* Memory cell to write value into */
36330 ){
36331   switch( serial_type ){
36332     case 10:   /* Reserved for future use */
36333     case 11:   /* Reserved for future use */
36334     case 0: {  /* NULL */
36335       pMem->flags = MEM_Null;
36336       break;
36337     }
36338     case 1: { /* 1-byte signed integer */
36339       pMem->u.i = (signed char)buf[0];
36340       pMem->flags = MEM_Int;
36341       return 1;
36342     }
36343     case 2: { /* 2-byte signed integer */
36344       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
36345       pMem->flags = MEM_Int;
36346       return 2;
36347     }
36348     case 3: { /* 3-byte signed integer */
36349       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
36350       pMem->flags = MEM_Int;
36351       return 3;
36352     }
36353     case 4: { /* 4-byte signed integer */
36354       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
36355       pMem->flags = MEM_Int;
36356       return 4;
36357     }
36358     case 5: { /* 6-byte signed integer */
36359       u64 x = (((signed char)buf[0])<<8) | buf[1];
36360       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
36361       x = (x<<32) | y;
36362       pMem->u.i = *(i64*)&x;
36363       pMem->flags = MEM_Int;
36364       return 6;
36365     }
36366     case 6:   /* 8-byte signed integer */
36367     case 7: { /* IEEE floating point */
36368       u64 x;
36369       u32 y;
36370 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
36371       /* Verify that integers and floating point values use the same
36372       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
36373       ** defined that 64-bit floating point values really are mixed
36374       ** endian.
36375       */
36376       static const u64 t1 = ((u64)0x3ff00000)<<32;
36377       static const double r1 = 1.0;
36378       u64 t2 = t1;
36379       swapMixedEndianFloat(t2);
36380       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
36381 #endif
36382
36383       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
36384       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
36385       x = (x<<32) | y;
36386       if( serial_type==6 ){
36387         pMem->u.i = *(i64*)&x;
36388         pMem->flags = MEM_Int;
36389       }else{
36390         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
36391         swapMixedEndianFloat(x);
36392         memcpy(&pMem->r, &x, sizeof(x));
36393         pMem->flags = MEM_Real;
36394       }
36395       return 8;
36396     }
36397     case 8:    /* Integer 0 */
36398     case 9: {  /* Integer 1 */
36399       pMem->u.i = serial_type-8;
36400       pMem->flags = MEM_Int;
36401       return 0;
36402     }
36403     default: {
36404       int len = (serial_type-12)/2;
36405       pMem->z = (char *)buf;
36406       pMem->n = len;
36407       pMem->xDel = 0;
36408       if( serial_type&0x01 ){
36409         pMem->flags = MEM_Str | MEM_Ephem;
36410       }else{
36411         pMem->flags = MEM_Blob | MEM_Ephem;
36412       }
36413       return len;
36414     }
36415   }
36416   return 0;
36417 }
36418
36419 /*
36420 ** The header of a record consists of a sequence variable-length integers.
36421 ** These integers are almost always small and are encoded as a single byte.
36422 ** The following macro takes advantage this fact to provide a fast decode
36423 ** of the integers in a record header.  It is faster for the common case
36424 ** where the integer is a single byte.  It is a little slower when the
36425 ** integer is two or more bytes.  But overall it is faster.
36426 **
36427 ** The following expressions are equivalent:
36428 **
36429 **     x = sqlite3GetVarint32( A, &B );
36430 **
36431 **     x = GetVarint( A, B );
36432 **
36433 */
36434 #define GetVarint(A,B)  ((B = *(A))<=0x7f ? 1 : sqlite3GetVarint32(A, &B))
36435
36436 /*
36437 ** This function compares the two table rows or index records specified by 
36438 ** {nKey1, pKey1} and {nKey2, pKey2}, returning a negative, zero
36439 ** or positive integer if {nKey1, pKey1} is less than, equal to or 
36440 ** greater than {nKey2, pKey2}.  Both Key1 and Key2 must be byte strings
36441 ** composed by the OP_MakeRecord opcode of the VDBE.
36442 */
36443 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
36444   void *userData,
36445   int nKey1, const void *pKey1, 
36446   int nKey2, const void *pKey2
36447 ){
36448   KeyInfo *pKeyInfo = (KeyInfo*)userData;
36449   u32 d1, d2;          /* Offset into aKey[] of next data element */
36450   u32 idx1, idx2;      /* Offset into aKey[] of next header element */
36451   u32 szHdr1, szHdr2;  /* Number of bytes in header */
36452   int i = 0;
36453   int nField;
36454   int rc = 0;
36455   const unsigned char *aKey1 = (const unsigned char *)pKey1;
36456   const unsigned char *aKey2 = (const unsigned char *)pKey2;
36457
36458   Mem mem1;
36459   Mem mem2;
36460   mem1.enc = pKeyInfo->enc;
36461   mem1.db = pKeyInfo->db;
36462   mem2.enc = pKeyInfo->enc;
36463   mem2.db = pKeyInfo->db;
36464   
36465   idx1 = GetVarint(aKey1, szHdr1);
36466   d1 = szHdr1;
36467   idx2 = GetVarint(aKey2, szHdr2);
36468   d2 = szHdr2;
36469   nField = pKeyInfo->nField;
36470   while( idx1<szHdr1 && idx2<szHdr2 ){
36471     u32 serial_type1;
36472     u32 serial_type2;
36473
36474     /* Read the serial types for the next element in each key. */
36475     idx1 += GetVarint( aKey1+idx1, serial_type1 );
36476     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
36477     idx2 += GetVarint( aKey2+idx2, serial_type2 );
36478     if( d2>=nKey2 && sqlite3VdbeSerialTypeLen(serial_type2)>0 ) break;
36479
36480     /* Extract the values to be compared.
36481     */
36482     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
36483     d2 += sqlite3VdbeSerialGet(&aKey2[d2], serial_type2, &mem2);
36484
36485     /* Do the comparison
36486     */
36487     rc = sqlite3MemCompare(&mem1, &mem2, i<nField ? pKeyInfo->aColl[i] : 0);
36488     if( mem1.flags & MEM_Dyn ) sqlite3VdbeMemRelease(&mem1);
36489     if( mem2.flags & MEM_Dyn ) sqlite3VdbeMemRelease(&mem2);
36490     if( rc!=0 ){
36491       break;
36492     }
36493     i++;
36494   }
36495
36496   /* One of the keys ran out of fields, but all the fields up to that point
36497   ** were equal. If the incrKey flag is true, then the second key is
36498   ** treated as larger.
36499   */
36500   if( rc==0 ){
36501     if( pKeyInfo->incrKey ){
36502       rc = -1;
36503     }else if( !pKeyInfo->prefixIsEqual ){
36504       if( d1<nKey1 ){
36505         rc = 1;
36506       }else if( d2<nKey2 ){
36507         rc = -1;
36508       }
36509     }
36510   }else if( pKeyInfo->aSortOrder && i<pKeyInfo->nField
36511                && pKeyInfo->aSortOrder[i] ){
36512     rc = -rc;
36513   }
36514
36515   return rc;
36516 }
36517
36518 /*
36519 ** The argument is an index entry composed using the OP_MakeRecord opcode.
36520 ** The last entry in this record should be an integer (specifically
36521 ** an integer rowid).  This routine returns the number of bytes in
36522 ** that integer.
36523 */
36524 SQLITE_PRIVATE int sqlite3VdbeIdxRowidLen(const u8 *aKey){
36525   u32 szHdr;        /* Size of the header */
36526   u32 typeRowid;    /* Serial type of the rowid */
36527
36528   sqlite3GetVarint32(aKey, &szHdr);
36529   sqlite3GetVarint32(&aKey[szHdr-1], &typeRowid);
36530   return sqlite3VdbeSerialTypeLen(typeRowid);
36531 }
36532   
36533
36534 /*
36535 ** pCur points at an index entry created using the OP_MakeRecord opcode.
36536 ** Read the rowid (the last field in the record) and store it in *rowid.
36537 ** Return SQLITE_OK if everything works, or an error code otherwise.
36538 */
36539 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
36540   i64 nCellKey = 0;
36541   int rc;
36542   u32 szHdr;        /* Size of the header */
36543   u32 typeRowid;    /* Serial type of the rowid */
36544   u32 lenRowid;     /* Size of the rowid */
36545   Mem m, v;
36546
36547   sqlite3BtreeKeySize(pCur, &nCellKey);
36548   if( nCellKey<=0 ){
36549     return SQLITE_CORRUPT_BKPT;
36550   }
36551   rc = sqlite3VdbeMemFromBtree(pCur, 0, nCellKey, 1, &m);
36552   if( rc ){
36553     return rc;
36554   }
36555   sqlite3GetVarint32((u8*)m.z, &szHdr);
36556   sqlite3GetVarint32((u8*)&m.z[szHdr-1], &typeRowid);
36557   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
36558   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
36559   *rowid = v.u.i;
36560   sqlite3VdbeMemRelease(&m);
36561   return SQLITE_OK;
36562 }
36563
36564 /*
36565 ** Compare the key of the index entry that cursor pC is point to against
36566 ** the key string in pKey (of length nKey).  Write into *pRes a number
36567 ** that is negative, zero, or positive if pC is less than, equal to,
36568 ** or greater than pKey.  Return SQLITE_OK on success.
36569 **
36570 ** pKey is either created without a rowid or is truncated so that it
36571 ** omits the rowid at the end.  The rowid at the end of the index entry
36572 ** is ignored as well.
36573 */
36574 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
36575   Cursor *pC,                 /* The cursor to compare against */
36576   int nKey, const u8 *pKey,   /* The key to compare */
36577   int *res                    /* Write the comparison result here */
36578 ){
36579   i64 nCellKey = 0;
36580   int rc;
36581   BtCursor *pCur = pC->pCursor;
36582   int lenRowid;
36583   Mem m;
36584
36585   sqlite3BtreeKeySize(pCur, &nCellKey);
36586   if( nCellKey<=0 ){
36587     *res = 0;
36588     return SQLITE_OK;
36589   }
36590   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, nCellKey, 1, &m);
36591   if( rc ){
36592     return rc;
36593   }
36594   lenRowid = sqlite3VdbeIdxRowidLen((u8*)m.z);
36595   *res = sqlite3VdbeRecordCompare(pC->pKeyInfo, m.n-lenRowid, m.z, nKey, pKey);
36596   sqlite3VdbeMemRelease(&m);
36597   return SQLITE_OK;
36598 }
36599
36600 /*
36601 ** This routine sets the value to be returned by subsequent calls to
36602 ** sqlite3_changes() on the database handle 'db'. 
36603 */
36604 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
36605   assert( sqlite3_mutex_held(db->mutex) );
36606   db->nChange = nChange;
36607   db->nTotalChange += nChange;
36608 }
36609
36610 /*
36611 ** Set a flag in the vdbe to update the change counter when it is finalised
36612 ** or reset.
36613 */
36614 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
36615   v->changeCntOn = 1;
36616 }
36617
36618 /*
36619 ** Mark every prepared statement associated with a database connection
36620 ** as expired.
36621 **
36622 ** An expired statement means that recompilation of the statement is
36623 ** recommend.  Statements expire when things happen that make their
36624 ** programs obsolete.  Removing user-defined functions or collating
36625 ** sequences, or changing an authorization function are the types of
36626 ** things that make prepared statements obsolete.
36627 */
36628 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
36629   Vdbe *p;
36630   for(p = db->pVdbe; p; p=p->pNext){
36631     p->expired = 1;
36632   }
36633 }
36634
36635 /*
36636 ** Return the database associated with the Vdbe.
36637 */
36638 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
36639   return v->db;
36640 }
36641
36642 /************** End of vdbeaux.c *********************************************/
36643 /************** Begin file vdbeapi.c *****************************************/
36644 /*
36645 ** 2004 May 26
36646 **
36647 ** The author disclaims copyright to this source code.  In place of
36648 ** a legal notice, here is a blessing:
36649 **
36650 **    May you do good and not evil.
36651 **    May you find forgiveness for yourself and forgive others.
36652 **    May you share freely, never taking more than you give.
36653 **
36654 *************************************************************************
36655 **
36656 ** This file contains code use to implement APIs that are part of the
36657 ** VDBE.
36658 */
36659
36660 /*
36661 ** Return TRUE (non-zero) of the statement supplied as an argument needs
36662 ** to be recompiled.  A statement needs to be recompiled whenever the
36663 ** execution environment changes in a way that would alter the program
36664 ** that sqlite3_prepare() generates.  For example, if new functions or
36665 ** collating sequences are registered or if an authorizer function is
36666 ** added or changed.
36667 */
36668 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
36669   Vdbe *p = (Vdbe*)pStmt;
36670   return p==0 || p->expired;
36671 }
36672
36673 /*
36674 ** The following routine destroys a virtual machine that is created by
36675 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
36676 ** success/failure code that describes the result of executing the virtual
36677 ** machine.
36678 **
36679 ** This routine sets the error code and string returned by
36680 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
36681 */
36682 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
36683   int rc;
36684   if( pStmt==0 ){
36685     rc = SQLITE_OK;
36686   }else{
36687     Vdbe *v = (Vdbe*)pStmt;
36688     sqlite3_mutex *mutex = v->db->mutex;
36689     sqlite3_mutex_enter(mutex);
36690     rc = sqlite3VdbeFinalize(v);
36691     sqlite3_mutex_leave(mutex);
36692   }
36693   return rc;
36694 }
36695
36696 /*
36697 ** Terminate the current execution of an SQL statement and reset it
36698 ** back to its starting state so that it can be reused. A success code from
36699 ** the prior execution is returned.
36700 **
36701 ** This routine sets the error code and string returned by
36702 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
36703 */
36704 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
36705   int rc;
36706   if( pStmt==0 ){
36707     rc = SQLITE_OK;
36708   }else{
36709     Vdbe *v = (Vdbe*)pStmt;
36710     sqlite3_mutex_enter(v->db->mutex);
36711     rc = sqlite3VdbeReset(v);
36712     sqlite3VdbeMakeReady(v, -1, 0, 0, 0);
36713     assert( (rc & (v->db->errMask))==rc );
36714     sqlite3_mutex_leave(v->db->mutex);
36715   }
36716   return rc;
36717 }
36718
36719 /*
36720 ** Set all the parameters in the compiled SQL statement to NULL.
36721 */
36722 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
36723   int i;
36724   int rc = SQLITE_OK;
36725   Vdbe *v = (Vdbe*)pStmt;
36726   sqlite3_mutex_enter(v->db->mutex);
36727   for(i=1; rc==SQLITE_OK && i<=sqlite3_bind_parameter_count(pStmt); i++){
36728     rc = sqlite3_bind_null(pStmt, i);
36729   }
36730   sqlite3_mutex_leave(v->db->mutex);
36731   return rc;
36732 }
36733
36734
36735 /**************************** sqlite3_value_  *******************************
36736 ** The following routines extract information from a Mem or sqlite3_value
36737 ** structure.
36738 */
36739 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
36740   Mem *p = (Mem*)pVal;
36741   if( p->flags & (MEM_Blob|MEM_Str) ){
36742     sqlite3VdbeMemExpandBlob(p);
36743     p->flags &= ~MEM_Str;
36744     p->flags |= MEM_Blob;
36745     return p->z;
36746   }else{
36747     return sqlite3_value_text(pVal);
36748   }
36749 }
36750 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
36751   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
36752 }
36753 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
36754   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
36755 }
36756 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
36757   return sqlite3VdbeRealValue((Mem*)pVal);
36758 }
36759 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
36760   return sqlite3VdbeIntValue((Mem*)pVal);
36761 }
36762 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
36763   return sqlite3VdbeIntValue((Mem*)pVal);
36764 }
36765 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
36766   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
36767 }
36768 #ifndef SQLITE_OMIT_UTF16
36769 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
36770   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
36771 }
36772 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
36773   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
36774 }
36775 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
36776   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
36777 }
36778 #endif /* SQLITE_OMIT_UTF16 */
36779 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
36780   return pVal->type;
36781 }
36782
36783 /**************************** sqlite3_result_  *******************************
36784 ** The following routines are used by user-defined functions to specify
36785 ** the function result.
36786 */
36787 SQLITE_API void sqlite3_result_blob(
36788   sqlite3_context *pCtx, 
36789   const void *z, 
36790   int n, 
36791   void (*xDel)(void *)
36792 ){
36793   assert( n>=0 );
36794   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
36795   sqlite3VdbeMemSetStr(&pCtx->s, z, n, 0, xDel);
36796 }
36797 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
36798   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
36799   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
36800 }
36801 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
36802   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
36803   pCtx->isError = 1;
36804   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
36805 }
36806 #ifndef SQLITE_OMIT_UTF16
36807 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
36808   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
36809   pCtx->isError = 1;
36810   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
36811 }
36812 #endif
36813 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
36814   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
36815   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
36816 }
36817 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
36818   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
36819   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
36820 }
36821 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
36822   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
36823   sqlite3VdbeMemSetNull(&pCtx->s);
36824 }
36825 SQLITE_API void sqlite3_result_text(
36826   sqlite3_context *pCtx, 
36827   const char *z, 
36828   int n,
36829   void (*xDel)(void *)
36830 ){
36831   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
36832   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, xDel);
36833 }
36834 #ifndef SQLITE_OMIT_UTF16
36835 SQLITE_API void sqlite3_result_text16(
36836   sqlite3_context *pCtx, 
36837   const void *z, 
36838   int n, 
36839   void (*xDel)(void *)
36840 ){
36841   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
36842   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, xDel);
36843 }
36844 SQLITE_API void sqlite3_result_text16be(
36845   sqlite3_context *pCtx, 
36846   const void *z, 
36847   int n, 
36848   void (*xDel)(void *)
36849 ){
36850   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
36851   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16BE, xDel);
36852 }
36853 SQLITE_API void sqlite3_result_text16le(
36854   sqlite3_context *pCtx, 
36855   const void *z, 
36856   int n, 
36857   void (*xDel)(void *)
36858 ){
36859   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
36860   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16LE, xDel);
36861 }
36862 #endif /* SQLITE_OMIT_UTF16 */
36863 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
36864   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
36865   sqlite3VdbeMemCopy(&pCtx->s, pValue);
36866 }
36867 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
36868   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
36869   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
36870 }
36871
36872 /* Force an SQLITE_TOOBIG error. */
36873 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
36874   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
36875   sqlite3VdbeMemSetZeroBlob(&pCtx->s, SQLITE_MAX_LENGTH+1);
36876 }
36877
36878 /* An SQLITE_NOMEM error. */
36879 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
36880   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
36881   sqlite3VdbeMemSetNull(&pCtx->s);
36882   pCtx->isError = 1;
36883   pCtx->s.db->mallocFailed = 1;
36884 }
36885
36886 /*
36887 ** Execute the statement pStmt, either until a row of data is ready, the
36888 ** statement is completely executed or an error occurs.
36889 **
36890 ** This routine implements the bulk of the logic behind the sqlite_step()
36891 ** API.  The only thing omitted is the automatic recompile if a 
36892 ** schema change has occurred.  That detail is handled by the
36893 ** outer sqlite3_step() wrapper procedure.
36894 */
36895 static int sqlite3Step(Vdbe *p){
36896   sqlite3 *db;
36897   int rc;
36898
36899   assert(p);
36900   if( p->magic!=VDBE_MAGIC_RUN ){
36901     return SQLITE_MISUSE;
36902   }
36903
36904   /* Assert that malloc() has not failed */
36905   db = p->db;
36906   assert( !db->mallocFailed );
36907
36908   if( p->aborted ){
36909     return SQLITE_ABORT;
36910   }
36911   if( p->pc<=0 && p->expired ){
36912     if( p->rc==SQLITE_OK ){
36913       p->rc = SQLITE_SCHEMA;
36914     }
36915     rc = SQLITE_ERROR;
36916     goto end_of_step;
36917   }
36918   if( sqlite3SafetyOn(db) ){
36919     p->rc = SQLITE_MISUSE;
36920     return SQLITE_MISUSE;
36921   }
36922   if( p->pc<0 ){
36923     /* If there are no other statements currently running, then
36924     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
36925     ** from interrupting a statement that has not yet started.
36926     */
36927     if( db->activeVdbeCnt==0 ){
36928       db->u1.isInterrupted = 0;
36929     }
36930
36931 #ifndef SQLITE_OMIT_TRACE
36932     /* Invoke the trace callback if there is one
36933     */
36934     if( db->xTrace && !db->init.busy ){
36935       assert( p->nOp>0 );
36936       assert( p->aOp[p->nOp-1].opcode==OP_Noop );
36937       assert( p->aOp[p->nOp-1].p3!=0 );
36938       assert( p->aOp[p->nOp-1].p3type==P3_DYNAMIC );
36939       sqlite3SafetyOff(db);
36940       db->xTrace(db->pTraceArg, p->aOp[p->nOp-1].p3);
36941       if( sqlite3SafetyOn(db) ){
36942         p->rc = SQLITE_MISUSE;
36943         return SQLITE_MISUSE;
36944       }
36945     }
36946     if( db->xProfile && !db->init.busy ){
36947       double rNow;
36948       sqlite3OsCurrentTime(db->pVfs, &rNow);
36949       p->startTime = (rNow - (int)rNow)*3600.0*24.0*1000000000.0;
36950     }
36951 #endif
36952
36953     /* Print a copy of SQL as it is executed if the SQL_TRACE pragma is turned
36954     ** on in debugging mode.
36955     */
36956 #ifdef SQLITE_DEBUG
36957     if( (db->flags & SQLITE_SqlTrace)!=0 ){
36958       sqlite3DebugPrintf("SQL-trace: %s\n", p->aOp[p->nOp-1].p3);
36959     }
36960 #endif /* SQLITE_DEBUG */
36961
36962     db->activeVdbeCnt++;
36963     p->pc = 0;
36964   }
36965 #ifndef SQLITE_OMIT_EXPLAIN
36966   if( p->explain ){
36967     rc = sqlite3VdbeList(p);
36968   }else
36969 #endif /* SQLITE_OMIT_EXPLAIN */
36970   {
36971     rc = sqlite3VdbeExec(p);
36972   }
36973
36974   if( sqlite3SafetyOff(db) ){
36975     rc = SQLITE_MISUSE;
36976   }
36977
36978 #ifndef SQLITE_OMIT_TRACE
36979   /* Invoke the profile callback if there is one
36980   */
36981   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy ){
36982     double rNow;
36983     u64 elapseTime;
36984
36985     sqlite3OsCurrentTime(db->pVfs, &rNow);
36986     elapseTime = (rNow - (int)rNow)*3600.0*24.0*1000000000.0 - p->startTime;
36987     assert( p->nOp>0 );
36988     assert( p->aOp[p->nOp-1].opcode==OP_Noop );
36989     assert( p->aOp[p->nOp-1].p3!=0 );
36990     assert( p->aOp[p->nOp-1].p3type==P3_DYNAMIC );
36991     db->xProfile(db->pProfileArg, p->aOp[p->nOp-1].p3, elapseTime);
36992   }
36993 #endif
36994
36995   sqlite3Error(p->db, rc, 0);
36996   p->rc = sqlite3ApiExit(p->db, p->rc);
36997 end_of_step:
36998   assert( (rc&0xff)==rc );
36999   if( p->zSql && (rc&0xff)<SQLITE_ROW ){
37000     /* This behavior occurs if sqlite3_prepare_v2() was used to build
37001     ** the prepared statement.  Return error codes directly */
37002     sqlite3Error(p->db, p->rc, 0);
37003     return p->rc;
37004   }else{
37005     /* This is for legacy sqlite3_prepare() builds and when the code
37006     ** is SQLITE_ROW or SQLITE_DONE */
37007     return rc;
37008   }
37009 }
37010
37011 /*
37012 ** This is the top-level implementation of sqlite3_step().  Call
37013 ** sqlite3Step() to do most of the work.  If a schema error occurs,
37014 ** call sqlite3Reprepare() and try again.
37015 */
37016 #ifdef SQLITE_OMIT_PARSER
37017 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
37018   int rc = SQLITE_MISUSE;
37019   if( pStmt ){
37020     Vdbe *v;
37021     v = (Vdbe*)pStmt;
37022     sqlite3_mutex_enter(v->db->mutex);
37023     rc = sqlite3Step(v);
37024     sqlite3_mutex_leave(v->db->mutex);
37025   }
37026   return rc;
37027 }
37028 #else
37029 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
37030   int rc = SQLITE_MISUSE;
37031   if( pStmt ){
37032     int cnt = 0;
37033     Vdbe *v = (Vdbe*)pStmt;
37034     sqlite3 *db = v->db;
37035     sqlite3_mutex_enter(db->mutex);
37036     while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
37037            && cnt++ < 5
37038            && sqlite3Reprepare(v) ){
37039       sqlite3_reset(pStmt);
37040       v->expired = 0;
37041     }
37042     if( rc==SQLITE_SCHEMA && v->zSql && db->pErr ){
37043       /* This case occurs after failing to recompile an sql statement. 
37044       ** The error message from the SQL compiler has already been loaded 
37045       ** into the database handle. This block copies the error message 
37046       ** from the database handle into the statement and sets the statement
37047       ** program counter to 0 to ensure that when the statement is 
37048       ** finalized or reset the parser error message is available via
37049       ** sqlite3_errmsg() and sqlite3_errcode().
37050       */
37051       const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
37052       sqlite3_free(v->zErrMsg);
37053       if( !db->mallocFailed ){
37054         v->zErrMsg = sqlite3DbStrDup(db, zErr);
37055       } else {
37056         v->zErrMsg = 0;
37057         v->rc = SQLITE_NOMEM;
37058       }
37059     }
37060     rc = sqlite3ApiExit(db, rc);
37061     sqlite3_mutex_leave(db->mutex);
37062   }
37063   return rc;
37064 }
37065 #endif
37066
37067 /*
37068 ** Extract the user data from a sqlite3_context structure and return a
37069 ** pointer to it.
37070 */
37071 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
37072   assert( p && p->pFunc );
37073   return p->pFunc->pUserData;
37074 }
37075
37076 /*
37077 ** The following is the implementation of an SQL function that always
37078 ** fails with an error message stating that the function is used in the
37079 ** wrong context.  The sqlite3_overload_function() API might construct
37080 ** SQL function that use this routine so that the functions will exist
37081 ** for name resolution but are actually overloaded by the xFindFunction
37082 ** method of virtual tables.
37083 */
37084 SQLITE_PRIVATE void sqlite3InvalidFunction(
37085   sqlite3_context *context,  /* The function calling context */
37086   int argc,                  /* Number of arguments to the function */
37087   sqlite3_value **argv       /* Value of each argument */
37088 ){
37089   const char *zName = context->pFunc->zName;
37090   char *zErr;
37091   zErr = sqlite3MPrintf(0,
37092       "unable to use function %s in the requested context", zName);
37093   sqlite3_result_error(context, zErr, -1);
37094   sqlite3_free(zErr);
37095 }
37096
37097 /*
37098 ** Allocate or return the aggregate context for a user function.  A new
37099 ** context is allocated on the first call.  Subsequent calls return the
37100 ** same context that was returned on prior calls.
37101 */
37102 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
37103   Mem *pMem;
37104   assert( p && p->pFunc && p->pFunc->xStep );
37105   assert( sqlite3_mutex_held(p->s.db->mutex) );
37106   pMem = p->pMem;
37107   if( (pMem->flags & MEM_Agg)==0 ){
37108     if( nByte==0 ){
37109       assert( pMem->flags==MEM_Null );
37110       pMem->z = 0;
37111     }else{
37112       pMem->flags = MEM_Agg;
37113       pMem->xDel = sqlite3_free;
37114       pMem->u.pDef = p->pFunc;
37115       pMem->z = sqlite3DbMallocZero(p->s.db, nByte);
37116     }
37117   }
37118   return (void*)pMem->z;
37119 }
37120
37121 /*
37122 ** Return the auxilary data pointer, if any, for the iArg'th argument to
37123 ** the user-function defined by pCtx.
37124 */
37125 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
37126   VdbeFunc *pVdbeFunc;
37127
37128   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
37129   pVdbeFunc = pCtx->pVdbeFunc;
37130   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
37131     return 0;
37132   }
37133   return pVdbeFunc->apAux[iArg].pAux;
37134 }
37135
37136 /*
37137 ** Set the auxilary data pointer and delete function, for the iArg'th
37138 ** argument to the user-function defined by pCtx. Any previous value is
37139 ** deleted by calling the delete function specified when it was set.
37140 */
37141 SQLITE_API void sqlite3_set_auxdata(
37142   sqlite3_context *pCtx, 
37143   int iArg, 
37144   void *pAux, 
37145   void (*xDelete)(void*)
37146 ){
37147   struct AuxData *pAuxData;
37148   VdbeFunc *pVdbeFunc;
37149   if( iArg<0 ) goto failed;
37150
37151   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
37152   pVdbeFunc = pCtx->pVdbeFunc;
37153   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
37154     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
37155     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
37156     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
37157     if( !pVdbeFunc ){
37158       goto failed;
37159     }
37160     pCtx->pVdbeFunc = pVdbeFunc;
37161     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
37162     pVdbeFunc->nAux = iArg+1;
37163     pVdbeFunc->pFunc = pCtx->pFunc;
37164   }
37165
37166   pAuxData = &pVdbeFunc->apAux[iArg];
37167   if( pAuxData->pAux && pAuxData->xDelete ){
37168     pAuxData->xDelete(pAuxData->pAux);
37169   }
37170   pAuxData->pAux = pAux;
37171   pAuxData->xDelete = xDelete;
37172   return;
37173
37174 failed:
37175   if( xDelete ){
37176     xDelete(pAux);
37177   }
37178 }
37179
37180 /*
37181 ** Return the number of times the Step function of a aggregate has been 
37182 ** called.
37183 **
37184 ** This function is deprecated.  Do not use it for new code.  It is
37185 ** provide only to avoid breaking legacy code.  New aggregate function
37186 ** implementations should keep their own counts within their aggregate
37187 ** context.
37188 */
37189 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
37190   assert( p && p->pFunc && p->pFunc->xStep );
37191   return p->pMem->n;
37192 }
37193
37194 /*
37195 ** Return the number of columns in the result set for the statement pStmt.
37196 */
37197 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
37198   Vdbe *pVm = (Vdbe *)pStmt;
37199   return pVm ? pVm->nResColumn : 0;
37200 }
37201
37202 /*
37203 ** Return the number of values available from the current row of the
37204 ** currently executing statement pStmt.
37205 */
37206 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
37207   Vdbe *pVm = (Vdbe *)pStmt;
37208   if( pVm==0 || !pVm->resOnStack ) return 0;
37209   return pVm->nResColumn;
37210 }
37211
37212
37213 /*
37214 ** Check to see if column iCol of the given statement is valid.  If
37215 ** it is, return a pointer to the Mem for the value of that column.
37216 ** If iCol is not valid, return a pointer to a Mem which has a value
37217 ** of NULL.
37218 */
37219 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
37220   Vdbe *pVm;
37221   int vals;
37222   Mem *pOut;
37223
37224   pVm = (Vdbe *)pStmt;
37225   if( pVm && pVm->resOnStack && i<pVm->nResColumn && i>=0 ){
37226     sqlite3_mutex_enter(pVm->db->mutex);
37227     vals = sqlite3_data_count(pStmt);
37228     pOut = &pVm->pTos[(1-vals)+i];
37229   }else{
37230     static const Mem nullMem = {{0}, 0.0, 0, "", 0, MEM_Null, SQLITE_NULL };
37231     if( pVm->db ){
37232       sqlite3_mutex_enter(pVm->db->mutex);
37233       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
37234     }
37235     pOut = (Mem*)&nullMem;
37236   }
37237   return pOut;
37238 }
37239
37240 /*
37241 ** This function is called after invoking an sqlite3_value_XXX function on a 
37242 ** column value (i.e. a value returned by evaluating an SQL expression in the
37243 ** select list of a SELECT statement) that may cause a malloc() failure. If 
37244 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
37245 ** code of statement pStmt set to SQLITE_NOMEM.
37246 **
37247 ** Specifically, this is called from within:
37248 **
37249 **     sqlite3_column_int()
37250 **     sqlite3_column_int64()
37251 **     sqlite3_column_text()
37252 **     sqlite3_column_text16()
37253 **     sqlite3_column_real()
37254 **     sqlite3_column_bytes()
37255 **     sqlite3_column_bytes16()
37256 **
37257 ** But not for sqlite3_column_blob(), which never calls malloc().
37258 */
37259 static void columnMallocFailure(sqlite3_stmt *pStmt)
37260 {
37261   /* If malloc() failed during an encoding conversion within an
37262   ** sqlite3_column_XXX API, then set the return code of the statement to
37263   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
37264   ** and _finalize() will return NOMEM.
37265   */
37266   Vdbe *p = (Vdbe *)pStmt;
37267   if( p ){
37268     p->rc = sqlite3ApiExit(p->db, p->rc);
37269     sqlite3_mutex_leave(p->db->mutex);
37270   }
37271 }
37272
37273 /**************************** sqlite3_column_  *******************************
37274 ** The following routines are used to access elements of the current row
37275 ** in the result set.
37276 */
37277 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
37278   const void *val;
37279   val = sqlite3_value_blob( columnMem(pStmt,i) );
37280   /* Even though there is no encoding conversion, value_blob() might
37281   ** need to call malloc() to expand the result of a zeroblob() 
37282   ** expression. 
37283   */
37284   columnMallocFailure(pStmt);
37285   return val;
37286 }
37287 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
37288   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
37289   columnMallocFailure(pStmt);
37290   return val;
37291 }
37292 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
37293   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
37294   columnMallocFailure(pStmt);
37295   return val;
37296 }
37297 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
37298   double val = sqlite3_value_double( columnMem(pStmt,i) );
37299   columnMallocFailure(pStmt);
37300   return val;
37301 }
37302 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
37303   int val = sqlite3_value_int( columnMem(pStmt,i) );
37304   columnMallocFailure(pStmt);
37305   return val;
37306 }
37307 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
37308   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
37309   columnMallocFailure(pStmt);
37310   return val;
37311 }
37312 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
37313   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
37314   columnMallocFailure(pStmt);
37315   return val;
37316 }
37317 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
37318   sqlite3_value *pOut = columnMem(pStmt, i);
37319   columnMallocFailure(pStmt);
37320   return pOut;
37321 }
37322 #ifndef SQLITE_OMIT_UTF16
37323 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
37324   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
37325   columnMallocFailure(pStmt);
37326   return val;
37327 }
37328 #endif /* SQLITE_OMIT_UTF16 */
37329 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
37330   int iType = sqlite3_value_type( columnMem(pStmt,i) );
37331   columnMallocFailure(pStmt);
37332   return iType;
37333 }
37334
37335 /* The following function is experimental and subject to change or
37336 ** removal */
37337 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
37338 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
37339 **}
37340 */
37341
37342 /*
37343 ** Convert the N-th element of pStmt->pColName[] into a string using
37344 ** xFunc() then return that string.  If N is out of range, return 0.
37345 **
37346 ** There are up to 5 names for each column.  useType determines which
37347 ** name is returned.  Here are the names:
37348 **
37349 **    0      The column name as it should be displayed for output
37350 **    1      The datatype name for the column
37351 **    2      The name of the database that the column derives from
37352 **    3      The name of the table that the column derives from
37353 **    4      The name of the table column that the result column derives from
37354 **
37355 ** If the result is not a simple column reference (if it is an expression
37356 ** or a constant) then useTypes 2, 3, and 4 return NULL.
37357 */
37358 static const void *columnName(
37359   sqlite3_stmt *pStmt,
37360   int N,
37361   const void *(*xFunc)(Mem*),
37362   int useType
37363 ){
37364   const void *ret = 0;
37365   Vdbe *p = (Vdbe *)pStmt;
37366   int n;
37367   
37368
37369   if( p!=0 ){
37370     n = sqlite3_column_count(pStmt);
37371     if( N<n && N>=0 ){
37372       N += useType*n;
37373       sqlite3_mutex_enter(p->db->mutex);
37374       ret = xFunc(&p->aColName[N]);
37375
37376       /* A malloc may have failed inside of the xFunc() call. If this
37377       ** is the case, clear the mallocFailed flag and return NULL.
37378       */
37379       if( p->db && p->db->mallocFailed ){
37380         p->db->mallocFailed = 0;
37381         ret = 0;
37382       }
37383       sqlite3_mutex_leave(p->db->mutex);
37384     }
37385   }
37386   return ret;
37387 }
37388
37389 /*
37390 ** Return the name of the Nth column of the result set returned by SQL
37391 ** statement pStmt.
37392 */
37393 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
37394   return columnName(
37395       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
37396 }
37397 #ifndef SQLITE_OMIT_UTF16
37398 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
37399   return columnName(
37400       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
37401 }
37402 #endif
37403
37404 /*
37405 ** Return the column declaration type (if applicable) of the 'i'th column
37406 ** of the result set of SQL statement pStmt.
37407 */
37408 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
37409   return columnName(
37410       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
37411 }
37412 #ifndef SQLITE_OMIT_UTF16
37413 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
37414   return columnName(
37415       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
37416 }
37417 #endif /* SQLITE_OMIT_UTF16 */
37418
37419 #ifdef SQLITE_ENABLE_COLUMN_METADATA
37420 /*
37421 ** Return the name of the database from which a result column derives.
37422 ** NULL is returned if the result column is an expression or constant or
37423 ** anything else which is not an unabiguous reference to a database column.
37424 */
37425 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
37426   return columnName(
37427       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
37428 }
37429 #ifndef SQLITE_OMIT_UTF16
37430 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
37431   return columnName(
37432       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
37433 }
37434 #endif /* SQLITE_OMIT_UTF16 */
37435
37436 /*
37437 ** Return the name of the table from which a result column derives.
37438 ** NULL is returned if the result column is an expression or constant or
37439 ** anything else which is not an unabiguous reference to a database column.
37440 */
37441 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
37442   return columnName(
37443       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
37444 }
37445 #ifndef SQLITE_OMIT_UTF16
37446 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
37447   return columnName(
37448       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
37449 }
37450 #endif /* SQLITE_OMIT_UTF16 */
37451
37452 /*
37453 ** Return the name of the table column from which a result column derives.
37454 ** NULL is returned if the result column is an expression or constant or
37455 ** anything else which is not an unabiguous reference to a database column.
37456 */
37457 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
37458   return columnName(
37459       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
37460 }
37461 #ifndef SQLITE_OMIT_UTF16
37462 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
37463   return columnName(
37464       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
37465 }
37466 #endif /* SQLITE_OMIT_UTF16 */
37467 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
37468
37469
37470 /******************************* sqlite3_bind_  ***************************
37471 ** 
37472 ** Routines used to attach values to wildcards in a compiled SQL statement.
37473 */
37474 /*
37475 ** Unbind the value bound to variable i in virtual machine p. This is the 
37476 ** the same as binding a NULL value to the column. If the "i" parameter is
37477 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
37478 **
37479 ** The error code stored in database p->db is overwritten with the return
37480 ** value in any case.
37481 */
37482 static int vdbeUnbind(Vdbe *p, int i){
37483   Mem *pVar;
37484   if( p==0 || p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
37485     if( p ) sqlite3Error(p->db, SQLITE_MISUSE, 0);
37486     return SQLITE_MISUSE;
37487   }
37488   if( i<1 || i>p->nVar ){
37489     sqlite3Error(p->db, SQLITE_RANGE, 0);
37490     return SQLITE_RANGE;
37491   }
37492   i--;
37493   pVar = &p->aVar[i];
37494   sqlite3VdbeMemRelease(pVar);
37495   pVar->flags = MEM_Null;
37496   sqlite3Error(p->db, SQLITE_OK, 0);
37497   return SQLITE_OK;
37498 }
37499
37500 /*
37501 ** Bind a text or BLOB value.
37502 */
37503 static int bindText(
37504   sqlite3_stmt *pStmt,   /* The statement to bind against */
37505   int i,                 /* Index of the parameter to bind */
37506   const void *zData,     /* Pointer to the data to be bound */
37507   int nData,             /* Number of bytes of data to be bound */
37508   void (*xDel)(void*),   /* Destructor for the data */
37509   int encoding           /* Encoding for the data */
37510 ){
37511   Vdbe *p = (Vdbe *)pStmt;
37512   Mem *pVar;
37513   int rc;
37514
37515   if( p==0 ){
37516     return SQLITE_MISUSE;
37517   }
37518   sqlite3_mutex_enter(p->db->mutex);
37519   rc = vdbeUnbind(p, i);
37520   if( rc==SQLITE_OK && zData!=0 ){
37521     pVar = &p->aVar[i-1];
37522     rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
37523     if( rc==SQLITE_OK && encoding!=0 ){
37524       rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
37525     }
37526     sqlite3Error(p->db, rc, 0);
37527     rc = sqlite3ApiExit(p->db, rc);
37528   }
37529   sqlite3_mutex_leave(p->db->mutex);
37530   return rc;
37531 }
37532
37533
37534 /*
37535 ** Bind a blob value to an SQL statement variable.
37536 */
37537 SQLITE_API int sqlite3_bind_blob(
37538   sqlite3_stmt *pStmt, 
37539   int i, 
37540   const void *zData, 
37541   int nData, 
37542   void (*xDel)(void*)
37543 ){
37544   return bindText(pStmt, i, zData, nData, xDel, 0);
37545 }
37546 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
37547   int rc;
37548   Vdbe *p = (Vdbe *)pStmt;
37549   sqlite3_mutex_enter(p->db->mutex);
37550   rc = vdbeUnbind(p, i);
37551   if( rc==SQLITE_OK ){
37552     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
37553   }
37554   sqlite3_mutex_leave(p->db->mutex);
37555   return rc;
37556 }
37557 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
37558   return sqlite3_bind_int64(p, i, (i64)iValue);
37559 }
37560 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
37561   int rc;
37562   Vdbe *p = (Vdbe *)pStmt;
37563   sqlite3_mutex_enter(p->db->mutex);
37564   rc = vdbeUnbind(p, i);
37565   if( rc==SQLITE_OK ){
37566     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
37567   }
37568   sqlite3_mutex_leave(p->db->mutex);
37569   return rc;
37570 }
37571 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
37572   int rc;
37573   Vdbe *p = (Vdbe*)pStmt;
37574   sqlite3_mutex_enter(p->db->mutex);
37575   rc = vdbeUnbind(p, i);
37576   sqlite3_mutex_leave(p->db->mutex);
37577   return rc;
37578 }
37579 SQLITE_API int sqlite3_bind_text( 
37580   sqlite3_stmt *pStmt, 
37581   int i, 
37582   const char *zData, 
37583   int nData, 
37584   void (*xDel)(void*)
37585 ){
37586   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
37587 }
37588 #ifndef SQLITE_OMIT_UTF16
37589 SQLITE_API int sqlite3_bind_text16(
37590   sqlite3_stmt *pStmt, 
37591   int i, 
37592   const void *zData, 
37593   int nData, 
37594   void (*xDel)(void*)
37595 ){
37596   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
37597 }
37598 #endif /* SQLITE_OMIT_UTF16 */
37599 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
37600   int rc;
37601   Vdbe *p = (Vdbe *)pStmt;
37602   sqlite3_mutex_enter(p->db->mutex);
37603   rc = vdbeUnbind(p, i);
37604   if( rc==SQLITE_OK ){
37605     rc = sqlite3VdbeMemCopy(&p->aVar[i-1], pValue);
37606   }
37607   sqlite3_mutex_leave(p->db->mutex);
37608   return rc;
37609 }
37610 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
37611   int rc;
37612   Vdbe *p = (Vdbe *)pStmt;
37613   sqlite3_mutex_enter(p->db->mutex);
37614   rc = vdbeUnbind(p, i);
37615   if( rc==SQLITE_OK ){
37616     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
37617   }
37618   sqlite3_mutex_leave(p->db->mutex);
37619   return rc;
37620 }
37621
37622 /*
37623 ** Return the number of wildcards that can be potentially bound to.
37624 ** This routine is added to support DBD::SQLite.  
37625 */
37626 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
37627   Vdbe *p = (Vdbe*)pStmt;
37628   return p ? p->nVar : 0;
37629 }
37630
37631 /*
37632 ** Create a mapping from variable numbers to variable names
37633 ** in the Vdbe.azVar[] array, if such a mapping does not already
37634 ** exist.
37635 */
37636 static void createVarMap(Vdbe *p){
37637   if( !p->okVar ){
37638     sqlite3_mutex_enter(p->db->mutex);
37639     if( !p->okVar ){
37640       int j;
37641       Op *pOp;
37642       for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
37643         if( pOp->opcode==OP_Variable ){
37644           assert( pOp->p1>0 && pOp->p1<=p->nVar );
37645           p->azVar[pOp->p1-1] = pOp->p3;
37646         }
37647       }
37648       p->okVar = 1;
37649     }
37650     sqlite3_mutex_leave(p->db->mutex);
37651   }
37652 }
37653
37654 /*
37655 ** Return the name of a wildcard parameter.  Return NULL if the index
37656 ** is out of range or if the wildcard is unnamed.
37657 **
37658 ** The result is always UTF-8.
37659 */
37660 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
37661   Vdbe *p = (Vdbe*)pStmt;
37662   if( p==0 || i<1 || i>p->nVar ){
37663     return 0;
37664   }
37665   createVarMap(p);
37666   return p->azVar[i-1];
37667 }
37668
37669 /*
37670 ** Given a wildcard parameter name, return the index of the variable
37671 ** with that name.  If there is no variable with the given name,
37672 ** return 0.
37673 */
37674 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
37675   Vdbe *p = (Vdbe*)pStmt;
37676   int i;
37677   if( p==0 ){
37678     return 0;
37679   }
37680   createVarMap(p); 
37681   if( zName ){
37682     for(i=0; i<p->nVar; i++){
37683       const char *z = p->azVar[i];
37684       if( z && strcmp(z,zName)==0 ){
37685         return i+1;
37686       }
37687     }
37688   }
37689   return 0;
37690 }
37691
37692 /*
37693 ** Transfer all bindings from the first statement over to the second.
37694 ** If the two statements contain a different number of bindings, then
37695 ** an SQLITE_ERROR is returned.
37696 */
37697 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
37698   Vdbe *pFrom = (Vdbe*)pFromStmt;
37699   Vdbe *pTo = (Vdbe*)pToStmt;
37700   int i, rc = SQLITE_OK;
37701   if( (pFrom->magic!=VDBE_MAGIC_RUN && pFrom->magic!=VDBE_MAGIC_HALT)
37702     || (pTo->magic!=VDBE_MAGIC_RUN && pTo->magic!=VDBE_MAGIC_HALT)
37703     || pTo->db!=pFrom->db ){
37704     return SQLITE_MISUSE;
37705   }
37706   if( pFrom->nVar!=pTo->nVar ){
37707     return SQLITE_ERROR;
37708   }
37709   sqlite3_mutex_enter(pTo->db->mutex);
37710   for(i=0; rc==SQLITE_OK && i<pFrom->nVar; i++){
37711     sqlite3MallocDisallow();
37712     rc = sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
37713     sqlite3MallocAllow();
37714   }
37715   sqlite3_mutex_leave(pTo->db->mutex);
37716   assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
37717   return rc;
37718 }
37719
37720 /*
37721 ** Return the sqlite3* database handle to which the prepared statement given
37722 ** in the argument belongs.  This is the same database handle that was
37723 ** the first argument to the sqlite3_prepare() that was used to create
37724 ** the statement in the first place.
37725 */
37726 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
37727   return pStmt ? ((Vdbe*)pStmt)->db : 0;
37728 }
37729
37730 /************** End of vdbeapi.c *********************************************/
37731 /************** Begin file vdbe.c ********************************************/
37732 /*
37733 ** 2001 September 15
37734 **
37735 ** The author disclaims copyright to this source code.  In place of
37736 ** a legal notice, here is a blessing:
37737 **
37738 **    May you do good and not evil.
37739 **    May you find forgiveness for yourself and forgive others.
37740 **    May you share freely, never taking more than you give.
37741 **
37742 *************************************************************************
37743 ** The code in this file implements execution method of the 
37744 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
37745 ** handles housekeeping details such as creating and deleting
37746 ** VDBE instances.  This file is solely interested in executing
37747 ** the VDBE program.
37748 **
37749 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
37750 ** to a VDBE.
37751 **
37752 ** The SQL parser generates a program which is then executed by
37753 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
37754 ** similar in form to assembly language.  The program consists of
37755 ** a linear sequence of operations.  Each operation has an opcode 
37756 ** and 3 operands.  Operands P1 and P2 are integers.  Operand P3 
37757 ** is a null-terminated string.   The P2 operand must be non-negative.
37758 ** Opcodes will typically ignore one or more operands.  Many opcodes
37759 ** ignore all three operands.
37760 **
37761 ** Computation results are stored on a stack.  Each entry on the
37762 ** stack is either an integer, a null-terminated string, a floating point
37763 ** number, or the SQL "NULL" value.  An inplicit conversion from one
37764 ** type to the other occurs as necessary.
37765 ** 
37766 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
37767 ** function which does the work of interpreting a VDBE program.
37768 ** But other routines are also provided to help in building up
37769 ** a program instruction by instruction.
37770 **
37771 ** Various scripts scan this source file in order to generate HTML
37772 ** documentation, headers files, or other derived files.  The formatting
37773 ** of the code in this file is, therefore, important.  See other comments
37774 ** in this file for details.  If in doubt, do not deviate from existing
37775 ** commenting and indentation practices when changing or adding code.
37776 **
37777 ** $Id: vdbe.c,v 1.660 2007/12/13 21:54:11 drh Exp $
37778 */
37779
37780 /*
37781 ** The following global variable is incremented every time a cursor
37782 ** moves, either by the OP_MoveXX, OP_Next, or OP_Prev opcodes.  The test
37783 ** procedures use this information to make sure that indices are
37784 ** working correctly.  This variable has no function other than to
37785 ** help verify the correct operation of the library.
37786 */
37787 #ifdef SQLITE_TEST
37788 SQLITE_API int sqlite3_search_count = 0;
37789 #endif
37790
37791 /*
37792 ** When this global variable is positive, it gets decremented once before
37793 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
37794 ** field of the sqlite3 structure is set in order to simulate and interrupt.
37795 **
37796 ** This facility is used for testing purposes only.  It does not function
37797 ** in an ordinary build.
37798 */
37799 #ifdef SQLITE_TEST
37800 SQLITE_API int sqlite3_interrupt_count = 0;
37801 #endif
37802
37803 /*
37804 ** The next global variable is incremented each type the OP_Sort opcode
37805 ** is executed.  The test procedures use this information to make sure that
37806 ** sorting is occurring or not occuring at appropriate times.   This variable
37807 ** has no function other than to help verify the correct operation of the
37808 ** library.
37809 */
37810 #ifdef SQLITE_TEST
37811 SQLITE_API int sqlite3_sort_count = 0;
37812 #endif
37813
37814 /*
37815 ** The next global variable records the size of the largest MEM_Blob
37816 ** or MEM_Str that has appeared on the VDBE stack.  The test procedures
37817 ** use this information to make sure that the zero-blob functionality
37818 ** is working correctly.   This variable has no function other than to
37819 ** help verify the correct operation of the library.
37820 */
37821 #ifdef SQLITE_TEST
37822 SQLITE_API int sqlite3_max_blobsize = 0;
37823 #endif
37824
37825 /*
37826 ** Release the memory associated with the given stack level.  This
37827 ** leaves the Mem.flags field in an inconsistent state.
37828 */
37829 #define Release(P) if((P)->flags&MEM_Dyn){ sqlite3VdbeMemRelease(P); }
37830
37831 /*
37832 ** Convert the given stack entity into a string if it isn't one
37833 ** already. Return non-zero if a malloc() fails.
37834 */
37835 #define Stringify(P, enc) \
37836    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
37837      { goto no_mem; }
37838
37839 /*
37840 ** The header of a record consists of a sequence variable-length integers.
37841 ** These integers are almost always small and are encoded as a single byte.
37842 ** The following macro takes advantage this fact to provide a fast decode
37843 ** of the integers in a record header.  It is faster for the common case
37844 ** where the integer is a single byte.  It is a little slower when the
37845 ** integer is two or more bytes.  But overall it is faster.
37846 **
37847 ** The following expressions are equivalent:
37848 **
37849 **     x = sqlite3GetVarint32( A, &B );
37850 **
37851 **     x = GetVarint( A, B );
37852 **
37853 */
37854 #define GetVarint(A,B)  ((B = *(A))<=0x7f ? 1 : sqlite3GetVarint32(A, &B))
37855
37856 /*
37857 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
37858 ** a pointer to a dynamically allocated string where some other entity
37859 ** is responsible for deallocating that string.  Because the stack entry
37860 ** does not control the string, it might be deleted without the stack
37861 ** entry knowing it.
37862 **
37863 ** This routine converts an ephemeral string into a dynamically allocated
37864 ** string that the stack entry itself controls.  In other words, it
37865 ** converts an MEM_Ephem string into an MEM_Dyn string.
37866 */
37867 #define Deephemeralize(P) \
37868    if( ((P)->flags&MEM_Ephem)!=0 \
37869        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
37870
37871 /*
37872 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
37873 ** P if required.
37874 */
37875 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
37876
37877 /*
37878 ** Argument pMem points at a memory cell that will be passed to a
37879 ** user-defined function or returned to the user as the result of a query.
37880 ** The second argument, 'db_enc' is the text encoding used by the vdbe for
37881 ** stack variables.  This routine sets the pMem->enc and pMem->type
37882 ** variables used by the sqlite3_value_*() routines.
37883 */
37884 #define storeTypeInfo(A,B) _storeTypeInfo(A)
37885 static void _storeTypeInfo(Mem *pMem){
37886   int flags = pMem->flags;
37887   if( flags & MEM_Null ){
37888     pMem->type = SQLITE_NULL;
37889   }
37890   else if( flags & MEM_Int ){
37891     pMem->type = SQLITE_INTEGER;
37892   }
37893   else if( flags & MEM_Real ){
37894     pMem->type = SQLITE_FLOAT;
37895   }
37896   else if( flags & MEM_Str ){
37897     pMem->type = SQLITE_TEXT;
37898   }else{
37899     pMem->type = SQLITE_BLOB;
37900   }
37901 }
37902
37903 /*
37904 ** Pop the stack N times.
37905 */
37906 static void popStack(Mem **ppTos, int N){
37907   Mem *pTos = *ppTos;
37908   while( N>0 ){
37909     N--;
37910     Release(pTos);
37911     pTos--;
37912   }
37913   *ppTos = pTos;
37914 }
37915
37916 /*
37917 ** Allocate cursor number iCur.  Return a pointer to it.  Return NULL
37918 ** if we run out of memory.
37919 */
37920 static Cursor *allocateCursor(Vdbe *p, int iCur, int iDb){
37921   Cursor *pCx;
37922   assert( iCur<p->nCursor );
37923   if( p->apCsr[iCur] ){
37924     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
37925   }
37926   p->apCsr[iCur] = pCx = sqlite3MallocZero( sizeof(Cursor) );
37927   if( pCx ){
37928     pCx->iDb = iDb;
37929   }
37930   return pCx;
37931 }
37932
37933 /*
37934 ** Try to convert a value into a numeric representation if we can
37935 ** do so without loss of information.  In other words, if the string
37936 ** looks like a number, convert it into a number.  If it does not
37937 ** look like a number, leave it alone.
37938 */
37939 static void applyNumericAffinity(Mem *pRec){
37940   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
37941     int realnum;
37942     sqlite3VdbeMemNulTerminate(pRec);
37943     if( (pRec->flags&MEM_Str)
37944          && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
37945       i64 value;
37946       sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
37947       if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
37948         sqlite3VdbeMemRelease(pRec);
37949         pRec->u.i = value;
37950         pRec->flags = MEM_Int;
37951       }else{
37952         sqlite3VdbeMemRealify(pRec);
37953       }
37954     }
37955   }
37956 }
37957
37958 /*
37959 ** Processing is determine by the affinity parameter:
37960 **
37961 ** SQLITE_AFF_INTEGER:
37962 ** SQLITE_AFF_REAL:
37963 ** SQLITE_AFF_NUMERIC:
37964 **    Try to convert pRec to an integer representation or a 
37965 **    floating-point representation if an integer representation
37966 **    is not possible.  Note that the integer representation is
37967 **    always preferred, even if the affinity is REAL, because
37968 **    an integer representation is more space efficient on disk.
37969 **
37970 ** SQLITE_AFF_TEXT:
37971 **    Convert pRec to a text representation.
37972 **
37973 ** SQLITE_AFF_NONE:
37974 **    No-op.  pRec is unchanged.
37975 */
37976 static void applyAffinity(
37977   Mem *pRec,          /* The value to apply affinity to */
37978   char affinity,      /* The affinity to be applied */
37979   u8 enc              /* Use this text encoding */
37980 ){
37981   if( affinity==SQLITE_AFF_TEXT ){
37982     /* Only attempt the conversion to TEXT if there is an integer or real
37983     ** representation (blob and NULL do not get converted) but no string
37984     ** representation.
37985     */
37986     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
37987       sqlite3VdbeMemStringify(pRec, enc);
37988     }
37989     pRec->flags &= ~(MEM_Real|MEM_Int);
37990   }else if( affinity!=SQLITE_AFF_NONE ){
37991     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
37992              || affinity==SQLITE_AFF_NUMERIC );
37993     applyNumericAffinity(pRec);
37994     if( pRec->flags & MEM_Real ){
37995       sqlite3VdbeIntegerAffinity(pRec);
37996     }
37997   }
37998 }
37999
38000 /*
38001 ** Try to convert the type of a function argument or a result column
38002 ** into a numeric representation.  Use either INTEGER or REAL whichever
38003 ** is appropriate.  But only do the conversion if it is possible without
38004 ** loss of information and return the revised type of the argument.
38005 **
38006 ** This is an EXPERIMENTAL api and is subject to change or removal.
38007 */
38008 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
38009   Mem *pMem = (Mem*)pVal;
38010   applyNumericAffinity(pMem);
38011   storeTypeInfo(pMem, 0);
38012   return pMem->type;
38013 }
38014
38015 /*
38016 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
38017 ** not the internal Mem* type.
38018 */
38019 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
38020   sqlite3_value *pVal, 
38021   u8 affinity, 
38022   u8 enc
38023 ){
38024   applyAffinity((Mem *)pVal, affinity, enc);
38025 }
38026
38027 #ifdef SQLITE_DEBUG
38028 /*
38029 ** Write a nice string representation of the contents of cell pMem
38030 ** into buffer zBuf, length nBuf.
38031 */
38032 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
38033   char *zCsr = zBuf;
38034   int f = pMem->flags;
38035
38036   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
38037
38038   if( f&MEM_Blob ){
38039     int i;
38040     char c;
38041     if( f & MEM_Dyn ){
38042       c = 'z';
38043       assert( (f & (MEM_Static|MEM_Ephem))==0 );
38044     }else if( f & MEM_Static ){
38045       c = 't';
38046       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
38047     }else if( f & MEM_Ephem ){
38048       c = 'e';
38049       assert( (f & (MEM_Static|MEM_Dyn))==0 );
38050     }else{
38051       c = 's';
38052     }
38053
38054     sqlite3_snprintf(100, zCsr, "%c", c);
38055     zCsr += strlen(zCsr);
38056     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
38057     zCsr += strlen(zCsr);
38058     for(i=0; i<16 && i<pMem->n; i++){
38059       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
38060       zCsr += strlen(zCsr);
38061     }
38062     for(i=0; i<16 && i<pMem->n; i++){
38063       char z = pMem->z[i];
38064       if( z<32 || z>126 ) *zCsr++ = '.';
38065       else *zCsr++ = z;
38066     }
38067
38068     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
38069     zCsr += strlen(zCsr);
38070     if( f & MEM_Zero ){
38071       sqlite3_snprintf(100, zCsr,"+%lldz",pMem->u.i);
38072       zCsr += strlen(zCsr);
38073     }
38074     *zCsr = '\0';
38075   }else if( f & MEM_Str ){
38076     int j, k;
38077     zBuf[0] = ' ';
38078     if( f & MEM_Dyn ){
38079       zBuf[1] = 'z';
38080       assert( (f & (MEM_Static|MEM_Ephem))==0 );
38081     }else if( f & MEM_Static ){
38082       zBuf[1] = 't';
38083       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
38084     }else if( f & MEM_Ephem ){
38085       zBuf[1] = 'e';
38086       assert( (f & (MEM_Static|MEM_Dyn))==0 );
38087     }else{
38088       zBuf[1] = 's';
38089     }
38090     k = 2;
38091     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
38092     k += strlen(&zBuf[k]);
38093     zBuf[k++] = '[';
38094     for(j=0; j<15 && j<pMem->n; j++){
38095       u8 c = pMem->z[j];
38096       if( c>=0x20 && c<0x7f ){
38097         zBuf[k++] = c;
38098       }else{
38099         zBuf[k++] = '.';
38100       }
38101     }
38102     zBuf[k++] = ']';
38103     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
38104     k += strlen(&zBuf[k]);
38105     zBuf[k++] = 0;
38106   }
38107 }
38108 #endif
38109
38110
38111 #ifdef VDBE_PROFILE
38112 /*
38113 ** The following routine only works on pentium-class processors.
38114 ** It uses the RDTSC opcode to read the cycle count value out of the
38115 ** processor and returns that value.  This can be used for high-res
38116 ** profiling.
38117 */
38118 __inline__ unsigned long long int hwtime(void){
38119   unsigned long long int x;
38120   __asm__("rdtsc\n\t"
38121           "mov %%edx, %%ecx\n\t"
38122           :"=A" (x));
38123   return x;
38124 }
38125 #endif
38126
38127 /*
38128 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
38129 ** sqlite3_interrupt() routine has been called.  If it has been, then
38130 ** processing of the VDBE program is interrupted.
38131 **
38132 ** This macro added to every instruction that does a jump in order to
38133 ** implement a loop.  This test used to be on every single instruction,
38134 ** but that meant we more testing that we needed.  By only testing the
38135 ** flag on jump instructions, we get a (small) speed improvement.
38136 */
38137 #define CHECK_FOR_INTERRUPT \
38138    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
38139
38140
38141 /*
38142 ** Execute as much of a VDBE program as we can then return.
38143 **
38144 ** sqlite3VdbeMakeReady() must be called before this routine in order to
38145 ** close the program with a final OP_Halt and to set up the callbacks
38146 ** and the error message pointer.
38147 **
38148 ** Whenever a row or result data is available, this routine will either
38149 ** invoke the result callback (if there is one) or return with
38150 ** SQLITE_ROW.
38151 **
38152 ** If an attempt is made to open a locked database, then this routine
38153 ** will either invoke the busy callback (if there is one) or it will
38154 ** return SQLITE_BUSY.
38155 **
38156 ** If an error occurs, an error message is written to memory obtained
38157 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
38158 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
38159 **
38160 ** If the callback ever returns non-zero, then the program exits
38161 ** immediately.  There will be no error message but the p->rc field is
38162 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
38163 **
38164 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
38165 ** routine to return SQLITE_ERROR.
38166 **
38167 ** Other fatal errors return SQLITE_ERROR.
38168 **
38169 ** After this routine has finished, sqlite3VdbeFinalize() should be
38170 ** used to clean up the mess that was left behind.
38171 */
38172 SQLITE_PRIVATE int sqlite3VdbeExec(
38173   Vdbe *p                    /* The VDBE */
38174 ){
38175   int pc;                    /* The program counter */
38176   Op *pOp;                   /* Current operation */
38177   int rc = SQLITE_OK;        /* Value to return */
38178   sqlite3 *db = p->db;       /* The database */
38179   u8 encoding = ENC(db);     /* The database encoding */
38180   Mem *pTos;                 /* Top entry in the operand stack */
38181 #ifdef VDBE_PROFILE
38182   unsigned long long start;  /* CPU clock count at start of opcode */
38183   int origPc;                /* Program counter at start of opcode */
38184 #endif
38185 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
38186   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
38187 #endif
38188 #ifndef NDEBUG
38189   Mem *pStackLimit;
38190 #endif
38191
38192   if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
38193   assert( db->magic==SQLITE_MAGIC_BUSY );
38194   pTos = p->pTos;
38195   sqlite3BtreeMutexArrayEnter(&p->aMutex);
38196   if( p->rc==SQLITE_NOMEM ){
38197     /* This happens if a malloc() inside a call to sqlite3_column_text() or
38198     ** sqlite3_column_text16() failed.  */
38199     goto no_mem;
38200   }
38201   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
38202   p->rc = SQLITE_OK;
38203   assert( p->explain==0 );
38204   if( p->popStack ){
38205     popStack(&pTos, p->popStack);
38206     p->popStack = 0;
38207   }
38208   p->resOnStack = 0;
38209   db->busyHandler.nBusy = 0;
38210   CHECK_FOR_INTERRUPT;
38211   sqlite3VdbeIOTraceSql(p);
38212 #ifdef SQLITE_DEBUG
38213   if( (p->db->flags & SQLITE_VdbeListing)!=0
38214     || sqlite3OsAccess(db->pVfs, "vdbe_explain", SQLITE_ACCESS_EXISTS)
38215   ){
38216     int i;
38217     printf("VDBE Program Listing:\n");
38218     sqlite3VdbePrintSql(p);
38219     for(i=0; i<p->nOp; i++){
38220       sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
38221     }
38222   }
38223   if( sqlite3OsAccess(db->pVfs, "vdbe_trace", SQLITE_ACCESS_EXISTS) ){
38224     p->trace = stdout;
38225   }
38226 #endif
38227   for(pc=p->pc; rc==SQLITE_OK; pc++){
38228     assert( pc>=0 && pc<p->nOp );
38229     assert( pTos<=&p->aStack[pc] );
38230     if( db->mallocFailed ) goto no_mem;
38231 #ifdef VDBE_PROFILE
38232     origPc = pc;
38233     start = hwtime();
38234 #endif
38235     pOp = &p->aOp[pc];
38236
38237     /* Only allow tracing if SQLITE_DEBUG is defined.
38238     */
38239 #ifdef SQLITE_DEBUG
38240     if( p->trace ){
38241       if( pc==0 ){
38242         printf("VDBE Execution Trace:\n");
38243         sqlite3VdbePrintSql(p);
38244       }
38245       sqlite3VdbePrintOp(p->trace, pc, pOp);
38246     }
38247     if( p->trace==0 && pc==0 
38248      && sqlite3OsAccess(db->pVfs, "vdbe_sqltrace", SQLITE_ACCESS_EXISTS) ){
38249       sqlite3VdbePrintSql(p);
38250     }
38251 #endif
38252       
38253
38254     /* Check to see if we need to simulate an interrupt.  This only happens
38255     ** if we have a special test build.
38256     */
38257 #ifdef SQLITE_TEST
38258     if( sqlite3_interrupt_count>0 ){
38259       sqlite3_interrupt_count--;
38260       if( sqlite3_interrupt_count==0 ){
38261         sqlite3_interrupt(db);
38262       }
38263     }
38264 #endif
38265
38266 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
38267     /* Call the progress callback if it is configured and the required number
38268     ** of VDBE ops have been executed (either since this invocation of
38269     ** sqlite3VdbeExec() or since last time the progress callback was called).
38270     ** If the progress callback returns non-zero, exit the virtual machine with
38271     ** a return code SQLITE_ABORT.
38272     */
38273     if( db->xProgress ){
38274       if( db->nProgressOps==nProgressOps ){
38275         int prc;
38276         if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
38277         prc =db->xProgress(db->pProgressArg);
38278         if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
38279         if( prc!=0 ){
38280           rc = SQLITE_INTERRUPT;
38281           goto vdbe_halt;
38282         }
38283         nProgressOps = 0;
38284       }
38285       nProgressOps++;
38286     }
38287 #endif
38288
38289 #ifndef NDEBUG
38290     /* This is to check that the return value of static function
38291     ** opcodeNoPush() (see vdbeaux.c) returns values that match the
38292     ** implementation of the virtual machine in this file. If
38293     ** opcodeNoPush() returns non-zero, then the stack is guarenteed
38294     ** not to grow when the opcode is executed. If it returns zero, then
38295     ** the stack may grow by at most 1.
38296     **
38297     ** The global wrapper function sqlite3VdbeOpcodeUsesStack() is not 
38298     ** available if NDEBUG is defined at build time.
38299     */ 
38300     pStackLimit = pTos;
38301     if( !sqlite3VdbeOpcodeNoPush(pOp->opcode) ){
38302       pStackLimit++;
38303     }
38304 #endif
38305
38306     switch( pOp->opcode ){
38307
38308 /*****************************************************************************
38309 ** What follows is a massive switch statement where each case implements a
38310 ** separate instruction in the virtual machine.  If we follow the usual
38311 ** indentation conventions, each case should be indented by 6 spaces.  But
38312 ** that is a lot of wasted space on the left margin.  So the code within
38313 ** the switch statement will break with convention and be flush-left. Another
38314 ** big comment (similar to this one) will mark the point in the code where
38315 ** we transition back to normal indentation.
38316 **
38317 ** The formatting of each case is important.  The makefile for SQLite
38318 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
38319 ** file looking for lines that begin with "case OP_".  The opcodes.h files
38320 ** will be filled with #defines that give unique integer values to each
38321 ** opcode and the opcodes.c file is filled with an array of strings where
38322 ** each string is the symbolic name for the corresponding opcode.  If the
38323 ** case statement is followed by a comment of the form "/# same as ... #/"
38324 ** that comment is used to determine the particular value of the opcode.
38325 **
38326 ** If a comment on the same line as the "case OP_" construction contains
38327 ** the word "no-push", then the opcode is guarenteed not to grow the 
38328 ** vdbe stack when it is executed. See function opcode() in
38329 ** vdbeaux.c for details.
38330 **
38331 ** Documentation about VDBE opcodes is generated by scanning this file
38332 ** for lines of that contain "Opcode:".  That line and all subsequent
38333 ** comment lines are used in the generation of the opcode.html documentation
38334 ** file.
38335 **
38336 ** SUMMARY:
38337 **
38338 **     Formatting is important to scripts that scan this file.
38339 **     Do not deviate from the formatting style currently in use.
38340 **
38341 *****************************************************************************/
38342
38343 /* Opcode:  Goto * P2 *
38344 **
38345 ** An unconditional jump to address P2.
38346 ** The next instruction executed will be 
38347 ** the one at index P2 from the beginning of
38348 ** the program.
38349 */
38350 case OP_Goto: {             /* no-push */
38351   CHECK_FOR_INTERRUPT;
38352   pc = pOp->p2 - 1;
38353   break;
38354 }
38355
38356 /* Opcode:  Gosub * P2 *
38357 **
38358 ** Push the current address plus 1 onto the return address stack
38359 ** and then jump to address P2.
38360 **
38361 ** The return address stack is of limited depth.  If too many
38362 ** OP_Gosub operations occur without intervening OP_Returns, then
38363 ** the return address stack will fill up and processing will abort
38364 ** with a fatal error.
38365 */
38366 case OP_Gosub: {            /* no-push */
38367   assert( p->returnDepth<sizeof(p->returnStack)/sizeof(p->returnStack[0]) );
38368   p->returnStack[p->returnDepth++] = pc+1;
38369   pc = pOp->p2 - 1;
38370   break;
38371 }
38372
38373 /* Opcode:  Return * * *
38374 **
38375 ** Jump immediately to the next instruction after the last unreturned
38376 ** OP_Gosub.  If an OP_Return has occurred for all OP_Gosubs, then
38377 ** processing aborts with a fatal error.
38378 */
38379 case OP_Return: {           /* no-push */
38380   assert( p->returnDepth>0 );
38381   p->returnDepth--;
38382   pc = p->returnStack[p->returnDepth] - 1;
38383   break;
38384 }
38385
38386 /* Opcode:  Halt P1 P2 P3
38387 **
38388 ** Exit immediately.  All open cursors, Fifos, etc are closed
38389 ** automatically.
38390 **
38391 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
38392 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
38393 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
38394 ** whether or not to rollback the current transaction.  Do not rollback
38395 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
38396 ** then back out all changes that have occurred during this execution of the
38397 ** VDBE, but do not rollback the transaction. 
38398 **
38399 ** If P3 is not null then it is an error message string.
38400 **
38401 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
38402 ** every program.  So a jump past the last instruction of the program
38403 ** is the same as executing Halt.
38404 */
38405 case OP_Halt: {            /* no-push */
38406   p->pTos = pTos;
38407   p->rc = pOp->p1;
38408   p->pc = pc;
38409   p->errorAction = pOp->p2;
38410   if( pOp->p3 ){
38411     sqlite3SetString(&p->zErrMsg, pOp->p3, (char*)0);
38412   }
38413   rc = sqlite3VdbeHalt(p);
38414   assert( rc==SQLITE_BUSY || rc==SQLITE_OK );
38415   if( rc==SQLITE_BUSY ){
38416     p->rc = rc = SQLITE_BUSY;
38417   }else{
38418     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
38419   }
38420   goto vdbe_return;
38421 }
38422
38423 /* Opcode:  StackDepth P1 * *
38424 **
38425 ** If P1 is less than zero, then store the current stack depth
38426 ** in P1.  If P1 is zero or greater, verify that the current stack
38427 ** depth is equal to P1 and throw an exception if it is not.
38428 **
38429 ** This opcode is used for internal consistency checking.
38430 */
38431 case OP_StackDepth: {       /* no-push */
38432   int n = pTos - p->aStack + 1;
38433   if( pOp->p1<0 ){
38434     pOp->p1 = n;
38435   }else if( pOp->p1!=n ){
38436     p->pTos = pTos;
38437     p->rc = rc = SQLITE_INTERNAL;
38438     p->pc = pc;
38439     p->errorAction = OE_Rollback;
38440     sqlite3SetString(&p->zErrMsg, "internal error: VDBE stack leak", (char*)0);
38441     goto vdbe_return;
38442   }
38443   break;
38444 }
38445
38446 /* Opcode: Integer P1 * *
38447 **
38448 ** The 32-bit integer value P1 is pushed onto the stack.
38449 */
38450 case OP_Integer: {
38451   pTos++;
38452   pTos->flags = MEM_Int;
38453   pTos->u.i = pOp->p1;
38454   break;
38455 }
38456
38457 /* Opcode: Int64 * * P3
38458 **
38459 ** P3 is a pointer to a 64-bit integer value.
38460 ** Push  that value onto  the stack.
38461 */
38462 case OP_Int64: {
38463   pTos++;
38464   assert( pOp->p3!=0 );
38465   pTos->flags = MEM_Int;
38466   memcpy(&pTos->u.i, pOp->p3, 8);
38467   break;
38468 }
38469
38470 /* Opcode: Real * * P3
38471 **
38472 ** P3 is a pointer to a 64-bit floating point value.  Push that value
38473 ** onto the stack.
38474 */
38475 case OP_Real: {            /* same as TK_FLOAT, */
38476   pTos++;
38477   pTos->flags = MEM_Real;
38478   memcpy(&pTos->r, pOp->p3, 8);
38479   break;
38480 }
38481
38482 /* Opcode: String8 * * P3
38483 **
38484 ** P3 points to a nul terminated UTF-8 string. This opcode is transformed 
38485 ** into an OP_String before it is executed for the first time.
38486 */
38487 case OP_String8: {         /* same as TK_STRING */
38488   assert( pOp->p3!=0 );
38489   pOp->opcode = OP_String;
38490   pOp->p1 = strlen(pOp->p3);
38491   assert( SQLITE_MAX_SQL_LENGTH <= SQLITE_MAX_LENGTH );
38492   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
38493
38494 #ifndef SQLITE_OMIT_UTF16
38495   if( encoding!=SQLITE_UTF8 ){
38496     pTos++;
38497     sqlite3VdbeMemSetStr(pTos, pOp->p3, -1, SQLITE_UTF8, SQLITE_STATIC);
38498     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pTos, encoding) ) goto no_mem;
38499     if( SQLITE_OK!=sqlite3VdbeMemDynamicify(pTos) ) goto no_mem;
38500     pTos->flags &= ~(MEM_Dyn);
38501     pTos->flags |= MEM_Static;
38502     if( pOp->p3type==P3_DYNAMIC ){
38503       sqlite3_free(pOp->p3);
38504     }
38505     pOp->p3type = P3_DYNAMIC;
38506     pOp->p3 = pTos->z;
38507     pOp->p1 = pTos->n;
38508     assert( pOp->p1 <= SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */
38509     break;
38510   }
38511 #endif
38512   /* Otherwise fall through to the next case, OP_String */
38513 }
38514   
38515 /* Opcode: String P1 * P3
38516 **
38517 ** The string value P3 of length P1 (bytes) is pushed onto the stack.
38518 */
38519 case OP_String: {
38520   assert( pOp->p1 <= SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */
38521   pTos++;
38522   assert( pOp->p3!=0 );
38523   pTos->flags = MEM_Str|MEM_Static|MEM_Term;
38524   pTos->z = pOp->p3;
38525   pTos->n = pOp->p1;
38526   pTos->enc = encoding;
38527   break;
38528 }
38529
38530 /* Opcode: Null * * *
38531 **
38532 ** Push a NULL onto the stack.
38533 */
38534 case OP_Null: {
38535   pTos++;
38536   pTos->flags = MEM_Null;
38537   pTos->n = 0;
38538   break;
38539 }
38540
38541
38542 #ifndef SQLITE_OMIT_BLOB_LITERAL
38543 /* Opcode: HexBlob * * P3
38544 **
38545 ** P3 is an UTF-8 SQL hex encoding of a blob. The blob is pushed onto the
38546 ** vdbe stack.
38547 **
38548 ** The first time this instruction executes, in transforms itself into a
38549 ** 'Blob' opcode with a binary blob as P3.
38550 */
38551 case OP_HexBlob: {            /* same as TK_BLOB */
38552   pOp->opcode = OP_Blob;
38553   pOp->p1 = strlen(pOp->p3)/2;
38554   assert( SQLITE_MAX_SQL_LENGTH <= SQLITE_MAX_LENGTH );
38555   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
38556   if( pOp->p1 ){
38557     char *zBlob = sqlite3HexToBlob(db, pOp->p3);
38558     if( !zBlob ) goto no_mem;
38559     if( pOp->p3type==P3_DYNAMIC ){
38560       sqlite3_free(pOp->p3);
38561     }
38562     pOp->p3 = zBlob;
38563     pOp->p3type = P3_DYNAMIC;
38564   }else{
38565     if( pOp->p3type==P3_DYNAMIC ){
38566       sqlite3_free(pOp->p3);
38567     }
38568     pOp->p3type = P3_STATIC;
38569     pOp->p3 = "";
38570   }
38571
38572   /* Fall through to the next case, OP_Blob. */
38573 }
38574
38575 /* Opcode: Blob P1 * P3
38576 **
38577 ** P3 points to a blob of data P1 bytes long. Push this
38578 ** value onto the stack. This instruction is not coded directly
38579 ** by the compiler. Instead, the compiler layer specifies
38580 ** an OP_HexBlob opcode, with the hex string representation of
38581 ** the blob as P3. This opcode is transformed to an OP_Blob
38582 ** the first time it is executed.
38583 */
38584 case OP_Blob: {
38585   pTos++;
38586   assert( pOp->p1 <= SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */
38587   sqlite3VdbeMemSetStr(pTos, pOp->p3, pOp->p1, 0, 0);
38588   pTos->enc = encoding;
38589   break;
38590 }
38591 #endif /* SQLITE_OMIT_BLOB_LITERAL */
38592
38593 /* Opcode: Variable P1 * *
38594 **
38595 ** Push the value of variable P1 onto the stack.  A variable is
38596 ** an unknown in the original SQL string as handed to sqlite3_compile().
38597 ** Any occurance of the '?' character in the original SQL is considered
38598 ** a variable.  Variables in the SQL string are number from left to
38599 ** right beginning with 1.  The values of variables are set using the
38600 ** sqlite3_bind() API.
38601 */
38602 case OP_Variable: {
38603   int j = pOp->p1 - 1;
38604   Mem *pVar;
38605   assert( j>=0 && j<p->nVar );
38606
38607   pVar = &p->aVar[j];
38608   if( sqlite3VdbeMemTooBig(pVar) ){
38609     goto too_big;
38610   }
38611   pTos++;
38612   sqlite3VdbeMemShallowCopy(pTos, &p->aVar[j], MEM_Static);
38613   break;
38614 }
38615
38616 /* Opcode: Pop P1 * *
38617 **
38618 ** P1 elements are popped off of the top of stack and discarded.
38619 */
38620 case OP_Pop: {            /* no-push */
38621   assert( pOp->p1>=0 );
38622   popStack(&pTos, pOp->p1);
38623   assert( pTos>=&p->aStack[-1] );
38624   break;
38625 }
38626
38627 /* Opcode: Dup P1 P2 *
38628 **
38629 ** A copy of the P1-th element of the stack 
38630 ** is made and pushed onto the top of the stack.
38631 ** The top of the stack is element 0.  So the
38632 ** instruction "Dup 0 0 0" will make a copy of the
38633 ** top of the stack.
38634 **
38635 ** If the content of the P1-th element is a dynamically
38636 ** allocated string, then a new copy of that string
38637 ** is made if P2==0.  If P2!=0, then just a pointer
38638 ** to the string is copied.
38639 **
38640 ** Also see the Pull instruction.
38641 */
38642 case OP_Dup: {
38643   Mem *pFrom = &pTos[-pOp->p1];
38644   assert( pFrom<=pTos && pFrom>=p->aStack );
38645   pTos++;
38646   sqlite3VdbeMemShallowCopy(pTos, pFrom, MEM_Ephem);
38647   if( pOp->p2 ){
38648     Deephemeralize(pTos);
38649   }
38650   break;
38651 }
38652
38653 /* Opcode: Pull P1 * *
38654 **
38655 ** The P1-th element is removed from its current location on 
38656 ** the stack and pushed back on top of the stack.  The
38657 ** top of the stack is element 0, so "Pull 0 0 0" is
38658 ** a no-op.  "Pull 1 0 0" swaps the top two elements of
38659 ** the stack.
38660 **
38661 ** See also the Dup instruction.
38662 */
38663 case OP_Pull: {            /* no-push */
38664   Mem *pFrom = &pTos[-pOp->p1];
38665   int i;
38666   Mem ts;
38667
38668   ts = *pFrom;
38669   Deephemeralize(pTos);
38670   for(i=0; i<pOp->p1; i++, pFrom++){
38671     Deephemeralize(&pFrom[1]);
38672     assert( (pFrom[1].flags & MEM_Ephem)==0 );
38673     *pFrom = pFrom[1];
38674     if( pFrom->flags & MEM_Short ){
38675       assert( pFrom->flags & (MEM_Str|MEM_Blob) );
38676       assert( pFrom->z==pFrom[1].zShort );
38677       pFrom->z = pFrom->zShort;
38678     }
38679   }
38680   *pTos = ts;
38681   if( pTos->flags & MEM_Short ){
38682     assert( pTos->flags & (MEM_Str|MEM_Blob) );
38683     assert( pTos->z==pTos[-pOp->p1].zShort );
38684     pTos->z = pTos->zShort;
38685   }
38686   break;
38687 }
38688
38689 /* Opcode: Push P1 * *
38690 **
38691 ** Overwrite the value of the P1-th element down on the
38692 ** stack (P1==0 is the top of the stack) with the value
38693 ** of the top of the stack.  Then pop the top of the stack.
38694 */
38695 case OP_Push: {            /* no-push */
38696   Mem *pTo = &pTos[-pOp->p1];
38697
38698   assert( pTo>=p->aStack );
38699   sqlite3VdbeMemMove(pTo, pTos);
38700   pTos--;
38701   break;
38702 }
38703
38704 /* Opcode: Callback P1 * *
38705 **
38706 ** The top P1 values on the stack represent a single result row from
38707 ** a query.  This opcode causes the sqlite3_step() call to terminate
38708 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
38709 ** structure to provide access to the top P1 values as the result
38710 ** row.  When the sqlite3_step() function is run again, the top P1
38711 ** values will be automatically popped from the stack before the next
38712 ** instruction executes.
38713 */
38714 case OP_Callback: {            /* no-push */
38715   Mem *pMem;
38716   Mem *pFirstColumn;
38717   assert( p->nResColumn==pOp->p1 );
38718
38719   /* Data in the pager might be moved or changed out from under us
38720   ** in between the return from this sqlite3_step() call and the
38721   ** next call to sqlite3_step().  So deephermeralize everything on 
38722   ** the stack.  Note that ephemeral data is never stored in memory 
38723   ** cells so we do not have to worry about them.
38724   */
38725   pFirstColumn = &pTos[0-pOp->p1];
38726   for(pMem = p->aStack; pMem<pFirstColumn; pMem++){
38727     Deephemeralize(pMem);
38728   }
38729
38730   /* Invalidate all ephemeral cursor row caches */
38731   p->cacheCtr = (p->cacheCtr + 2)|1;
38732
38733   /* Make sure the results of the current row are \000 terminated
38734   ** and have an assigned type.  The results are deephemeralized as
38735   ** as side effect.
38736   */
38737   for(; pMem<=pTos; pMem++ ){
38738     sqlite3VdbeMemNulTerminate(pMem);
38739     storeTypeInfo(pMem, encoding);
38740   }
38741
38742   /* Set up the statement structure so that it will pop the current
38743   ** results from the stack when the statement returns.
38744   */
38745   p->resOnStack = 1;
38746   p->nCallback++;
38747   p->popStack = pOp->p1;
38748   p->pc = pc + 1;
38749   p->pTos = pTos;
38750   rc = SQLITE_ROW;
38751   goto vdbe_return;
38752 }
38753
38754 /* Opcode: Concat P1 P2 *
38755 **
38756 ** Look at the first P1+2 elements of the stack.  Append them all 
38757 ** together with the lowest element first.  The original P1+2 elements
38758 ** are popped from the stack if P2==0 and retained if P2==1.  If
38759 ** any element of the stack is NULL, then the result is NULL.
38760 **
38761 ** When P1==1, this routine makes a copy of the top stack element
38762 ** into memory obtained from sqlite3_malloc().
38763 */
38764 case OP_Concat: {           /* same as TK_CONCAT */
38765   char *zNew;
38766   i64 nByte;
38767   int nField;
38768   int i, j;
38769   Mem *pTerm;
38770
38771   /* Loop through the stack elements to see how long the result will be. */
38772   nField = pOp->p1 + 2;
38773   pTerm = &pTos[1-nField];
38774   nByte = 0;
38775   for(i=0; i<nField; i++, pTerm++){
38776     assert( pOp->p2==0 || (pTerm->flags&MEM_Str) );
38777     if( pTerm->flags&MEM_Null ){
38778       nByte = -1;
38779       break;
38780     }
38781     ExpandBlob(pTerm);
38782     Stringify(pTerm, encoding);
38783     nByte += pTerm->n;
38784   }
38785
38786   if( nByte<0 ){
38787     /* If nByte is less than zero, then there is a NULL value on the stack.
38788     ** In this case just pop the values off the stack (if required) and
38789     ** push on a NULL.
38790     */
38791     if( pOp->p2==0 ){
38792       popStack(&pTos, nField);
38793     }
38794     pTos++;
38795     pTos->flags = MEM_Null;
38796   }else{
38797     /* Otherwise malloc() space for the result and concatenate all the
38798     ** stack values.
38799     */
38800     if( nByte+2>SQLITE_MAX_LENGTH ){
38801       goto too_big;
38802     }
38803     zNew = sqlite3DbMallocRaw(db, nByte+2 );
38804     if( zNew==0 ) goto no_mem;
38805     j = 0;
38806     pTerm = &pTos[1-nField];
38807     for(i=j=0; i<nField; i++, pTerm++){
38808       int n = pTerm->n;
38809       assert( pTerm->flags & (MEM_Str|MEM_Blob) );
38810       memcpy(&zNew[j], pTerm->z, n);
38811       j += n;
38812     }
38813     zNew[j] = 0;
38814     zNew[j+1] = 0;
38815     assert( j==nByte );
38816
38817     if( pOp->p2==0 ){
38818       popStack(&pTos, nField);
38819     }
38820     pTos++;
38821     pTos->n = j;
38822     pTos->flags = MEM_Str|MEM_Dyn|MEM_Term;
38823     pTos->xDel = 0;
38824     pTos->enc = encoding;
38825     pTos->z = zNew;
38826   }
38827   break;
38828 }
38829
38830 /* Opcode: Add * * *
38831 **
38832 ** Pop the top two elements from the stack, add them together,
38833 ** and push the result back onto the stack.  If either element
38834 ** is a string then it is converted to a double using the atof()
38835 ** function before the addition.
38836 ** If either operand is NULL, the result is NULL.
38837 */
38838 /* Opcode: Multiply * * *
38839 **
38840 ** Pop the top two elements from the stack, multiply them together,
38841 ** and push the result back onto the stack.  If either element
38842 ** is a string then it is converted to a double using the atof()
38843 ** function before the multiplication.
38844 ** If either operand is NULL, the result is NULL.
38845 */
38846 /* Opcode: Subtract * * *
38847 **
38848 ** Pop the top two elements from the stack, subtract the
38849 ** first (what was on top of the stack) from the second (the
38850 ** next on stack)
38851 ** and push the result back onto the stack.  If either element
38852 ** is a string then it is converted to a double using the atof()
38853 ** function before the subtraction.
38854 ** If either operand is NULL, the result is NULL.
38855 */
38856 /* Opcode: Divide * * *
38857 **
38858 ** Pop the top two elements from the stack, divide the
38859 ** first (what was on top of the stack) from the second (the
38860 ** next on stack)
38861 ** and push the result back onto the stack.  If either element
38862 ** is a string then it is converted to a double using the atof()
38863 ** function before the division.  Division by zero returns NULL.
38864 ** If either operand is NULL, the result is NULL.
38865 */
38866 /* Opcode: Remainder * * *
38867 **
38868 ** Pop the top two elements from the stack, divide the
38869 ** first (what was on top of the stack) from the second (the
38870 ** next on stack)
38871 ** and push the remainder after division onto the stack.  If either element
38872 ** is a string then it is converted to a double using the atof()
38873 ** function before the division.  Division by zero returns NULL.
38874 ** If either operand is NULL, the result is NULL.
38875 */
38876 case OP_Add:                   /* same as TK_PLUS, no-push */
38877 case OP_Subtract:              /* same as TK_MINUS, no-push */
38878 case OP_Multiply:              /* same as TK_STAR, no-push */
38879 case OP_Divide:                /* same as TK_SLASH, no-push */
38880 case OP_Remainder: {           /* same as TK_REM, no-push */
38881   Mem *pNos = &pTos[-1];
38882   int flags;
38883   assert( pNos>=p->aStack );
38884   flags = pTos->flags | pNos->flags;
38885   if( (flags & MEM_Null)!=0 ){
38886     Release(pTos);
38887     pTos--;
38888     Release(pTos);
38889     pTos->flags = MEM_Null;
38890   }else if( (pTos->flags & pNos->flags & MEM_Int)==MEM_Int ){
38891     i64 a, b;
38892     a = pTos->u.i;
38893     b = pNos->u.i;
38894     switch( pOp->opcode ){
38895       case OP_Add:         b += a;       break;
38896       case OP_Subtract:    b -= a;       break;
38897       case OP_Multiply:    b *= a;       break;
38898       case OP_Divide: {
38899         if( a==0 ) goto divide_by_zero;
38900         /* Dividing the largest possible negative 64-bit integer (1<<63) by 
38901         ** -1 returns an integer to large to store in a 64-bit data-type. On
38902         ** some architectures, the value overflows to (1<<63). On others,
38903         ** a SIGFPE is issued. The following statement normalizes this
38904         ** behaviour so that all architectures behave as if integer 
38905         ** overflow occured.
38906         */
38907         if( a==-1 && b==(((i64)1)<<63) ) a = 1;
38908         b /= a;
38909         break;
38910       }
38911       default: {
38912         if( a==0 ) goto divide_by_zero;
38913         if( a==-1 ) a = 1;
38914         b %= a;
38915         break;
38916       }
38917     }
38918     Release(pTos);
38919     pTos--;
38920     Release(pTos);
38921     pTos->u.i = b;
38922     pTos->flags = MEM_Int;
38923   }else{
38924     double a, b;
38925     a = sqlite3VdbeRealValue(pTos);
38926     b = sqlite3VdbeRealValue(pNos);
38927     switch( pOp->opcode ){
38928       case OP_Add:         b += a;       break;
38929       case OP_Subtract:    b -= a;       break;
38930       case OP_Multiply:    b *= a;       break;
38931       case OP_Divide: {
38932         if( a==0.0 ) goto divide_by_zero;
38933         b /= a;
38934         break;
38935       }
38936       default: {
38937         i64 ia = (i64)a;
38938         i64 ib = (i64)b;
38939         if( ia==0 ) goto divide_by_zero;
38940         if( ia==-1 ) ia = 1;
38941         b = ib % ia;
38942         break;
38943       }
38944     }
38945     if( sqlite3_isnan(b) ){
38946       goto divide_by_zero;
38947     }
38948     Release(pTos);
38949     pTos--;
38950     Release(pTos);
38951     pTos->r = b;
38952     pTos->flags = MEM_Real;
38953     if( (flags & MEM_Real)==0 ){
38954       sqlite3VdbeIntegerAffinity(pTos);
38955     }
38956   }
38957   break;
38958
38959 divide_by_zero:
38960   Release(pTos);
38961   pTos--;
38962   Release(pTos);
38963   pTos->flags = MEM_Null;
38964   break;
38965 }
38966
38967 /* Opcode: CollSeq * * P3
38968 **
38969 ** P3 is a pointer to a CollSeq struct. If the next call to a user function
38970 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
38971 ** be returned. This is used by the built-in min(), max() and nullif()
38972 ** functions.
38973 **
38974 ** The interface used by the implementation of the aforementioned functions
38975 ** to retrieve the collation sequence set by this opcode is not available
38976 ** publicly, only to user functions defined in func.c.
38977 */
38978 case OP_CollSeq: {             /* no-push */
38979   assert( pOp->p3type==P3_COLLSEQ );
38980   break;
38981 }
38982
38983 /* Opcode: Function P1 P2 P3
38984 **
38985 ** Invoke a user function (P3 is a pointer to a Function structure that
38986 ** defines the function) with P2 arguments taken from the stack.  Pop all
38987 ** arguments from the stack and push back the result.
38988 **
38989 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
38990 ** function was determined to be constant at compile time. If the first
38991 ** argument was constant then bit 0 of P1 is set. This is used to determine
38992 ** whether meta data associated with a user function argument using the
38993 ** sqlite3_set_auxdata() API may be safely retained until the next
38994 ** invocation of this opcode.
38995 **
38996 ** See also: AggStep and AggFinal
38997 */
38998 case OP_Function: {
38999   int i;
39000   Mem *pArg;
39001   sqlite3_context ctx;
39002   sqlite3_value **apVal;
39003   int n = pOp->p2;
39004
39005   apVal = p->apArg;
39006   assert( apVal || n==0 );
39007
39008   pArg = &pTos[1-n];
39009   for(i=0; i<n; i++, pArg++){
39010     apVal[i] = pArg;
39011     storeTypeInfo(pArg, encoding);
39012   }
39013
39014   assert( pOp->p3type==P3_FUNCDEF || pOp->p3type==P3_VDBEFUNC );
39015   if( pOp->p3type==P3_FUNCDEF ){
39016     ctx.pFunc = (FuncDef*)pOp->p3;
39017     ctx.pVdbeFunc = 0;
39018   }else{
39019     ctx.pVdbeFunc = (VdbeFunc*)pOp->p3;
39020     ctx.pFunc = ctx.pVdbeFunc->pFunc;
39021   }
39022
39023   ctx.s.flags = MEM_Null;
39024   ctx.s.z = 0;
39025   ctx.s.xDel = 0;
39026   ctx.s.db = db;
39027   ctx.isError = 0;
39028   if( ctx.pFunc->needCollSeq ){
39029     assert( pOp>p->aOp );
39030     assert( pOp[-1].p3type==P3_COLLSEQ );
39031     assert( pOp[-1].opcode==OP_CollSeq );
39032     ctx.pColl = (CollSeq *)pOp[-1].p3;
39033   }
39034   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
39035   (*ctx.pFunc->xFunc)(&ctx, n, apVal);
39036   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
39037   if( db->mallocFailed ){
39038     /* Even though a malloc() has failed, the implementation of the
39039     ** user function may have called an sqlite3_result_XXX() function
39040     ** to return a value. The following call releases any resources
39041     ** associated with such a value.
39042     **
39043     ** Note: Maybe MemRelease() should be called if sqlite3SafetyOn()
39044     ** fails also (the if(...) statement above). But if people are
39045     ** misusing sqlite, they have bigger problems than a leaked value.
39046     */
39047     sqlite3VdbeMemRelease(&ctx.s);
39048     goto no_mem;
39049   }
39050   popStack(&pTos, n);
39051
39052   /* If any auxilary data functions have been called by this user function,
39053   ** immediately call the destructor for any non-static values.
39054   */
39055   if( ctx.pVdbeFunc ){
39056     sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
39057     pOp->p3 = (char *)ctx.pVdbeFunc;
39058     pOp->p3type = P3_VDBEFUNC;
39059   }
39060
39061   /* If the function returned an error, throw an exception */
39062   if( ctx.isError ){
39063     sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0);
39064     rc = SQLITE_ERROR;
39065   }
39066
39067   /* Copy the result of the function to the top of the stack */
39068   sqlite3VdbeChangeEncoding(&ctx.s, encoding);
39069   pTos++;
39070   pTos->flags = 0;
39071   sqlite3VdbeMemMove(pTos, &ctx.s);
39072   if( sqlite3VdbeMemTooBig(pTos) ){
39073     goto too_big;
39074   }
39075   break;
39076 }
39077
39078 /* Opcode: BitAnd * * *
39079 **
39080 ** Pop the top two elements from the stack.  Convert both elements
39081 ** to integers.  Push back onto the stack the bit-wise AND of the
39082 ** two elements.
39083 ** If either operand is NULL, the result is NULL.
39084 */
39085 /* Opcode: BitOr * * *
39086 **
39087 ** Pop the top two elements from the stack.  Convert both elements
39088 ** to integers.  Push back onto the stack the bit-wise OR of the
39089 ** two elements.
39090 ** If either operand is NULL, the result is NULL.
39091 */
39092 /* Opcode: ShiftLeft * * *
39093 **
39094 ** Pop the top two elements from the stack.  Convert both elements
39095 ** to integers.  Push back onto the stack the second element shifted
39096 ** left by N bits where N is the top element on the stack.
39097 ** If either operand is NULL, the result is NULL.
39098 */
39099 /* Opcode: ShiftRight * * *
39100 **
39101 ** Pop the top two elements from the stack.  Convert both elements
39102 ** to integers.  Push back onto the stack the second element shifted
39103 ** right by N bits where N is the top element on the stack.
39104 ** If either operand is NULL, the result is NULL.
39105 */
39106 case OP_BitAnd:                 /* same as TK_BITAND, no-push */
39107 case OP_BitOr:                  /* same as TK_BITOR, no-push */
39108 case OP_ShiftLeft:              /* same as TK_LSHIFT, no-push */
39109 case OP_ShiftRight: {           /* same as TK_RSHIFT, no-push */
39110   Mem *pNos = &pTos[-1];
39111   i64 a, b;
39112
39113   assert( pNos>=p->aStack );
39114   if( (pTos->flags | pNos->flags) & MEM_Null ){
39115     popStack(&pTos, 2);
39116     pTos++;
39117     pTos->flags = MEM_Null;
39118     break;
39119   }
39120   a = sqlite3VdbeIntValue(pNos);
39121   b = sqlite3VdbeIntValue(pTos);
39122   switch( pOp->opcode ){
39123     case OP_BitAnd:      a &= b;     break;
39124     case OP_BitOr:       a |= b;     break;
39125     case OP_ShiftLeft:   a <<= b;    break;
39126     case OP_ShiftRight:  a >>= b;    break;
39127     default:   /* CANT HAPPEN */     break;
39128   }
39129   Release(pTos);
39130   pTos--;
39131   Release(pTos);
39132   pTos->u.i = a;
39133   pTos->flags = MEM_Int;
39134   break;
39135 }
39136
39137 /* Opcode: AddImm  P1 * *
39138 ** 
39139 ** Add the value P1 to whatever is on top of the stack.  The result
39140 ** is always an integer.
39141 **
39142 ** To force the top of the stack to be an integer, just add 0.
39143 */
39144 case OP_AddImm: {            /* no-push */
39145   assert( pTos>=p->aStack );
39146   sqlite3VdbeMemIntegerify(pTos);
39147   pTos->u.i += pOp->p1;
39148   break;
39149 }
39150
39151 /* Opcode: ForceInt P1 P2 *
39152 **
39153 ** Convert the top of the stack into an integer.  If the current top of
39154 ** the stack is not numeric (meaning that is is a NULL or a string that
39155 ** does not look like an integer or floating point number) then pop the
39156 ** stack and jump to P2.  If the top of the stack is numeric then
39157 ** convert it into the least integer that is greater than or equal to its
39158 ** current value if P1==0, or to the least integer that is strictly
39159 ** greater than its current value if P1==1.
39160 */
39161 case OP_ForceInt: {            /* no-push */
39162   i64 v;
39163   assert( pTos>=p->aStack );
39164   applyAffinity(pTos, SQLITE_AFF_NUMERIC, encoding);
39165   if( (pTos->flags & (MEM_Int|MEM_Real))==0 ){
39166     Release(pTos);
39167     pTos--;
39168     pc = pOp->p2 - 1;
39169     break;
39170   }
39171   if( pTos->flags & MEM_Int ){
39172     v = pTos->u.i + (pOp->p1!=0);
39173   }else{
39174     /* FIX ME:  should this not be assert( pTos->flags & MEM_Real ) ??? */
39175     sqlite3VdbeMemRealify(pTos);
39176     v = (int)pTos->r;
39177     if( pTos->r>(double)v ) v++;
39178     if( pOp->p1 && pTos->r==(double)v ) v++;
39179   }
39180   Release(pTos);
39181   pTos->u.i = v;
39182   pTos->flags = MEM_Int;
39183   break;
39184 }
39185
39186 /* Opcode: MustBeInt P1 P2 *
39187 ** 
39188 ** Force the top of the stack to be an integer.  If the top of the
39189 ** stack is not an integer and cannot be converted into an integer
39190 ** without data loss, then jump immediately to P2, or if P2==0
39191 ** raise an SQLITE_MISMATCH exception.
39192 **
39193 ** If the top of the stack is not an integer and P2 is not zero and
39194 ** P1 is 1, then the stack is popped.  In all other cases, the depth
39195 ** of the stack is unchanged.
39196 */
39197 case OP_MustBeInt: {            /* no-push */
39198   assert( pTos>=p->aStack );
39199   applyAffinity(pTos, SQLITE_AFF_NUMERIC, encoding);
39200   if( (pTos->flags & MEM_Int)==0 ){
39201     if( pOp->p2==0 ){
39202       rc = SQLITE_MISMATCH;
39203       goto abort_due_to_error;
39204     }else{
39205       if( pOp->p1 ) popStack(&pTos, 1);
39206       pc = pOp->p2 - 1;
39207     }
39208   }else{
39209     Release(pTos);
39210     pTos->flags = MEM_Int;
39211   }
39212   break;
39213 }
39214
39215 /* Opcode: RealAffinity * * *
39216 **
39217 ** If the top of the stack is an integer, convert it to a real value.
39218 **
39219 ** This opcode is used when extracting information from a column that
39220 ** has REAL affinity.  Such column values may still be stored as
39221 ** integers, for space efficiency, but after extraction we want them
39222 ** to have only a real value.
39223 */
39224 case OP_RealAffinity: {                  /* no-push */
39225   assert( pTos>=p->aStack );
39226   if( pTos->flags & MEM_Int ){
39227     sqlite3VdbeMemRealify(pTos);
39228   }
39229   break;
39230 }
39231
39232 #ifndef SQLITE_OMIT_CAST
39233 /* Opcode: ToText * * *
39234 **
39235 ** Force the value on the top of the stack to be text.
39236 ** If the value is numeric, convert it to a string using the
39237 ** equivalent of printf().  Blob values are unchanged and
39238 ** are afterwards simply interpreted as text.
39239 **
39240 ** A NULL value is not changed by this routine.  It remains NULL.
39241 */
39242 case OP_ToText: {                  /* same as TK_TO_TEXT, no-push */
39243   assert( pTos>=p->aStack );
39244   if( pTos->flags & MEM_Null ) break;
39245   assert( MEM_Str==(MEM_Blob>>3) );
39246   pTos->flags |= (pTos->flags&MEM_Blob)>>3;
39247   applyAffinity(pTos, SQLITE_AFF_TEXT, encoding);
39248   rc = ExpandBlob(pTos);
39249   assert( pTos->flags & MEM_Str );
39250   pTos->flags &= ~(MEM_Int|MEM_Real|MEM_Blob);
39251   break;
39252 }
39253
39254 /* Opcode: ToBlob * * *
39255 **
39256 ** Force the value on the top of the stack to be a BLOB.
39257 ** If the value is numeric, convert it to a string first.
39258 ** Strings are simply reinterpreted as blobs with no change
39259 ** to the underlying data.
39260 **
39261 ** A NULL value is not changed by this routine.  It remains NULL.
39262 */
39263 case OP_ToBlob: {                  /* same as TK_TO_BLOB, no-push */
39264   assert( pTos>=p->aStack );
39265   if( pTos->flags & MEM_Null ) break;
39266   if( (pTos->flags & MEM_Blob)==0 ){
39267     applyAffinity(pTos, SQLITE_AFF_TEXT, encoding);
39268     assert( pTos->flags & MEM_Str );
39269     pTos->flags |= MEM_Blob;
39270   }
39271   pTos->flags &= ~(MEM_Int|MEM_Real|MEM_Str);
39272   break;
39273 }
39274
39275 /* Opcode: ToNumeric * * *
39276 **
39277 ** Force the value on the top of the stack to be numeric (either an
39278 ** integer or a floating-point number.)
39279 ** If the value is text or blob, try to convert it to an using the
39280 ** equivalent of atoi() or atof() and store 0 if no such conversion 
39281 ** is possible.
39282 **
39283 ** A NULL value is not changed by this routine.  It remains NULL.
39284 */
39285 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, no-push */
39286   assert( pTos>=p->aStack );
39287   if( (pTos->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
39288     sqlite3VdbeMemNumerify(pTos);
39289   }
39290   break;
39291 }
39292 #endif /* SQLITE_OMIT_CAST */
39293
39294 /* Opcode: ToInt * * *
39295 **
39296 ** Force the value on the top of the stack to be an integer.  If
39297 ** The value is currently a real number, drop its fractional part.
39298 ** If the value is text or blob, try to convert it to an integer using the
39299 ** equivalent of atoi() and store 0 if no such conversion is possible.
39300 **
39301 ** A NULL value is not changed by this routine.  It remains NULL.
39302 */
39303 case OP_ToInt: {                  /* same as TK_TO_INT, no-push */
39304   assert( pTos>=p->aStack );
39305   if( (pTos->flags & MEM_Null)==0 ){
39306     sqlite3VdbeMemIntegerify(pTos);
39307   }
39308   break;
39309 }
39310
39311 #ifndef SQLITE_OMIT_CAST
39312 /* Opcode: ToReal * * *
39313 **
39314 ** Force the value on the top of the stack to be a floating point number.
39315 ** If The value is currently an integer, convert it.
39316 ** If the value is text or blob, try to convert it to an integer using the
39317 ** equivalent of atoi() and store 0 if no such conversion is possible.
39318 **
39319 ** A NULL value is not changed by this routine.  It remains NULL.
39320 */
39321 case OP_ToReal: {                  /* same as TK_TO_REAL, no-push */
39322   assert( pTos>=p->aStack );
39323   if( (pTos->flags & MEM_Null)==0 ){
39324     sqlite3VdbeMemRealify(pTos);
39325   }
39326   break;
39327 }
39328 #endif /* SQLITE_OMIT_CAST */
39329
39330 /* Opcode: Eq P1 P2 P3
39331 **
39332 ** Pop the top two elements from the stack.  If they are equal, then
39333 ** jump to instruction P2.  Otherwise, continue to the next instruction.
39334 **
39335 ** If the 0x100 bit of P1 is true and either operand is NULL then take the
39336 ** jump.  If the 0x100 bit of P1 is clear then fall thru if either operand
39337 ** is NULL.
39338 **
39339 ** If the 0x200 bit of P1 is set and either operand is NULL then
39340 ** both operands are converted to integers prior to comparison.
39341 ** NULL operands are converted to zero and non-NULL operands are
39342 ** converted to 1.  Thus, for example, with 0x200 set,  NULL==NULL is true
39343 ** whereas it would normally be NULL.  Similarly,  NULL==123 is false when
39344 ** 0x200 is set but is NULL when the 0x200 bit of P1 is clear.
39345 **
39346 ** The least significant byte of P1 (mask 0xff) must be an affinity character -
39347 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
39348 ** to coerce both values
39349 ** according to the affinity before the comparison is made. If the byte is
39350 ** 0x00, then numeric affinity is used.
39351 **
39352 ** Once any conversions have taken place, and neither value is NULL, 
39353 ** the values are compared. If both values are blobs, or both are text,
39354 ** then memcmp() is used to determine the results of the comparison. If
39355 ** both values are numeric, then a numeric comparison is used. If the
39356 ** two values are of different types, then they are inequal.
39357 **
39358 ** If P2 is zero, do not jump.  Instead, push an integer 1 onto the
39359 ** stack if the jump would have been taken, or a 0 if not.  Push a
39360 ** NULL if either operand was NULL.
39361 **
39362 ** If P3 is not NULL it is a pointer to a collating sequence (a CollSeq
39363 ** structure) that defines how to compare text.
39364 */
39365 /* Opcode: Ne P1 P2 P3
39366 **
39367 ** This works just like the Eq opcode except that the jump is taken if
39368 ** the operands from the stack are not equal.  See the Eq opcode for
39369 ** additional information.
39370 */
39371 /* Opcode: Lt P1 P2 P3
39372 **
39373 ** This works just like the Eq opcode except that the jump is taken if
39374 ** the 2nd element down on the stack is less than the top of the stack.
39375 ** See the Eq opcode for additional information.
39376 */
39377 /* Opcode: Le P1 P2 P3
39378 **
39379 ** This works just like the Eq opcode except that the jump is taken if
39380 ** the 2nd element down on the stack is less than or equal to the
39381 ** top of the stack.  See the Eq opcode for additional information.
39382 */
39383 /* Opcode: Gt P1 P2 P3
39384 **
39385 ** This works just like the Eq opcode except that the jump is taken if
39386 ** the 2nd element down on the stack is greater than the top of the stack.
39387 ** See the Eq opcode for additional information.
39388 */
39389 /* Opcode: Ge P1 P2 P3
39390 **
39391 ** This works just like the Eq opcode except that the jump is taken if
39392 ** the 2nd element down on the stack is greater than or equal to the
39393 ** top of the stack.  See the Eq opcode for additional information.
39394 */
39395 case OP_Eq:               /* same as TK_EQ, no-push */
39396 case OP_Ne:               /* same as TK_NE, no-push */
39397 case OP_Lt:               /* same as TK_LT, no-push */
39398 case OP_Le:               /* same as TK_LE, no-push */
39399 case OP_Gt:               /* same as TK_GT, no-push */
39400 case OP_Ge: {             /* same as TK_GE, no-push */
39401   Mem *pNos;
39402   int flags;
39403   int res;
39404   char affinity;
39405
39406   pNos = &pTos[-1];
39407   flags = pTos->flags|pNos->flags;
39408
39409   /* If either value is a NULL P2 is not zero, take the jump if the least
39410   ** significant byte of P1 is true. If P2 is zero, then push a NULL onto
39411   ** the stack.
39412   */
39413   if( flags&MEM_Null ){
39414     if( (pOp->p1 & 0x200)!=0 ){
39415       /* The 0x200 bit of P1 means, roughly "do not treat NULL as the
39416       ** magic SQL value it normally is - treat it as if it were another
39417       ** integer".
39418       **
39419       ** With 0x200 set, if either operand is NULL then both operands
39420       ** are converted to integers prior to being passed down into the
39421       ** normal comparison logic below.  NULL operands are converted to
39422       ** zero and non-NULL operands are converted to 1.  Thus, for example,
39423       ** with 0x200 set,  NULL==NULL is true whereas it would normally
39424       ** be NULL.  Similarly,  NULL!=123 is true.
39425       */
39426       sqlite3VdbeMemSetInt64(pTos, (pTos->flags & MEM_Null)==0);
39427       sqlite3VdbeMemSetInt64(pNos, (pNos->flags & MEM_Null)==0);
39428     }else{
39429       /* If the 0x200 bit of P1 is clear and either operand is NULL then
39430       ** the result is always NULL.  The jump is taken if the 0x100 bit
39431       ** of P1 is set.
39432       */
39433       popStack(&pTos, 2);
39434       if( pOp->p2 ){
39435         if( pOp->p1 & 0x100 ){
39436           pc = pOp->p2-1;
39437         }
39438       }else{
39439         pTos++;
39440         pTos->flags = MEM_Null;
39441       }
39442       break;
39443     }
39444   }
39445
39446   affinity = pOp->p1 & 0xFF;
39447   if( affinity ){
39448     applyAffinity(pNos, affinity, encoding);
39449     applyAffinity(pTos, affinity, encoding);
39450   }
39451
39452   assert( pOp->p3type==P3_COLLSEQ || pOp->p3==0 );
39453   ExpandBlob(pNos);
39454   ExpandBlob(pTos);
39455   res = sqlite3MemCompare(pNos, pTos, (CollSeq*)pOp->p3);
39456   switch( pOp->opcode ){
39457     case OP_Eq:    res = res==0;     break;
39458     case OP_Ne:    res = res!=0;     break;
39459     case OP_Lt:    res = res<0;      break;
39460     case OP_Le:    res = res<=0;     break;
39461     case OP_Gt:    res = res>0;      break;
39462     default:       res = res>=0;     break;
39463   }
39464
39465   popStack(&pTos, 2);
39466   if( pOp->p2 ){
39467     if( res ){
39468       pc = pOp->p2-1;
39469     }
39470   }else{
39471     pTos++;
39472     pTos->flags = MEM_Int;
39473     pTos->u.i = res;
39474   }
39475   break;
39476 }
39477
39478 /* Opcode: And * * *
39479 **
39480 ** Pop two values off the stack.  Take the logical AND of the
39481 ** two values and push the resulting boolean value back onto the
39482 ** stack. 
39483 */
39484 /* Opcode: Or * * *
39485 **
39486 ** Pop two values off the stack.  Take the logical OR of the
39487 ** two values and push the resulting boolean value back onto the
39488 ** stack. 
39489 */
39490 case OP_And:              /* same as TK_AND, no-push */
39491 case OP_Or: {             /* same as TK_OR, no-push */
39492   Mem *pNos = &pTos[-1];
39493   int v1, v2;    /* 0==TRUE, 1==FALSE, 2==UNKNOWN or NULL */
39494
39495   assert( pNos>=p->aStack );
39496   if( pTos->flags & MEM_Null ){
39497     v1 = 2;
39498   }else{
39499     sqlite3VdbeMemIntegerify(pTos);
39500     v1 = pTos->u.i==0;
39501   }
39502   if( pNos->flags & MEM_Null ){
39503     v2 = 2;
39504   }else{
39505     sqlite3VdbeMemIntegerify(pNos);
39506     v2 = pNos->u.i==0;
39507   }
39508   if( pOp->opcode==OP_And ){
39509     static const unsigned char and_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
39510     v1 = and_logic[v1*3+v2];
39511   }else{
39512     static const unsigned char or_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
39513     v1 = or_logic[v1*3+v2];
39514   }
39515   popStack(&pTos, 2);
39516   pTos++;
39517   if( v1==2 ){
39518     pTos->flags = MEM_Null;
39519   }else{
39520     pTos->u.i = v1==0;
39521     pTos->flags = MEM_Int;
39522   }
39523   break;
39524 }
39525
39526 /* Opcode: Negative * * *
39527 **
39528 ** Treat the top of the stack as a numeric quantity.  Replace it
39529 ** with its additive inverse.  If the top of the stack is NULL
39530 ** its value is unchanged.
39531 */
39532 /* Opcode: AbsValue * * *
39533 **
39534 ** Treat the top of the stack as a numeric quantity.  Replace it
39535 ** with its absolute value. If the top of the stack is NULL
39536 ** its value is unchanged.
39537 */
39538 case OP_Negative:              /* same as TK_UMINUS, no-push */
39539 case OP_AbsValue: {
39540   assert( pTos>=p->aStack );
39541   if( (pTos->flags & (MEM_Real|MEM_Int|MEM_Null))==0 ){
39542     sqlite3VdbeMemNumerify(pTos);
39543   }
39544   if( pTos->flags & MEM_Real ){
39545     Release(pTos);
39546     if( pOp->opcode==OP_Negative || pTos->r<0.0 ){
39547       pTos->r = -pTos->r;
39548     }
39549     pTos->flags = MEM_Real;
39550   }else if( pTos->flags & MEM_Int ){
39551     Release(pTos);
39552     if( pOp->opcode==OP_Negative || pTos->u.i<0 ){
39553       pTos->u.i = -pTos->u.i;
39554     }
39555     pTos->flags = MEM_Int;
39556   }
39557   break;
39558 }
39559
39560 /* Opcode: Not * * *
39561 **
39562 ** Interpret the top of the stack as a boolean value.  Replace it
39563 ** with its complement.  If the top of the stack is NULL its value
39564 ** is unchanged.
39565 */
39566 case OP_Not: {                /* same as TK_NOT, no-push */
39567   assert( pTos>=p->aStack );
39568   if( pTos->flags & MEM_Null ) break;  /* Do nothing to NULLs */
39569   sqlite3VdbeMemIntegerify(pTos);
39570   assert( (pTos->flags & MEM_Dyn)==0 );
39571   pTos->u.i = !pTos->u.i;
39572   pTos->flags = MEM_Int;
39573   break;
39574 }
39575
39576 /* Opcode: BitNot * * *
39577 **
39578 ** Interpret the top of the stack as an value.  Replace it
39579 ** with its ones-complement.  If the top of the stack is NULL its
39580 ** value is unchanged.
39581 */
39582 case OP_BitNot: {             /* same as TK_BITNOT, no-push */
39583   assert( pTos>=p->aStack );
39584   if( pTos->flags & MEM_Null ) break;  /* Do nothing to NULLs */
39585   sqlite3VdbeMemIntegerify(pTos);
39586   assert( (pTos->flags & MEM_Dyn)==0 );
39587   pTos->u.i = ~pTos->u.i;
39588   pTos->flags = MEM_Int;
39589   break;
39590 }
39591
39592 /* Opcode: Noop * * *
39593 **
39594 ** Do nothing.  This instruction is often useful as a jump
39595 ** destination.
39596 */
39597 /*
39598 ** The magic Explain opcode are only inserted when explain==2 (which
39599 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
39600 ** This opcode records information from the optimizer.  It is the
39601 ** the same as a no-op.  This opcodesnever appears in a real VM program.
39602 */
39603 case OP_Explain:
39604 case OP_Noop: {            /* no-push */
39605   break;
39606 }
39607
39608 /* Opcode: If P1 P2 *
39609 **
39610 ** Pop a single boolean from the stack.  If the boolean popped is
39611 ** true, then jump to p2.  Otherwise continue to the next instruction.
39612 ** An integer is false if zero and true otherwise.  A string is
39613 ** false if it has zero length and true otherwise.
39614 **
39615 ** If the value popped of the stack is NULL, then take the jump if P1
39616 ** is true and fall through if P1 is false.
39617 */
39618 /* Opcode: IfNot P1 P2 *
39619 **
39620 ** Pop a single boolean from the stack.  If the boolean popped is
39621 ** false, then jump to p2.  Otherwise continue to the next instruction.
39622 ** An integer is false if zero and true otherwise.  A string is
39623 ** false if it has zero length and true otherwise.
39624 **
39625 ** If the value popped of the stack is NULL, then take the jump if P1
39626 ** is true and fall through if P1 is false.
39627 */
39628 case OP_If:                 /* no-push */
39629 case OP_IfNot: {            /* no-push */
39630   int c;
39631   assert( pTos>=p->aStack );
39632   if( pTos->flags & MEM_Null ){
39633     c = pOp->p1;
39634   }else{
39635 #ifdef SQLITE_OMIT_FLOATING_POINT
39636     c = sqlite3VdbeIntValue(pTos);
39637 #else
39638     c = sqlite3VdbeRealValue(pTos)!=0.0;
39639 #endif
39640     if( pOp->opcode==OP_IfNot ) c = !c;
39641   }
39642   Release(pTos);
39643   pTos--;
39644   if( c ) pc = pOp->p2-1;
39645   break;
39646 }
39647
39648 /* Opcode: IsNull P1 P2 *
39649 **
39650 ** Check the top of the stack and jump to P2 if the top of the stack
39651 ** is NULL.  If P1 is positive, then pop P1 elements from the stack
39652 ** regardless of whether or not the jump is taken.  If P1 is negative,
39653 ** pop -P1 elements from the stack only if the jump is taken and leave
39654 ** the stack unchanged if the jump is not taken.
39655 */
39656 case OP_IsNull: {            /* same as TK_ISNULL, no-push */
39657   if( pTos->flags & MEM_Null ){
39658     pc = pOp->p2-1;
39659     if( pOp->p1<0 ){
39660       popStack(&pTos, -pOp->p1);
39661     }
39662   }
39663   if( pOp->p1>0 ){
39664     popStack(&pTos, pOp->p1);
39665   }
39666   break;
39667 }
39668
39669 /* Opcode: NotNull P1 P2 *
39670 **
39671 ** Jump to P2 if the top abs(P1) values on the stack are all not NULL.  
39672 ** Regardless of whether or not the jump is taken, pop the stack
39673 ** P1 times if P1 is greater than zero.  But if P1 is negative,
39674 ** leave the stack unchanged.
39675 */
39676 case OP_NotNull: {            /* same as TK_NOTNULL, no-push */
39677   int i, cnt;
39678   cnt = pOp->p1;
39679   if( cnt<0 ) cnt = -cnt;
39680   assert( &pTos[1-cnt] >= p->aStack );
39681   for(i=0; i<cnt && (pTos[1+i-cnt].flags & MEM_Null)==0; i++){}
39682   if( i>=cnt ) pc = pOp->p2-1;
39683   if( pOp->p1>0 ) popStack(&pTos, cnt);
39684   break;
39685 }
39686
39687 /* Opcode: SetNumColumns P1 P2 *
39688 **
39689 ** Before the OP_Column opcode can be executed on a cursor, this
39690 ** opcode must be called to set the number of fields in the table.
39691 **
39692 ** This opcode sets the number of columns for cursor P1 to P2.
39693 **
39694 ** If OP_KeyAsData is to be applied to cursor P1, it must be executed
39695 ** before this op-code.
39696 */
39697 case OP_SetNumColumns: {       /* no-push */
39698   Cursor *pC;
39699   assert( (pOp->p1)<p->nCursor );
39700   assert( p->apCsr[pOp->p1]!=0 );
39701   pC = p->apCsr[pOp->p1];
39702   pC->nField = pOp->p2;
39703   break;
39704 }
39705
39706 /* Opcode: Column P1 P2 P3
39707 **
39708 ** Interpret the data that cursor P1 points to as a structure built using
39709 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
39710 ** information about the format of the data.) Push onto the stack the value
39711 ** of the P2-th column contained in the data. If there are less that (P2+1) 
39712 ** values in the record, push a NULL onto the stack.
39713 **
39714 ** If the KeyAsData opcode has previously executed on this cursor, then the
39715 ** field might be extracted from the key rather than the data.
39716 **
39717 ** If the column contains fewer than P2 fields, then push a NULL.  Or
39718 ** if P3 is of type P3_MEM, then push the P3 value.  The P3 value will
39719 ** be default value for a column that has been added using the ALTER TABLE
39720 ** ADD COLUMN command.  If P3 is an ordinary string, just push a NULL.
39721 ** When P3 is a string it is really just a comment describing the value
39722 ** to be pushed, not a default value.
39723 */
39724 case OP_Column: {
39725   u32 payloadSize;   /* Number of bytes in the record */
39726   int p1 = pOp->p1;  /* P1 value of the opcode */
39727   int p2 = pOp->p2;  /* column number to retrieve */
39728   Cursor *pC = 0;    /* The VDBE cursor */
39729   char *zRec;        /* Pointer to complete record-data */
39730   BtCursor *pCrsr;   /* The BTree cursor */
39731   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
39732   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
39733   u32 nField;        /* number of fields in the record */
39734   int len;           /* The length of the serialized data for the column */
39735   int i;             /* Loop counter */
39736   char *zData;       /* Part of the record being decoded */
39737   Mem sMem;          /* For storing the record being decoded */
39738
39739   sMem.flags = 0;
39740   assert( p1<p->nCursor );
39741   pTos++;
39742   pTos->flags = MEM_Null;
39743
39744   /* This block sets the variable payloadSize to be the total number of
39745   ** bytes in the record.
39746   **
39747   ** zRec is set to be the complete text of the record if it is available.
39748   ** The complete record text is always available for pseudo-tables
39749   ** If the record is stored in a cursor, the complete record text
39750   ** might be available in the  pC->aRow cache.  Or it might not be.
39751   ** If the data is unavailable,  zRec is set to NULL.
39752   **
39753   ** We also compute the number of columns in the record.  For cursors,
39754   ** the number of columns is stored in the Cursor.nField element.  For
39755   ** records on the stack, the next entry down on the stack is an integer
39756   ** which is the number of records.
39757   */
39758   pC = p->apCsr[p1];
39759   assert( pC!=0 );
39760 #ifndef SQLITE_OMIT_VIRTUALTABLE
39761   assert( pC->pVtabCursor==0 );
39762 #endif
39763   if( pC->pCursor!=0 ){
39764     /* The record is stored in a B-Tree */
39765     rc = sqlite3VdbeCursorMoveto(pC);
39766     if( rc ) goto abort_due_to_error;
39767     zRec = 0;
39768     pCrsr = pC->pCursor;
39769     if( pC->nullRow ){
39770       payloadSize = 0;
39771     }else if( pC->cacheStatus==p->cacheCtr ){
39772       payloadSize = pC->payloadSize;
39773       zRec = (char*)pC->aRow;
39774     }else if( pC->isIndex ){
39775       i64 payloadSize64;
39776       sqlite3BtreeKeySize(pCrsr, &payloadSize64);
39777       payloadSize = payloadSize64;
39778     }else{
39779       sqlite3BtreeDataSize(pCrsr, &payloadSize);
39780     }
39781     nField = pC->nField;
39782   }else if( pC->pseudoTable ){
39783     /* The record is the sole entry of a pseudo-table */
39784     payloadSize = pC->nData;
39785     zRec = pC->pData;
39786     pC->cacheStatus = CACHE_STALE;
39787     assert( payloadSize==0 || zRec!=0 );
39788     nField = pC->nField;
39789     pCrsr = 0;
39790   }else{
39791     zRec = 0;
39792     payloadSize = 0;
39793     pCrsr = 0;
39794     nField = 0;
39795   }
39796
39797   /* If payloadSize is 0, then just push a NULL onto the stack. */
39798   if( payloadSize==0 ){
39799     assert( pTos->flags==MEM_Null );
39800     break;
39801   }
39802   if( payloadSize>SQLITE_MAX_LENGTH ){
39803     goto too_big;
39804   }
39805
39806   assert( p2<nField );
39807
39808   /* Read and parse the table header.  Store the results of the parse
39809   ** into the record header cache fields of the cursor.
39810   */
39811   if( pC && pC->cacheStatus==p->cacheCtr ){
39812     aType = pC->aType;
39813     aOffset = pC->aOffset;
39814   }else{
39815     u8 *zIdx;        /* Index into header */
39816     u8 *zEndHdr;     /* Pointer to first byte after the header */
39817     u32 offset;      /* Offset into the data */
39818     int szHdrSz;     /* Size of the header size field at start of record */
39819     int avail;       /* Number of bytes of available data */
39820
39821     aType = pC->aType;
39822     if( aType==0 ){
39823       pC->aType = aType = sqlite3DbMallocRaw(db, 2*nField*sizeof(aType) );
39824     }
39825     if( aType==0 ){
39826       goto no_mem;
39827     }
39828     pC->aOffset = aOffset = &aType[nField];
39829     pC->payloadSize = payloadSize;
39830     pC->cacheStatus = p->cacheCtr;
39831
39832     /* Figure out how many bytes are in the header */
39833     if( zRec ){
39834       zData = zRec;
39835     }else{
39836       if( pC->isIndex ){
39837         zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail);
39838       }else{
39839         zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail);
39840       }
39841       /* If KeyFetch()/DataFetch() managed to get the entire payload,
39842       ** save the payload in the pC->aRow cache.  That will save us from
39843       ** having to make additional calls to fetch the content portion of
39844       ** the record.
39845       */
39846       if( avail>=payloadSize ){
39847         zRec = zData;
39848         pC->aRow = (u8*)zData;
39849       }else{
39850         pC->aRow = 0;
39851       }
39852     }
39853     /* The following assert is true in all cases accept when
39854     ** the database file has been corrupted externally.
39855     **    assert( zRec!=0 || avail>=payloadSize || avail>=9 ); */
39856     szHdrSz = GetVarint((u8*)zData, offset);
39857
39858     /* The KeyFetch() or DataFetch() above are fast and will get the entire
39859     ** record header in most cases.  But they will fail to get the complete
39860     ** record header if the record header does not fit on a single page
39861     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
39862     ** acquire the complete header text.
39863     */
39864     if( !zRec && avail<offset ){
39865       rc = sqlite3VdbeMemFromBtree(pCrsr, 0, offset, pC->isIndex, &sMem);
39866       if( rc!=SQLITE_OK ){
39867         goto op_column_out;
39868       }
39869       zData = sMem.z;
39870     }
39871     zEndHdr = (u8 *)&zData[offset];
39872     zIdx = (u8 *)&zData[szHdrSz];
39873
39874     /* Scan the header and use it to fill in the aType[] and aOffset[]
39875     ** arrays.  aType[i] will contain the type integer for the i-th
39876     ** column and aOffset[i] will contain the offset from the beginning
39877     ** of the record to the start of the data for the i-th column
39878     */
39879     for(i=0; i<nField; i++){
39880       if( zIdx<zEndHdr ){
39881         aOffset[i] = offset;
39882         zIdx += GetVarint(zIdx, aType[i]);
39883         offset += sqlite3VdbeSerialTypeLen(aType[i]);
39884       }else{
39885         /* If i is less that nField, then there are less fields in this
39886         ** record than SetNumColumns indicated there are columns in the
39887         ** table. Set the offset for any extra columns not present in
39888         ** the record to 0. This tells code below to push a NULL onto the
39889         ** stack instead of deserializing a value from the record.
39890         */
39891         aOffset[i] = 0;
39892       }
39893     }
39894     Release(&sMem);
39895     sMem.flags = MEM_Null;
39896
39897     /* If we have read more header data than was contained in the header,
39898     ** or if the end of the last field appears to be past the end of the
39899     ** record, then we must be dealing with a corrupt database.
39900     */
39901     if( zIdx>zEndHdr || offset>payloadSize ){
39902       rc = SQLITE_CORRUPT_BKPT;
39903       goto op_column_out;
39904     }
39905   }
39906
39907   /* Get the column information. If aOffset[p2] is non-zero, then 
39908   ** deserialize the value from the record. If aOffset[p2] is zero,
39909   ** then there are not enough fields in the record to satisfy the
39910   ** request.  In this case, set the value NULL or to P3 if P3 is
39911   ** a pointer to a Mem object.
39912   */
39913   if( aOffset[p2] ){
39914     assert( rc==SQLITE_OK );
39915     if( zRec ){
39916       zData = &zRec[aOffset[p2]];
39917     }else{
39918       len = sqlite3VdbeSerialTypeLen(aType[p2]);
39919       rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex, &sMem);
39920       if( rc!=SQLITE_OK ){
39921         goto op_column_out;
39922       }
39923       zData = sMem.z;
39924     }
39925     sqlite3VdbeSerialGet((u8*)zData, aType[p2], pTos);
39926     pTos->enc = encoding;
39927   }else{
39928     if( pOp->p3type==P3_MEM ){
39929       sqlite3VdbeMemShallowCopy(pTos, (Mem *)(pOp->p3), MEM_Static);
39930     }else{
39931       pTos->flags = MEM_Null;
39932     }
39933   }
39934
39935   /* If we dynamically allocated space to hold the data (in the
39936   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
39937   ** dynamically allocated space over to the pTos structure.
39938   ** This prevents a memory copy.
39939   */
39940   if( (sMem.flags & MEM_Dyn)!=0 ){
39941     assert( pTos->flags & MEM_Ephem );
39942     assert( pTos->flags & (MEM_Str|MEM_Blob) );
39943     assert( pTos->z==sMem.z );
39944     assert( sMem.flags & MEM_Term );
39945     pTos->flags &= ~MEM_Ephem;
39946     pTos->flags |= MEM_Dyn|MEM_Term;
39947   }
39948
39949   /* pTos->z might be pointing to sMem.zShort[].  Fix that so that we
39950   ** can abandon sMem */
39951   rc = sqlite3VdbeMemMakeWriteable(pTos);
39952
39953 op_column_out:
39954   break;
39955 }
39956
39957 /* Opcode: MakeRecord P1 P2 P3
39958 **
39959 ** Convert the top abs(P1) entries of the stack into a single entry
39960 ** suitable for use as a data record in a database table or as a key
39961 ** in an index.  The details of the format are irrelavant as long as
39962 ** the OP_Column opcode can decode the record later and as long as the
39963 ** sqlite3VdbeRecordCompare function will correctly compare two encoded
39964 ** records.  Refer to source code comments for the details of the record
39965 ** format.
39966 **
39967 ** The original stack entries are popped from the stack if P1>0 but
39968 ** remain on the stack if P1<0.
39969 **
39970 ** If P2 is not zero and one or more of the entries are NULL, then jump
39971 ** to the address given by P2.  This feature can be used to skip a
39972 ** uniqueness test on indices.
39973 **
39974 ** P3 may be a string that is P1 characters long.  The nth character of the
39975 ** string indicates the column affinity that should be used for the nth
39976 ** field of the index key (i.e. the first character of P3 corresponds to the
39977 ** lowest element on the stack).
39978 **
39979 ** The mapping from character to affinity is given by the SQLITE_AFF_
39980 ** macros defined in sqliteInt.h.
39981 **
39982 ** If P3 is NULL then all index fields have the affinity NONE.
39983 **
39984 ** See also OP_MakeIdxRec
39985 */
39986 /* Opcode: MakeIdxRec P1 P2 P3
39987 **
39988 ** This opcode works just OP_MakeRecord except that it reads an extra
39989 ** integer from the stack (thus reading a total of abs(P1+1) entries)
39990 ** and appends that extra integer to the end of the record as a varint.
39991 ** This results in an index key.
39992 */
39993 case OP_MakeIdxRec:
39994 case OP_MakeRecord: {
39995   /* Assuming the record contains N fields, the record format looks
39996   ** like this:
39997   **
39998   ** ------------------------------------------------------------------------
39999   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | 
40000   ** ------------------------------------------------------------------------
40001   **
40002   ** Data(0) is taken from the lowest element of the stack and data(N-1) is
40003   ** the top of the stack.
40004   **
40005   ** Each type field is a varint representing the serial type of the 
40006   ** corresponding data element (see sqlite3VdbeSerialType()). The
40007   ** hdr-size field is also a varint which is the offset from the beginning
40008   ** of the record to data0.
40009   */
40010   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
40011   Mem *pRec;             /* The new record */
40012   Mem *pRowid = 0;       /* Rowid appended to the new record */
40013   u64 nData = 0;         /* Number of bytes of data space */
40014   int nHdr = 0;          /* Number of bytes of header space */
40015   u64 nByte = 0;         /* Data space required for this record */
40016   int nZero = 0;         /* Number of zero bytes at the end of the record */
40017   int nVarint;           /* Number of bytes in a varint */
40018   u32 serial_type;       /* Type field */
40019   int containsNull = 0;  /* True if any of the data fields are NULL */
40020   Mem *pData0;           /* Bottom of the stack */
40021   int leaveOnStack;      /* If true, leave the entries on the stack */
40022   int nField;            /* Number of fields in the record */
40023   int jumpIfNull;        /* Jump here if non-zero and any entries are NULL. */
40024   int addRowid;          /* True to append a rowid column at the end */
40025   char *zAffinity;       /* The affinity string for the record */
40026   int file_format;       /* File format to use for encoding */
40027   int i;                 /* Space used in zNewRecord[] */
40028   char zTemp[NBFS];      /* Space to hold small records */
40029
40030   leaveOnStack = ((pOp->p1<0)?1:0);
40031   nField = pOp->p1 * (leaveOnStack?-1:1);
40032   jumpIfNull = pOp->p2;
40033   addRowid = pOp->opcode==OP_MakeIdxRec;
40034   zAffinity = pOp->p3;
40035
40036   pData0 = &pTos[1-nField];
40037   assert( pData0>=p->aStack );
40038   containsNull = 0;
40039   file_format = p->minWriteFileFormat;
40040
40041   /* Loop through the elements that will make up the record to figure
40042   ** out how much space is required for the new record.
40043   */
40044   for(pRec=pData0; pRec<=pTos; pRec++){
40045     int len;
40046     if( zAffinity ){
40047       applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
40048     }
40049     if( pRec->flags&MEM_Null ){
40050       containsNull = 1;
40051     }
40052     if( pRec->flags&MEM_Zero && pRec->n>0 ){
40053       ExpandBlob(pRec);
40054     }
40055     serial_type = sqlite3VdbeSerialType(pRec, file_format);
40056     len = sqlite3VdbeSerialTypeLen(serial_type);
40057     nData += len;
40058     nHdr += sqlite3VarintLen(serial_type);
40059     if( pRec->flags & MEM_Zero ){
40060       /* Only pure zero-filled BLOBs can be input to this Opcode.
40061       ** We do not allow blobs with a prefix and a zero-filled tail. */
40062       nZero += pRec->u.i;
40063     }else if( len ){
40064       nZero = 0;
40065     }
40066   }
40067
40068   /* If we have to append a varint rowid to this record, set pRowid
40069   ** to the value of the rowid and increase nByte by the amount of space
40070   ** required to store it.
40071   */
40072   if( addRowid ){
40073     pRowid = &pTos[0-nField];
40074     assert( pRowid>=p->aStack );
40075     sqlite3VdbeMemIntegerify(pRowid);
40076     serial_type = sqlite3VdbeSerialType(pRowid, 0);
40077     nData += sqlite3VdbeSerialTypeLen(serial_type);
40078     nHdr += sqlite3VarintLen(serial_type);
40079     nZero = 0;
40080   }
40081
40082   /* Add the initial header varint and total the size */
40083   nHdr += nVarint = sqlite3VarintLen(nHdr);
40084   if( nVarint<sqlite3VarintLen(nHdr) ){
40085     nHdr++;
40086   }
40087   nByte = nHdr+nData-nZero;
40088   if( nByte>SQLITE_MAX_LENGTH ){
40089     goto too_big;
40090   }
40091
40092   /* Allocate space for the new record. */
40093   if( nByte>sizeof(zTemp) ){
40094     zNewRecord = sqlite3DbMallocRaw(db, nByte);
40095     if( !zNewRecord ){
40096       goto no_mem;
40097     }
40098   }else{
40099     zNewRecord = (u8*)zTemp;
40100   }
40101
40102   /* Write the record */
40103   i = sqlite3PutVarint(zNewRecord, nHdr);
40104   for(pRec=pData0; pRec<=pTos; pRec++){
40105     serial_type = sqlite3VdbeSerialType(pRec, file_format);
40106     i += sqlite3PutVarint(&zNewRecord[i], serial_type);      /* serial type */
40107   }
40108   if( addRowid ){
40109     i += sqlite3PutVarint(&zNewRecord[i], sqlite3VdbeSerialType(pRowid, 0));
40110   }
40111   for(pRec=pData0; pRec<=pTos; pRec++){  /* serial data */
40112     i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRec, file_format);
40113   }
40114   if( addRowid ){
40115     i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRowid, 0);
40116   }
40117   assert( i==nByte );
40118
40119   /* Pop entries off the stack if required. Push the new record on. */
40120   if( !leaveOnStack ){
40121     popStack(&pTos, nField+addRowid);
40122   }
40123   pTos++;
40124   pTos->n = nByte;
40125   if( nByte<=sizeof(zTemp) ){
40126     assert( zNewRecord==(unsigned char *)zTemp );
40127     pTos->z = pTos->zShort;
40128     memcpy(pTos->zShort, zTemp, nByte);
40129     pTos->flags = MEM_Blob | MEM_Short;
40130   }else{
40131     assert( zNewRecord!=(unsigned char *)zTemp );
40132     pTos->z = (char*)zNewRecord;
40133     pTos->flags = MEM_Blob | MEM_Dyn;
40134     pTos->xDel = 0;
40135   }
40136   if( nZero ){
40137     pTos->u.i = nZero;
40138     pTos->flags |= MEM_Zero;
40139   }
40140   pTos->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
40141
40142   /* If a NULL was encountered and jumpIfNull is non-zero, take the jump. */
40143   if( jumpIfNull && containsNull ){
40144     pc = jumpIfNull - 1;
40145   }
40146   break;
40147 }
40148
40149 /* Opcode: Statement P1 * *
40150 **
40151 ** Begin an individual statement transaction which is part of a larger
40152 ** BEGIN..COMMIT transaction.  This is needed so that the statement
40153 ** can be rolled back after an error without having to roll back the
40154 ** entire transaction.  The statement transaction will automatically
40155 ** commit when the VDBE halts.
40156 **
40157 ** The statement is begun on the database file with index P1.  The main
40158 ** database file has an index of 0 and the file used for temporary tables
40159 ** has an index of 1.
40160 */
40161 case OP_Statement: {       /* no-push */
40162   int i = pOp->p1;
40163   Btree *pBt;
40164   if( i>=0 && i<db->nDb && (pBt = db->aDb[i].pBt)!=0
40165         && (db->autoCommit==0 || db->activeVdbeCnt>1) ){
40166     assert( sqlite3BtreeIsInTrans(pBt) );
40167     assert( (p->btreeMask & (1<<i))!=0 );
40168     if( !sqlite3BtreeIsInStmt(pBt) ){
40169       rc = sqlite3BtreeBeginStmt(pBt);
40170       p->openedStatement = 1;
40171     }
40172   }
40173   break;
40174 }
40175
40176 /* Opcode: AutoCommit P1 P2 *
40177 **
40178 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
40179 ** back any currently active btree transactions. If there are any active
40180 ** VMs (apart from this one), then the COMMIT or ROLLBACK statement fails.
40181 **
40182 ** This instruction causes the VM to halt.
40183 */
40184 case OP_AutoCommit: {       /* no-push */
40185   u8 i = pOp->p1;
40186   u8 rollback = pOp->p2;
40187
40188   assert( i==1 || i==0 );
40189   assert( i==1 || rollback==0 );
40190
40191   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
40192
40193   if( db->activeVdbeCnt>1 && i && !db->autoCommit ){
40194     /* If this instruction implements a COMMIT or ROLLBACK, other VMs are
40195     ** still running, and a transaction is active, return an error indicating
40196     ** that the other VMs must complete first. 
40197     */
40198     sqlite3SetString(&p->zErrMsg, "cannot ", rollback?"rollback":"commit", 
40199         " transaction - SQL statements in progress", (char*)0);
40200     rc = SQLITE_ERROR;
40201   }else if( i!=db->autoCommit ){
40202     if( pOp->p2 ){
40203       assert( i==1 );
40204       sqlite3RollbackAll(db);
40205       db->autoCommit = 1;
40206     }else{
40207       db->autoCommit = i;
40208       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
40209         p->pTos = pTos;
40210         p->pc = pc;
40211         db->autoCommit = 1-i;
40212         p->rc = rc = SQLITE_BUSY;
40213         goto vdbe_return;
40214       }
40215     }
40216     if( p->rc==SQLITE_OK ){
40217       rc = SQLITE_DONE;
40218     }else{
40219       rc = SQLITE_ERROR;
40220     }
40221     goto vdbe_return;
40222   }else{
40223     sqlite3SetString(&p->zErrMsg,
40224         (!i)?"cannot start a transaction within a transaction":(
40225         (rollback)?"cannot rollback - no transaction is active":
40226                    "cannot commit - no transaction is active"), (char*)0);
40227          
40228     rc = SQLITE_ERROR;
40229   }
40230   break;
40231 }
40232
40233 /* Opcode: Transaction P1 P2 *
40234 **
40235 ** Begin a transaction.  The transaction ends when a Commit or Rollback
40236 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
40237 ** transaction might also be rolled back if an error is encountered.
40238 **
40239 ** P1 is the index of the database file on which the transaction is
40240 ** started.  Index 0 is the main database file and index 1 is the
40241 ** file used for temporary tables.
40242 **
40243 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
40244 ** obtained on the database file when a write-transaction is started.  No
40245 ** other process can start another write transaction while this transaction is
40246 ** underway.  Starting a write transaction also creates a rollback journal. A
40247 ** write transaction must be started before any changes can be made to the
40248 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
40249 ** on the file.
40250 **
40251 ** If P2 is zero, then a read-lock is obtained on the database file.
40252 */
40253 case OP_Transaction: {       /* no-push */
40254   int i = pOp->p1;
40255   Btree *pBt;
40256
40257   assert( i>=0 && i<db->nDb );
40258   assert( (p->btreeMask & (1<<i))!=0 );
40259   pBt = db->aDb[i].pBt;
40260
40261   if( pBt ){
40262     rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
40263     if( rc==SQLITE_BUSY ){
40264       p->pc = pc;
40265       p->rc = rc = SQLITE_BUSY;
40266       p->pTos = pTos;
40267       goto vdbe_return;
40268     }
40269     if( rc!=SQLITE_OK && rc!=SQLITE_READONLY /* && rc!=SQLITE_BUSY */ ){
40270       goto abort_due_to_error;
40271     }
40272   }
40273   break;
40274 }
40275
40276 /* Opcode: ReadCookie P1 P2 *
40277 **
40278 ** Read cookie number P2 from database P1 and push it onto the stack.
40279 ** P2==0 is the schema version.  P2==1 is the database format.
40280 ** P2==2 is the recommended pager cache size, and so forth.  P1==0 is
40281 ** the main database file and P1==1 is the database file used to store
40282 ** temporary tables.
40283 **
40284 ** If P1 is negative, then this is a request to read the size of a
40285 ** databases free-list. P2 must be set to 1 in this case. The actual
40286 ** database accessed is ((P1+1)*-1). For example, a P1 parameter of -1
40287 ** corresponds to database 0 ("main"), a P1 of -2 is database 1 ("temp").
40288 **
40289 ** There must be a read-lock on the database (either a transaction
40290 ** must be started or there must be an open cursor) before
40291 ** executing this instruction.
40292 */
40293 case OP_ReadCookie: {
40294   int iMeta;
40295   int iDb = pOp->p1;
40296   int iCookie = pOp->p2;
40297
40298   assert( pOp->p2<SQLITE_N_BTREE_META );
40299   if( iDb<0 ){
40300     iDb = (-1*(iDb+1));
40301     iCookie *= -1;
40302   }
40303   assert( iDb>=0 && iDb<db->nDb );
40304   assert( db->aDb[iDb].pBt!=0 );
40305   assert( (p->btreeMask & (1<<iDb))!=0 );
40306   /* The indexing of meta values at the schema layer is off by one from
40307   ** the indexing in the btree layer.  The btree considers meta[0] to
40308   ** be the number of free pages in the database (a read-only value)
40309   ** and meta[1] to be the schema cookie.  The schema layer considers
40310   ** meta[1] to be the schema cookie.  So we have to shift the index
40311   ** by one in the following statement.
40312   */
40313   rc = sqlite3BtreeGetMeta(db->aDb[iDb].pBt, 1 + iCookie, (u32 *)&iMeta);
40314   pTos++;
40315   pTos->u.i = iMeta;
40316   pTos->flags = MEM_Int;
40317   break;
40318 }
40319
40320 /* Opcode: SetCookie P1 P2 *
40321 **
40322 ** Write the top of the stack into cookie number P2 of database P1.
40323 ** P2==0 is the schema version.  P2==1 is the database format.
40324 ** P2==2 is the recommended pager cache size, and so forth.  P1==0 is
40325 ** the main database file and P1==1 is the database file used to store
40326 ** temporary tables.
40327 **
40328 ** A transaction must be started before executing this opcode.
40329 */
40330 case OP_SetCookie: {       /* no-push */
40331   Db *pDb;
40332   assert( pOp->p2<SQLITE_N_BTREE_META );
40333   assert( pOp->p1>=0 && pOp->p1<db->nDb );
40334   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
40335   pDb = &db->aDb[pOp->p1];
40336   assert( pDb->pBt!=0 );
40337   assert( pTos>=p->aStack );
40338   sqlite3VdbeMemIntegerify(pTos);
40339   /* See note about index shifting on OP_ReadCookie */
40340   rc = sqlite3BtreeUpdateMeta(pDb->pBt, 1+pOp->p2, (int)pTos->u.i);
40341   if( pOp->p2==0 ){
40342     /* When the schema cookie changes, record the new cookie internally */
40343     pDb->pSchema->schema_cookie = pTos->u.i;
40344     db->flags |= SQLITE_InternChanges;
40345   }else if( pOp->p2==1 ){
40346     /* Record changes in the file format */
40347     pDb->pSchema->file_format = pTos->u.i;
40348   }
40349   assert( (pTos->flags & MEM_Dyn)==0 );
40350   pTos--;
40351   if( pOp->p1==1 ){
40352     /* Invalidate all prepared statements whenever the TEMP database
40353     ** schema is changed.  Ticket #1644 */
40354     sqlite3ExpirePreparedStatements(db);
40355   }
40356   break;
40357 }
40358
40359 /* Opcode: VerifyCookie P1 P2 *
40360 **
40361 ** Check the value of global database parameter number 0 (the
40362 ** schema version) and make sure it is equal to P2.  
40363 ** P1 is the database number which is 0 for the main database file
40364 ** and 1 for the file holding temporary tables and some higher number
40365 ** for auxiliary databases.
40366 **
40367 ** The cookie changes its value whenever the database schema changes.
40368 ** This operation is used to detect when that the cookie has changed
40369 ** and that the current process needs to reread the schema.
40370 **
40371 ** Either a transaction needs to have been started or an OP_Open needs
40372 ** to be executed (to establish a read lock) before this opcode is
40373 ** invoked.
40374 */
40375 case OP_VerifyCookie: {       /* no-push */
40376   int iMeta;
40377   Btree *pBt;
40378   assert( pOp->p1>=0 && pOp->p1<db->nDb );
40379   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
40380   pBt = db->aDb[pOp->p1].pBt;
40381   if( pBt ){
40382     rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&iMeta);
40383   }else{
40384     rc = SQLITE_OK;
40385     iMeta = 0;
40386   }
40387   if( rc==SQLITE_OK && iMeta!=pOp->p2 ){
40388     sqlite3_free(p->zErrMsg);
40389     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
40390     /* If the schema-cookie from the database file matches the cookie 
40391     ** stored with the in-memory representation of the schema, do
40392     ** not reload the schema from the database file.
40393     **
40394     ** If virtual-tables are in use, this is not just an optimisation.
40395     ** Often, v-tables store their data in other SQLite tables, which
40396     ** are queried from within xNext() and other v-table methods using
40397     ** prepared queries. If such a query is out-of-date, we do not want to
40398     ** discard the database schema, as the user code implementing the
40399     ** v-table would have to be ready for the sqlite3_vtab structure itself
40400     ** to be invalidated whenever sqlite3_step() is called from within 
40401     ** a v-table method.
40402     */
40403     if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
40404       sqlite3ResetInternalSchema(db, pOp->p1);
40405     }
40406
40407     sqlite3ExpirePreparedStatements(db);
40408     rc = SQLITE_SCHEMA;
40409   }
40410   break;
40411 }
40412
40413 /* Opcode: OpenRead P1 P2 P3
40414 **
40415 ** Open a read-only cursor for the database table whose root page is
40416 ** P2 in a database file.  The database file is determined by an 
40417 ** integer from the top of the stack.  0 means the main database and
40418 ** 1 means the database used for temporary tables.  Give the new 
40419 ** cursor an identifier of P1.  The P1 values need not be contiguous
40420 ** but all P1 values should be small integers.  It is an error for
40421 ** P1 to be negative.
40422 **
40423 ** If P2==0 then take the root page number from the next of the stack.
40424 **
40425 ** There will be a read lock on the database whenever there is an
40426 ** open cursor.  If the database was unlocked prior to this instruction
40427 ** then a read lock is acquired as part of this instruction.  A read
40428 ** lock allows other processes to read the database but prohibits
40429 ** any other process from modifying the database.  The read lock is
40430 ** released when all cursors are closed.  If this instruction attempts
40431 ** to get a read lock but fails, the script terminates with an
40432 ** SQLITE_BUSY error code.
40433 **
40434 ** The P3 value is a pointer to a KeyInfo structure that defines the
40435 ** content and collating sequence of indices.  P3 is NULL for cursors
40436 ** that are not pointing to indices.
40437 **
40438 ** See also OpenWrite.
40439 */
40440 /* Opcode: OpenWrite P1 P2 P3
40441 **
40442 ** Open a read/write cursor named P1 on the table or index whose root
40443 ** page is P2.  If P2==0 then take the root page number from the stack.
40444 **
40445 ** The P3 value is a pointer to a KeyInfo structure that defines the
40446 ** content and collating sequence of indices.  P3 is NULL for cursors
40447 ** that are not pointing to indices.
40448 **
40449 ** This instruction works just like OpenRead except that it opens the cursor
40450 ** in read/write mode.  For a given table, there can be one or more read-only
40451 ** cursors or a single read/write cursor but not both.
40452 **
40453 ** See also OpenRead.
40454 */
40455 case OP_OpenRead:          /* no-push */
40456 case OP_OpenWrite: {       /* no-push */
40457   int i = pOp->p1;
40458   int p2 = pOp->p2;
40459   int wrFlag;
40460   Btree *pX;
40461   int iDb;
40462   Cursor *pCur;
40463   Db *pDb;
40464   
40465   assert( pTos>=p->aStack );
40466   sqlite3VdbeMemIntegerify(pTos);
40467   iDb = pTos->u.i;
40468   assert( (pTos->flags & MEM_Dyn)==0 );
40469   pTos--;
40470   assert( iDb>=0 && iDb<db->nDb );
40471   assert( (p->btreeMask & (1<<iDb))!=0 );
40472   pDb = &db->aDb[iDb];
40473   pX = pDb->pBt;
40474   assert( pX!=0 );
40475   if( pOp->opcode==OP_OpenWrite ){
40476     wrFlag = 1;
40477     if( pDb->pSchema->file_format < p->minWriteFileFormat ){
40478       p->minWriteFileFormat = pDb->pSchema->file_format;
40479     }
40480   }else{
40481     wrFlag = 0;
40482   }
40483   if( p2<=0 ){
40484     assert( pTos>=p->aStack );
40485     sqlite3VdbeMemIntegerify(pTos);
40486     p2 = pTos->u.i;
40487     assert( (pTos->flags & MEM_Dyn)==0 );
40488     pTos--;
40489     assert( p2>=2 );
40490   }
40491   assert( i>=0 );
40492   pCur = allocateCursor(p, i, iDb);
40493   if( pCur==0 ) goto no_mem;
40494   pCur->nullRow = 1;
40495   if( pX==0 ) break;
40496   /* We always provide a key comparison function.  If the table being
40497   ** opened is of type INTKEY, the comparision function will be ignored. */
40498   rc = sqlite3BtreeCursor(pX, p2, wrFlag,
40499            sqlite3VdbeRecordCompare, pOp->p3,
40500            &pCur->pCursor);
40501   if( pOp->p3type==P3_KEYINFO ){
40502     pCur->pKeyInfo = (KeyInfo*)pOp->p3;
40503     pCur->pIncrKey = &pCur->pKeyInfo->incrKey;
40504     pCur->pKeyInfo->enc = ENC(p->db);
40505   }else{
40506     pCur->pKeyInfo = 0;
40507     pCur->pIncrKey = &pCur->bogusIncrKey;
40508   }
40509   switch( rc ){
40510     case SQLITE_BUSY: {
40511       p->pc = pc;
40512       p->rc = rc = SQLITE_BUSY;
40513       p->pTos = &pTos[1 + (pOp->p2<=0)]; /* Operands must remain on stack */
40514       goto vdbe_return;
40515     }
40516     case SQLITE_OK: {
40517       int flags = sqlite3BtreeFlags(pCur->pCursor);
40518       /* Sanity checking.  Only the lower four bits of the flags byte should
40519       ** be used.  Bit 3 (mask 0x08) is unpreditable.  The lower 3 bits
40520       ** (mask 0x07) should be either 5 (intkey+leafdata for tables) or
40521       ** 2 (zerodata for indices).  If these conditions are not met it can
40522       ** only mean that we are dealing with a corrupt database file
40523       */
40524       if( (flags & 0xf0)!=0 || ((flags & 0x07)!=5 && (flags & 0x07)!=2) ){
40525         rc = SQLITE_CORRUPT_BKPT;
40526         goto abort_due_to_error;
40527       }
40528       pCur->isTable = (flags & BTREE_INTKEY)!=0;
40529       pCur->isIndex = (flags & BTREE_ZERODATA)!=0;
40530       /* If P3==0 it means we are expected to open a table.  If P3!=0 then
40531       ** we expect to be opening an index.  If this is not what happened,
40532       ** then the database is corrupt
40533       */
40534       if( (pCur->isTable && pOp->p3type==P3_KEYINFO)
40535        || (pCur->isIndex && pOp->p3type!=P3_KEYINFO) ){
40536         rc = SQLITE_CORRUPT_BKPT;
40537         goto abort_due_to_error;
40538       }
40539       break;
40540     }
40541     case SQLITE_EMPTY: {
40542       pCur->isTable = pOp->p3type!=P3_KEYINFO;
40543       pCur->isIndex = !pCur->isTable;
40544       rc = SQLITE_OK;
40545       break;
40546     }
40547     default: {
40548       goto abort_due_to_error;
40549     }
40550   }
40551   break;
40552 }
40553
40554 /* Opcode: OpenEphemeral P1 P2 P3
40555 **
40556 ** Open a new cursor P1 to a transient table.
40557 ** The cursor is always opened read/write even if 
40558 ** the main database is read-only.  The transient or virtual
40559 ** table is deleted automatically when the cursor is closed.
40560 **
40561 ** P2 is the number of columns in the virtual table.
40562 ** The cursor points to a BTree table if P3==0 and to a BTree index
40563 ** if P3 is not 0.  If P3 is not NULL, it points to a KeyInfo structure
40564 ** that defines the format of keys in the index.
40565 **
40566 ** This opcode was once called OpenTemp.  But that created
40567 ** confusion because the term "temp table", might refer either
40568 ** to a TEMP table at the SQL level, or to a table opened by
40569 ** this opcode.  Then this opcode was call OpenVirtual.  But
40570 ** that created confusion with the whole virtual-table idea.
40571 */
40572 case OP_OpenEphemeral: {       /* no-push */
40573   int i = pOp->p1;
40574   Cursor *pCx;
40575   static const int openFlags = 
40576       SQLITE_OPEN_READWRITE |
40577       SQLITE_OPEN_CREATE |
40578       SQLITE_OPEN_EXCLUSIVE |
40579       SQLITE_OPEN_DELETEONCLOSE |
40580       SQLITE_OPEN_TRANSIENT_DB;
40581
40582   assert( i>=0 );
40583   pCx = allocateCursor(p, i, -1);
40584   if( pCx==0 ) goto no_mem;
40585   pCx->nullRow = 1;
40586   rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
40587                            &pCx->pBt);
40588   if( rc==SQLITE_OK ){
40589     rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
40590   }
40591   if( rc==SQLITE_OK ){
40592     /* If a transient index is required, create it by calling
40593     ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
40594     ** opening it. If a transient table is required, just use the
40595     ** automatically created table with root-page 1 (an INTKEY table).
40596     */
40597     if( pOp->p3 ){
40598       int pgno;
40599       assert( pOp->p3type==P3_KEYINFO );
40600       rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_ZERODATA); 
40601       if( rc==SQLITE_OK ){
40602         assert( pgno==MASTER_ROOT+1 );
40603         rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, sqlite3VdbeRecordCompare,
40604             pOp->p3, &pCx->pCursor);
40605         pCx->pKeyInfo = (KeyInfo*)pOp->p3;
40606         pCx->pKeyInfo->enc = ENC(p->db);
40607         pCx->pIncrKey = &pCx->pKeyInfo->incrKey;
40608       }
40609       pCx->isTable = 0;
40610     }else{
40611       rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, 0, &pCx->pCursor);
40612       pCx->isTable = 1;
40613       pCx->pIncrKey = &pCx->bogusIncrKey;
40614     }
40615   }
40616   pCx->nField = pOp->p2;
40617   pCx->isIndex = !pCx->isTable;
40618   break;
40619 }
40620
40621 /* Opcode: OpenPseudo P1 * *
40622 **
40623 ** Open a new cursor that points to a fake table that contains a single
40624 ** row of data.  Any attempt to write a second row of data causes the
40625 ** first row to be deleted.  All data is deleted when the cursor is
40626 ** closed.
40627 **
40628 ** A pseudo-table created by this opcode is useful for holding the
40629 ** NEW or OLD tables in a trigger.  Also used to hold the a single
40630 ** row output from the sorter so that the row can be decomposed into
40631 ** individual columns using the OP_Column opcode.
40632 */
40633 case OP_OpenPseudo: {       /* no-push */
40634   int i = pOp->p1;
40635   Cursor *pCx;
40636   assert( i>=0 );
40637   pCx = allocateCursor(p, i, -1);
40638   if( pCx==0 ) goto no_mem;
40639   pCx->nullRow = 1;
40640   pCx->pseudoTable = 1;
40641   pCx->pIncrKey = &pCx->bogusIncrKey;
40642   pCx->isTable = 1;
40643   pCx->isIndex = 0;
40644   break;
40645 }
40646
40647 /* Opcode: Close P1 * *
40648 **
40649 ** Close a cursor previously opened as P1.  If P1 is not
40650 ** currently open, this instruction is a no-op.
40651 */
40652 case OP_Close: {       /* no-push */
40653   int i = pOp->p1;
40654   if( i>=0 && i<p->nCursor ){
40655     sqlite3VdbeFreeCursor(p, p->apCsr[i]);
40656     p->apCsr[i] = 0;
40657   }
40658   break;
40659 }
40660
40661 /* Opcode: MoveGe P1 P2 *
40662 **
40663 ** Pop the top of the stack and use its value as a key.  Reposition
40664 ** cursor P1 so that it points to the smallest entry that is greater
40665 ** than or equal to the key that was popped ffrom the stack.
40666 ** If there are no records greater than or equal to the key and P2 
40667 ** is not zero, then jump to P2.
40668 **
40669 ** See also: Found, NotFound, Distinct, MoveLt, MoveGt, MoveLe
40670 */
40671 /* Opcode: MoveGt P1 P2 *
40672 **
40673 ** Pop the top of the stack and use its value as a key.  Reposition
40674 ** cursor P1 so that it points to the smallest entry that is greater
40675 ** than the key from the stack.
40676 ** If there are no records greater than the key and P2 is not zero,
40677 ** then jump to P2.
40678 **
40679 ** See also: Found, NotFound, Distinct, MoveLt, MoveGe, MoveLe
40680 */
40681 /* Opcode: MoveLt P1 P2 *
40682 **
40683 ** Pop the top of the stack and use its value as a key.  Reposition
40684 ** cursor P1 so that it points to the largest entry that is less
40685 ** than the key from the stack.
40686 ** If there are no records less than the key and P2 is not zero,
40687 ** then jump to P2.
40688 **
40689 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLe
40690 */
40691 /* Opcode: MoveLe P1 P2 *
40692 **
40693 ** Pop the top of the stack and use its value as a key.  Reposition
40694 ** cursor P1 so that it points to the largest entry that is less than
40695 ** or equal to the key that was popped from the stack.
40696 ** If there are no records less than or eqal to the key and P2 is not zero,
40697 ** then jump to P2.
40698 **
40699 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLt
40700 */
40701 case OP_MoveLt:         /* no-push */
40702 case OP_MoveLe:         /* no-push */
40703 case OP_MoveGe:         /* no-push */
40704 case OP_MoveGt: {       /* no-push */
40705   int i = pOp->p1;
40706   Cursor *pC;
40707
40708   assert( pTos>=p->aStack );
40709   assert( i>=0 && i<p->nCursor );
40710   pC = p->apCsr[i];
40711   assert( pC!=0 );
40712   if( pC->pCursor!=0 ){
40713     int res, oc;
40714     oc = pOp->opcode;
40715     pC->nullRow = 0;
40716     *pC->pIncrKey = oc==OP_MoveGt || oc==OP_MoveLe;
40717     if( pC->isTable ){
40718       i64 iKey;
40719       sqlite3VdbeMemIntegerify(pTos);
40720       iKey = intToKey(pTos->u.i);
40721       if( pOp->p2==0 && pOp->opcode==OP_MoveGe ){
40722         pC->movetoTarget = iKey;
40723         pC->deferredMoveto = 1;
40724         assert( (pTos->flags & MEM_Dyn)==0 );
40725         pTos--;
40726         break;
40727       }
40728       rc = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)iKey, 0, &res);
40729       if( rc!=SQLITE_OK ){
40730         goto abort_due_to_error;
40731       }
40732       pC->lastRowid = pTos->u.i;
40733       pC->rowidIsValid = res==0;
40734     }else{
40735       assert( pTos->flags & MEM_Blob );
40736       ExpandBlob(pTos);
40737       rc = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, 0, &res);
40738       if( rc!=SQLITE_OK ){
40739         goto abort_due_to_error;
40740       }
40741       pC->rowidIsValid = 0;
40742     }
40743     pC->deferredMoveto = 0;
40744     pC->cacheStatus = CACHE_STALE;
40745     *pC->pIncrKey = 0;
40746 #ifdef SQLITE_TEST
40747     sqlite3_search_count++;
40748 #endif
40749     if( oc==OP_MoveGe || oc==OP_MoveGt ){
40750       if( res<0 ){
40751         rc = sqlite3BtreeNext(pC->pCursor, &res);
40752         if( rc!=SQLITE_OK ) goto abort_due_to_error;
40753         pC->rowidIsValid = 0;
40754       }else{
40755         res = 0;
40756       }
40757     }else{
40758       assert( oc==OP_MoveLt || oc==OP_MoveLe );
40759       if( res>=0 ){
40760         rc = sqlite3BtreePrevious(pC->pCursor, &res);
40761         if( rc!=SQLITE_OK ) goto abort_due_to_error;
40762         pC->rowidIsValid = 0;
40763       }else{
40764         /* res might be negative because the table is empty.  Check to
40765         ** see if this is the case.
40766         */
40767         res = sqlite3BtreeEof(pC->pCursor);
40768       }
40769     }
40770     if( res ){
40771       if( pOp->p2>0 ){
40772         pc = pOp->p2 - 1;
40773       }else{
40774         pC->nullRow = 1;
40775       }
40776     }
40777   }
40778   Release(pTos);
40779   pTos--;
40780   break;
40781 }
40782
40783 /* Opcode: Distinct P1 P2 *
40784 **
40785 ** Use the top of the stack as a record created using MakeRecord.  P1 is a
40786 ** cursor on a table that declared as an index.  If that table contains an
40787 ** entry that matches the top of the stack fall thru.  If the top of the stack
40788 ** matches no entry in P1 then jump to P2.
40789 **
40790 ** The cursor is left pointing at the matching entry if it exists.  The
40791 ** record on the top of the stack is not popped.
40792 **
40793 ** This instruction is similar to NotFound except that this operation
40794 ** does not pop the key from the stack.
40795 **
40796 ** The instruction is used to implement the DISTINCT operator on SELECT
40797 ** statements.  The P1 table is not a true index but rather a record of
40798 ** all results that have produced so far.  
40799 **
40800 ** See also: Found, NotFound, MoveTo, IsUnique, NotExists
40801 */
40802 /* Opcode: Found P1 P2 *
40803 **
40804 ** Top of the stack holds a blob constructed by MakeRecord.  P1 is an index.
40805 ** If an entry that matches the top of the stack exists in P1 then
40806 ** jump to P2.  If the top of the stack does not match any entry in P1
40807 ** then fall thru.  The P1 cursor is left pointing at the matching entry
40808 ** if it exists.  The blob is popped off the top of the stack.
40809 **
40810 ** This instruction is used to implement the IN operator where the
40811 ** left-hand side is a SELECT statement.  P1 may be a true index, or it
40812 ** may be a temporary index that holds the results of the SELECT
40813 ** statement. 
40814 **
40815 ** This instruction checks if index P1 contains a record for which 
40816 ** the first N serialised values exactly match the N serialised values
40817 ** in the record on the stack, where N is the total number of values in
40818 ** the stack record (stack record is a prefix of the P1 record). 
40819 **
40820 ** See also: Distinct, NotFound, MoveTo, IsUnique, NotExists
40821 */
40822 /* Opcode: NotFound P1 P2 *
40823 **
40824 ** The top of the stack holds a blob constructed by MakeRecord.  P1 is
40825 ** an index.  If no entry exists in P1 that matches the blob then jump
40826 ** to P2.  If an entry does existing, fall through.  The cursor is left
40827 ** pointing to the entry that matches.  The blob is popped from the stack.
40828 **
40829 ** The difference between this operation and Distinct is that
40830 ** Distinct does not pop the key from the stack.
40831 **
40832 ** See also: Distinct, Found, MoveTo, NotExists, IsUnique
40833 */
40834 case OP_Distinct:       /* no-push */
40835 case OP_NotFound:       /* no-push */
40836 case OP_Found: {        /* no-push */
40837   int i = pOp->p1;
40838   int alreadyExists = 0;
40839   Cursor *pC;
40840   assert( pTos>=p->aStack );
40841   assert( i>=0 && i<p->nCursor );
40842   assert( p->apCsr[i]!=0 );
40843   if( (pC = p->apCsr[i])->pCursor!=0 ){
40844     int res;
40845     assert( pC->isTable==0 );
40846     assert( pTos->flags & MEM_Blob );
40847     Stringify(pTos, encoding);
40848     if( pOp->opcode==OP_Found ){
40849       pC->pKeyInfo->prefixIsEqual = 1;
40850     }
40851     rc = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, 0, &res);
40852     pC->pKeyInfo->prefixIsEqual = 0;
40853     if( rc!=SQLITE_OK ){
40854       break;
40855     }
40856     alreadyExists = (res==0);
40857     pC->deferredMoveto = 0;
40858     pC->cacheStatus = CACHE_STALE;
40859   }
40860   if( pOp->opcode==OP_Found ){
40861     if( alreadyExists ) pc = pOp->p2 - 1;
40862   }else{
40863     if( !alreadyExists ) pc = pOp->p2 - 1;
40864   }
40865   if( pOp->opcode!=OP_Distinct ){
40866     Release(pTos);
40867     pTos--;
40868   }
40869   break;
40870 }
40871
40872 /* Opcode: IsUnique P1 P2 *
40873 **
40874 ** The top of the stack is an integer record number.  Call this
40875 ** record number R.  The next on the stack is an index key created
40876 ** using MakeIdxRec.  Call it K.  This instruction pops R from the
40877 ** stack but it leaves K unchanged.
40878 **
40879 ** P1 is an index.  So it has no data and its key consists of a
40880 ** record generated by OP_MakeRecord where the last field is the 
40881 ** rowid of the entry that the index refers to.
40882 ** 
40883 ** This instruction asks if there is an entry in P1 where the
40884 ** fields matches K but the rowid is different from R.
40885 ** If there is no such entry, then there is an immediate
40886 ** jump to P2.  If any entry does exist where the index string
40887 ** matches K but the record number is not R, then the record
40888 ** number for that entry is pushed onto the stack and control
40889 ** falls through to the next instruction.
40890 **
40891 ** See also: Distinct, NotFound, NotExists, Found
40892 */
40893 case OP_IsUnique: {        /* no-push */
40894   int i = pOp->p1;
40895   Mem *pNos = &pTos[-1];
40896   Cursor *pCx;
40897   BtCursor *pCrsr;
40898   i64 R;
40899
40900   /* Pop the value R off the top of the stack
40901   */
40902   assert( pNos>=p->aStack );
40903   sqlite3VdbeMemIntegerify(pTos);
40904   R = pTos->u.i;
40905   assert( (pTos->flags & MEM_Dyn)==0 );
40906   pTos--;
40907   assert( i>=0 && i<p->nCursor );
40908   pCx = p->apCsr[i];
40909   assert( pCx!=0 );
40910   pCrsr = pCx->pCursor;
40911   if( pCrsr!=0 ){
40912     int res;
40913     i64 v;         /* The record number on the P1 entry that matches K */
40914     char *zKey;    /* The value of K */
40915     int nKey;      /* Number of bytes in K */
40916     int len;       /* Number of bytes in K without the rowid at the end */
40917     int szRowid;   /* Size of the rowid column at the end of zKey */
40918
40919     /* Make sure K is a string and make zKey point to K
40920     */
40921     assert( pNos->flags & MEM_Blob );
40922     Stringify(pNos, encoding);
40923     zKey = pNos->z;
40924     nKey = pNos->n;
40925
40926     szRowid = sqlite3VdbeIdxRowidLen((u8*)zKey);
40927     len = nKey-szRowid;
40928
40929     /* Search for an entry in P1 where all but the last four bytes match K.
40930     ** If there is no such entry, jump immediately to P2.
40931     */
40932     assert( pCx->deferredMoveto==0 );
40933     pCx->cacheStatus = CACHE_STALE;
40934     rc = sqlite3BtreeMoveto(pCrsr, zKey, len, 0, &res);
40935     if( rc!=SQLITE_OK ){
40936       goto abort_due_to_error;
40937     }
40938     if( res<0 ){
40939       rc = sqlite3BtreeNext(pCrsr, &res);
40940       if( res ){
40941         pc = pOp->p2 - 1;
40942         break;
40943       }
40944     }
40945     rc = sqlite3VdbeIdxKeyCompare(pCx, len, (u8*)zKey, &res); 
40946     if( rc!=SQLITE_OK ) goto abort_due_to_error;
40947     if( res>0 ){
40948       pc = pOp->p2 - 1;
40949       break;
40950     }
40951
40952     /* At this point, pCrsr is pointing to an entry in P1 where all but
40953     ** the final entry (the rowid) matches K.  Check to see if the
40954     ** final rowid column is different from R.  If it equals R then jump
40955     ** immediately to P2.
40956     */
40957     rc = sqlite3VdbeIdxRowid(pCrsr, &v);
40958     if( rc!=SQLITE_OK ){
40959       goto abort_due_to_error;
40960     }
40961     if( v==R ){
40962       pc = pOp->p2 - 1;
40963       break;
40964     }
40965
40966     /* The final varint of the key is different from R.  Push it onto
40967     ** the stack.  (The record number of an entry that violates a UNIQUE
40968     ** constraint.)
40969     */
40970     pTos++;
40971     pTos->u.i = v;
40972     pTos->flags = MEM_Int;
40973   }
40974   break;
40975 }
40976
40977 /* Opcode: NotExists P1 P2 *
40978 **
40979 ** Use the top of the stack as a integer key.  If a record with that key
40980 ** does not exist in table of P1, then jump to P2.  If the record
40981 ** does exist, then fall thru.  The cursor is left pointing to the
40982 ** record if it exists.  The integer key is popped from the stack.
40983 **
40984 ** The difference between this operation and NotFound is that this
40985 ** operation assumes the key is an integer and that P1 is a table whereas
40986 ** NotFound assumes key is a blob constructed from MakeRecord and
40987 ** P1 is an index.
40988 **
40989 ** See also: Distinct, Found, MoveTo, NotFound, IsUnique
40990 */
40991 case OP_NotExists: {        /* no-push */
40992   int i = pOp->p1;
40993   Cursor *pC;
40994   BtCursor *pCrsr;
40995   assert( pTos>=p->aStack );
40996   assert( i>=0 && i<p->nCursor );
40997   assert( p->apCsr[i]!=0 );
40998   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
40999     int res;
41000     u64 iKey;
41001     assert( pTos->flags & MEM_Int );
41002     assert( p->apCsr[i]->isTable );
41003     iKey = intToKey(pTos->u.i);
41004     rc = sqlite3BtreeMoveto(pCrsr, 0, iKey, 0,&res);
41005     pC->lastRowid = pTos->u.i;
41006     pC->rowidIsValid = res==0;
41007     pC->nullRow = 0;
41008     pC->cacheStatus = CACHE_STALE;
41009     /* res might be uninitialized if rc!=SQLITE_OK.  But if rc!=SQLITE_OK
41010     ** processing is about to abort so we really do not care whether or not
41011     ** the following jump is taken.  (In other words, do not stress over
41012     ** the error that valgrind sometimes shows on the next statement when
41013     ** running ioerr.test and similar failure-recovery test scripts.) */
41014     if( res!=0 ){
41015       pc = pOp->p2 - 1;
41016       pC->rowidIsValid = 0;
41017     }
41018   }
41019   Release(pTos);
41020   pTos--;
41021   break;
41022 }
41023
41024 /* Opcode: Sequence P1 * *
41025 **
41026 ** Push an integer onto the stack which is the next available
41027 ** sequence number for cursor P1.  The sequence number on the
41028 ** cursor is incremented after the push.
41029 */
41030 case OP_Sequence: {
41031   int i = pOp->p1;
41032   assert( pTos>=p->aStack );
41033   assert( i>=0 && i<p->nCursor );
41034   assert( p->apCsr[i]!=0 );
41035   pTos++;
41036   pTos->u.i = p->apCsr[i]->seqCount++;
41037   pTos->flags = MEM_Int;
41038   break;
41039 }
41040
41041
41042 /* Opcode: NewRowid P1 P2 *
41043 **
41044 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
41045 ** The record number is not previously used as a key in the database
41046 ** table that cursor P1 points to.  The new record number is pushed 
41047 ** onto the stack.
41048 **
41049 ** If P2>0 then P2 is a memory cell that holds the largest previously
41050 ** generated record number.  No new record numbers are allowed to be less
41051 ** than this value.  When this value reaches its maximum, a SQLITE_FULL
41052 ** error is generated.  The P2 memory cell is updated with the generated
41053 ** record number.  This P2 mechanism is used to help implement the
41054 ** AUTOINCREMENT feature.
41055 */
41056 case OP_NewRowid: {
41057   int i = pOp->p1;
41058   i64 v = 0;
41059   Cursor *pC;
41060   assert( i>=0 && i<p->nCursor );
41061   assert( p->apCsr[i]!=0 );
41062   if( (pC = p->apCsr[i])->pCursor==0 ){
41063     /* The zero initialization above is all that is needed */
41064   }else{
41065     /* The next rowid or record number (different terms for the same
41066     ** thing) is obtained in a two-step algorithm.
41067     **
41068     ** First we attempt to find the largest existing rowid and add one
41069     ** to that.  But if the largest existing rowid is already the maximum
41070     ** positive integer, we have to fall through to the second
41071     ** probabilistic algorithm
41072     **
41073     ** The second algorithm is to select a rowid at random and see if
41074     ** it already exists in the table.  If it does not exist, we have
41075     ** succeeded.  If the random rowid does exist, we select a new one
41076     ** and try again, up to 1000 times.
41077     **
41078     ** For a table with less than 2 billion entries, the probability
41079     ** of not finding a unused rowid is about 1.0e-300.  This is a 
41080     ** non-zero probability, but it is still vanishingly small and should
41081     ** never cause a problem.  You are much, much more likely to have a
41082     ** hardware failure than for this algorithm to fail.
41083     **
41084     ** The analysis in the previous paragraph assumes that you have a good
41085     ** source of random numbers.  Is a library function like lrand48()
41086     ** good enough?  Maybe. Maybe not. It's hard to know whether there
41087     ** might be subtle bugs is some implementations of lrand48() that
41088     ** could cause problems. To avoid uncertainty, SQLite uses its own 
41089     ** random number generator based on the RC4 algorithm.
41090     **
41091     ** To promote locality of reference for repetitive inserts, the
41092     ** first few attempts at chosing a random rowid pick values just a little
41093     ** larger than the previous rowid.  This has been shown experimentally
41094     ** to double the speed of the COPY operation.
41095     */
41096     int res, rx=SQLITE_OK, cnt;
41097     i64 x;
41098     cnt = 0;
41099     if( (sqlite3BtreeFlags(pC->pCursor)&(BTREE_INTKEY|BTREE_ZERODATA)) !=
41100           BTREE_INTKEY ){
41101       rc = SQLITE_CORRUPT_BKPT;
41102       goto abort_due_to_error;
41103     }
41104     assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_INTKEY)!=0 );
41105     assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_ZERODATA)==0 );
41106
41107 #ifdef SQLITE_32BIT_ROWID
41108 #   define MAX_ROWID 0x7fffffff
41109 #else
41110     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
41111     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
41112     ** to provide the constant while making all compilers happy.
41113     */
41114 #   define MAX_ROWID  ( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
41115 #endif
41116
41117     if( !pC->useRandomRowid ){
41118       if( pC->nextRowidValid ){
41119         v = pC->nextRowid;
41120       }else{
41121         rc = sqlite3BtreeLast(pC->pCursor, &res);
41122         if( rc!=SQLITE_OK ){
41123           goto abort_due_to_error;
41124         }
41125         if( res ){
41126           v = 1;
41127         }else{
41128           sqlite3BtreeKeySize(pC->pCursor, &v);
41129           v = keyToInt(v);
41130           if( v==MAX_ROWID ){
41131             pC->useRandomRowid = 1;
41132           }else{
41133             v++;
41134           }
41135         }
41136       }
41137
41138 #ifndef SQLITE_OMIT_AUTOINCREMENT
41139       if( pOp->p2 ){
41140         Mem *pMem;
41141         assert( pOp->p2>0 && pOp->p2<p->nMem );  /* P2 is a valid memory cell */
41142         pMem = &p->aMem[pOp->p2];
41143         sqlite3VdbeMemIntegerify(pMem);
41144         assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P2) holds an integer */
41145         if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
41146           rc = SQLITE_FULL;
41147           goto abort_due_to_error;
41148         }
41149         if( v<pMem->u.i+1 ){
41150           v = pMem->u.i + 1;
41151         }
41152         pMem->u.i = v;
41153       }
41154 #endif
41155
41156       if( v<MAX_ROWID ){
41157         pC->nextRowidValid = 1;
41158         pC->nextRowid = v+1;
41159       }else{
41160         pC->nextRowidValid = 0;
41161       }
41162     }
41163     if( pC->useRandomRowid ){
41164       assert( pOp->p2==0 );  /* SQLITE_FULL must have occurred prior to this */
41165       v = db->priorNewRowid;
41166       cnt = 0;
41167       do{
41168         if( v==0 || cnt>2 ){
41169           sqlite3Randomness(sizeof(v), &v);
41170           if( cnt<5 ) v &= 0xffffff;
41171         }else{
41172           unsigned char r;
41173           sqlite3Randomness(1, &r);
41174           v += r + 1;
41175         }
41176         if( v==0 ) continue;
41177         x = intToKey(v);
41178         rx = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)x, 0, &res);
41179         cnt++;
41180       }while( cnt<1000 && rx==SQLITE_OK && res==0 );
41181       db->priorNewRowid = v;
41182       if( rx==SQLITE_OK && res==0 ){
41183         rc = SQLITE_FULL;
41184         goto abort_due_to_error;
41185       }
41186     }
41187     pC->rowidIsValid = 0;
41188     pC->deferredMoveto = 0;
41189     pC->cacheStatus = CACHE_STALE;
41190   }
41191   pTos++;
41192   pTos->u.i = v;
41193   pTos->flags = MEM_Int;
41194   break;
41195 }
41196
41197 /* Opcode: Insert P1 P2 P3
41198 **
41199 ** Write an entry into the table of cursor P1.  A new entry is
41200 ** created if it doesn't already exist or the data for an existing
41201 ** entry is overwritten.  The data is the value on the top of the
41202 ** stack.  The key is the next value down on the stack.  The key must
41203 ** be an integer.  The stack is popped twice by this instruction.
41204 **
41205 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
41206 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P2 is set,
41207 ** then rowid is stored for subsequent return by the
41208 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
41209 **
41210 ** Parameter P3 may point to a string containing the table-name, or
41211 ** may be NULL. If it is not NULL, then the update-hook 
41212 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
41213 **
41214 ** This instruction only works on tables.  The equivalent instruction
41215 ** for indices is OP_IdxInsert.
41216 */
41217 case OP_Insert: {         /* no-push */
41218   Mem *pNos = &pTos[-1];
41219   int i = pOp->p1;
41220   Cursor *pC;
41221   assert( pNos>=p->aStack );
41222   assert( i>=0 && i<p->nCursor );
41223   assert( p->apCsr[i]!=0 );
41224   if( ((pC = p->apCsr[i])->pCursor!=0 || pC->pseudoTable) ){
41225     i64 iKey;   /* The integer ROWID or key for the record to be inserted */
41226
41227     assert( pNos->flags & MEM_Int );
41228     assert( pC->isTable );
41229     iKey = intToKey(pNos->u.i);
41230
41231     if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
41232     if( pOp->p2 & OPFLAG_LASTROWID ) db->lastRowid = pNos->u.i;
41233     if( pC->nextRowidValid && pNos->u.i>=pC->nextRowid ){
41234       pC->nextRowidValid = 0;
41235     }
41236     if( pTos->flags & MEM_Null ){
41237       pTos->z = 0;
41238       pTos->n = 0;
41239     }else{
41240       assert( pTos->flags & (MEM_Blob|MEM_Str) );
41241     }
41242     if( pC->pseudoTable ){
41243       sqlite3_free(pC->pData);
41244       pC->iKey = iKey;
41245       pC->nData = pTos->n;
41246       if( pTos->flags & MEM_Dyn ){
41247         pC->pData = pTos->z;
41248         pTos->flags = MEM_Null;
41249       }else{
41250         pC->pData = sqlite3_malloc( pC->nData+2 );
41251         if( !pC->pData ) goto no_mem;
41252         memcpy(pC->pData, pTos->z, pC->nData);
41253         pC->pData[pC->nData] = 0;
41254         pC->pData[pC->nData+1] = 0;
41255       }
41256       pC->nullRow = 0;
41257     }else{
41258       int nZero;
41259       if( pTos->flags & MEM_Zero ){
41260         nZero = pTos->u.i;
41261       }else{
41262         nZero = 0;
41263       }
41264       rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
41265                               pTos->z, pTos->n, nZero,
41266                               pOp->p2 & OPFLAG_APPEND);
41267     }
41268     
41269     pC->rowidIsValid = 0;
41270     pC->deferredMoveto = 0;
41271     pC->cacheStatus = CACHE_STALE;
41272
41273     /* Invoke the update-hook if required. */
41274     if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p3 ){
41275       const char *zDb = db->aDb[pC->iDb].zName;
41276       const char *zTbl = pOp->p3;
41277       int op = ((pOp->p2 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
41278       assert( pC->isTable );
41279       db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
41280       assert( pC->iDb>=0 );
41281     }
41282   }
41283   popStack(&pTos, 2);
41284
41285   break;
41286 }
41287
41288 /* Opcode: Delete P1 P2 P3
41289 **
41290 ** Delete the record at which the P1 cursor is currently pointing.
41291 **
41292 ** The cursor will be left pointing at either the next or the previous
41293 ** record in the table. If it is left pointing at the next record, then
41294 ** the next Next instruction will be a no-op.  Hence it is OK to delete
41295 ** a record from within an Next loop.
41296 **
41297 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
41298 ** incremented (otherwise not).
41299 **
41300 ** If P1 is a pseudo-table, then this instruction is a no-op.
41301 */
41302 case OP_Delete: {        /* no-push */
41303   int i = pOp->p1;
41304   Cursor *pC;
41305   assert( i>=0 && i<p->nCursor );
41306   pC = p->apCsr[i];
41307   assert( pC!=0 );
41308   if( pC->pCursor!=0 ){
41309     i64 iKey;
41310
41311     /* If the update-hook will be invoked, set iKey to the rowid of the
41312     ** row being deleted.
41313     */
41314     if( db->xUpdateCallback && pOp->p3 ){
41315       assert( pC->isTable );
41316       if( pC->rowidIsValid ){
41317         iKey = pC->lastRowid;
41318       }else{
41319         rc = sqlite3BtreeKeySize(pC->pCursor, &iKey);
41320         if( rc ){
41321           goto abort_due_to_error;
41322         }
41323         iKey = keyToInt(iKey);
41324       }
41325     }
41326
41327     rc = sqlite3VdbeCursorMoveto(pC);
41328     if( rc ) goto abort_due_to_error;
41329     rc = sqlite3BtreeDelete(pC->pCursor);
41330     pC->nextRowidValid = 0;
41331     pC->cacheStatus = CACHE_STALE;
41332
41333     /* Invoke the update-hook if required. */
41334     if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p3 ){
41335       const char *zDb = db->aDb[pC->iDb].zName;
41336       const char *zTbl = pOp->p3;
41337       db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
41338       assert( pC->iDb>=0 );
41339     }
41340   }
41341   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
41342   break;
41343 }
41344
41345 /* Opcode: ResetCount P1 * *
41346 **
41347 ** This opcode resets the VMs internal change counter to 0. If P1 is true,
41348 ** then the value of the change counter is copied to the database handle
41349 ** change counter (returned by subsequent calls to sqlite3_changes())
41350 ** before it is reset. This is used by trigger programs.
41351 */
41352 case OP_ResetCount: {        /* no-push */
41353   if( pOp->p1 ){
41354     sqlite3VdbeSetChanges(db, p->nChange);
41355   }
41356   p->nChange = 0;
41357   break;
41358 }
41359
41360 /* Opcode: RowData P1 * *
41361 **
41362 ** Push onto the stack the complete row data for cursor P1.
41363 ** There is no interpretation of the data.  It is just copied
41364 ** onto the stack exactly as it is found in the database file.
41365 **
41366 ** If the cursor is not pointing to a valid row, a NULL is pushed
41367 ** onto the stack.
41368 */
41369 /* Opcode: RowKey P1 * *
41370 **
41371 ** Push onto the stack the complete row key for cursor P1.
41372 ** There is no interpretation of the key.  It is just copied
41373 ** onto the stack exactly as it is found in the database file.
41374 **
41375 ** If the cursor is not pointing to a valid row, a NULL is pushed
41376 ** onto the stack.
41377 */
41378 case OP_RowKey:
41379 case OP_RowData: {
41380   int i = pOp->p1;
41381   Cursor *pC;
41382   u32 n;
41383
41384   /* Note that RowKey and RowData are really exactly the same instruction */
41385   pTos++;
41386   assert( i>=0 && i<p->nCursor );
41387   pC = p->apCsr[i];
41388   assert( pC->isTable || pOp->opcode==OP_RowKey );
41389   assert( pC->isIndex || pOp->opcode==OP_RowData );
41390   assert( pC!=0 );
41391   if( pC->nullRow ){
41392     pTos->flags = MEM_Null;
41393   }else if( pC->pCursor!=0 ){
41394     BtCursor *pCrsr = pC->pCursor;
41395     rc = sqlite3VdbeCursorMoveto(pC);
41396     if( rc ) goto abort_due_to_error;
41397     if( pC->nullRow ){
41398       pTos->flags = MEM_Null;
41399       break;
41400     }else if( pC->isIndex ){
41401       i64 n64;
41402       assert( !pC->isTable );
41403       sqlite3BtreeKeySize(pCrsr, &n64);
41404       if( n64>SQLITE_MAX_LENGTH ){
41405         goto too_big;
41406       }
41407       n = n64;
41408     }else{
41409       sqlite3BtreeDataSize(pCrsr, &n);
41410     }
41411     if( n>SQLITE_MAX_LENGTH ){
41412       goto too_big;
41413     }
41414     pTos->n = n;
41415     if( n<=NBFS ){
41416       pTos->flags = MEM_Blob | MEM_Short;
41417       pTos->z = pTos->zShort;
41418     }else{
41419       char *z = sqlite3_malloc( n );
41420       if( z==0 ) goto no_mem;
41421       pTos->flags = MEM_Blob | MEM_Dyn;
41422       pTos->xDel = 0;
41423       pTos->z = z;
41424     }
41425     if( pC->isIndex ){
41426       rc = sqlite3BtreeKey(pCrsr, 0, n, pTos->z);
41427     }else{
41428       rc = sqlite3BtreeData(pCrsr, 0, n, pTos->z);
41429     }
41430   }else if( pC->pseudoTable ){
41431     pTos->n = pC->nData;
41432     assert( pC->nData<=SQLITE_MAX_LENGTH );
41433     pTos->z = pC->pData;
41434     pTos->flags = MEM_Blob|MEM_Ephem;
41435   }else{
41436     pTos->flags = MEM_Null;
41437   }
41438   pTos->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
41439   break;
41440 }
41441
41442 /* Opcode: Rowid P1 * *
41443 **
41444 ** Push onto the stack an integer which is the key of the table entry that
41445 ** P1 is currently point to.
41446 */
41447 case OP_Rowid: {
41448   int i = pOp->p1;
41449   Cursor *pC;
41450   i64 v;
41451
41452   assert( i>=0 && i<p->nCursor );
41453   pC = p->apCsr[i];
41454   assert( pC!=0 );
41455   rc = sqlite3VdbeCursorMoveto(pC);
41456   if( rc ) goto abort_due_to_error;
41457   pTos++;
41458   if( pC->rowidIsValid ){
41459     v = pC->lastRowid;
41460   }else if( pC->pseudoTable ){
41461     v = keyToInt(pC->iKey);
41462   }else if( pC->nullRow || pC->pCursor==0 ){
41463     pTos->flags = MEM_Null;
41464     break;
41465   }else{
41466     assert( pC->pCursor!=0 );
41467     sqlite3BtreeKeySize(pC->pCursor, &v);
41468     v = keyToInt(v);
41469   }
41470   pTos->u.i = v;
41471   pTos->flags = MEM_Int;
41472   break;
41473 }
41474
41475 /* Opcode: NullRow P1 * *
41476 **
41477 ** Move the cursor P1 to a null row.  Any OP_Column operations
41478 ** that occur while the cursor is on the null row will always push 
41479 ** a NULL onto the stack.
41480 */
41481 case OP_NullRow: {        /* no-push */
41482   int i = pOp->p1;
41483   Cursor *pC;
41484
41485   assert( i>=0 && i<p->nCursor );
41486   pC = p->apCsr[i];
41487   assert( pC!=0 );
41488   pC->nullRow = 1;
41489   pC->rowidIsValid = 0;
41490   break;
41491 }
41492
41493 /* Opcode: Last P1 P2 *
41494 **
41495 ** The next use of the Rowid or Column or Next instruction for P1 
41496 ** will refer to the last entry in the database table or index.
41497 ** If the table or index is empty and P2>0, then jump immediately to P2.
41498 ** If P2 is 0 or if the table or index is not empty, fall through
41499 ** to the following instruction.
41500 */
41501 case OP_Last: {        /* no-push */
41502   int i = pOp->p1;
41503   Cursor *pC;
41504   BtCursor *pCrsr;
41505
41506   assert( i>=0 && i<p->nCursor );
41507   pC = p->apCsr[i];
41508   assert( pC!=0 );
41509   if( (pCrsr = pC->pCursor)!=0 ){
41510     int res;
41511     rc = sqlite3BtreeLast(pCrsr, &res);
41512     pC->nullRow = res;
41513     pC->deferredMoveto = 0;
41514     pC->cacheStatus = CACHE_STALE;
41515     if( res && pOp->p2>0 ){
41516       pc = pOp->p2 - 1;
41517     }
41518   }else{
41519     pC->nullRow = 0;
41520   }
41521   break;
41522 }
41523
41524
41525 /* Opcode: Sort P1 P2 *
41526 **
41527 ** This opcode does exactly the same thing as OP_Rewind except that
41528 ** it increments an undocumented global variable used for testing.
41529 **
41530 ** Sorting is accomplished by writing records into a sorting index,
41531 ** then rewinding that index and playing it back from beginning to
41532 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
41533 ** rewinding so that the global variable will be incremented and
41534 ** regression tests can determine whether or not the optimizer is
41535 ** correctly optimizing out sorts.
41536 */
41537 case OP_Sort: {        /* no-push */
41538 #ifdef SQLITE_TEST
41539   sqlite3_sort_count++;
41540   sqlite3_search_count--;
41541 #endif
41542   /* Fall through into OP_Rewind */
41543 }
41544 /* Opcode: Rewind P1 P2 *
41545 **
41546 ** The next use of the Rowid or Column or Next instruction for P1 
41547 ** will refer to the first entry in the database table or index.
41548 ** If the table or index is empty and P2>0, then jump immediately to P2.
41549 ** If P2 is 0 or if the table or index is not empty, fall through
41550 ** to the following instruction.
41551 */
41552 case OP_Rewind: {        /* no-push */
41553   int i = pOp->p1;
41554   Cursor *pC;
41555   BtCursor *pCrsr;
41556   int res;
41557
41558   assert( i>=0 && i<p->nCursor );
41559   pC = p->apCsr[i];
41560   assert( pC!=0 );
41561   if( (pCrsr = pC->pCursor)!=0 ){
41562     rc = sqlite3BtreeFirst(pCrsr, &res);
41563     pC->atFirst = res==0;
41564     pC->deferredMoveto = 0;
41565     pC->cacheStatus = CACHE_STALE;
41566   }else{
41567     res = 1;
41568   }
41569   pC->nullRow = res;
41570   if( res && pOp->p2>0 ){
41571     pc = pOp->p2 - 1;
41572   }
41573   break;
41574 }
41575
41576 /* Opcode: Next P1 P2 *
41577 **
41578 ** Advance cursor P1 so that it points to the next key/data pair in its
41579 ** table or index.  If there are no more key/value pairs then fall through
41580 ** to the following instruction.  But if the cursor advance was successful,
41581 ** jump immediately to P2.
41582 **
41583 ** See also: Prev
41584 */
41585 /* Opcode: Prev P1 P2 *
41586 **
41587 ** Back up cursor P1 so that it points to the previous key/data pair in its
41588 ** table or index.  If there is no previous key/value pairs then fall through
41589 ** to the following instruction.  But if the cursor backup was successful,
41590 ** jump immediately to P2.
41591 */
41592 case OP_Prev:          /* no-push */
41593 case OP_Next: {        /* no-push */
41594   Cursor *pC;
41595   BtCursor *pCrsr;
41596
41597   CHECK_FOR_INTERRUPT;
41598   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
41599   pC = p->apCsr[pOp->p1];
41600   if( pC==0 ){
41601     break;  /* See ticket #2273 */
41602   }
41603   if( (pCrsr = pC->pCursor)!=0 ){
41604     int res;
41605     if( pC->nullRow ){
41606       res = 1;
41607     }else{
41608       assert( pC->deferredMoveto==0 );
41609       rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) :
41610                                   sqlite3BtreePrevious(pCrsr, &res);
41611       pC->nullRow = res;
41612       pC->cacheStatus = CACHE_STALE;
41613     }
41614     if( res==0 ){
41615       pc = pOp->p2 - 1;
41616 #ifdef SQLITE_TEST
41617       sqlite3_search_count++;
41618 #endif
41619     }
41620   }else{
41621     pC->nullRow = 1;
41622   }
41623   pC->rowidIsValid = 0;
41624   break;
41625 }
41626
41627 /* Opcode: IdxInsert P1 P2 *
41628 **
41629 ** The top of the stack holds a SQL index key made using either the
41630 ** MakeIdxRec or MakeRecord instructions.  This opcode writes that key
41631 ** into the index P1.  Data for the entry is nil.
41632 **
41633 ** P2 is a flag that provides a hint to the b-tree layer that this
41634 ** insert is likely to be an append.
41635 **
41636 ** This instruction only works for indices.  The equivalent instruction
41637 ** for tables is OP_Insert.
41638 */
41639 case OP_IdxInsert: {        /* no-push */
41640   int i = pOp->p1;
41641   Cursor *pC;
41642   BtCursor *pCrsr;
41643   assert( pTos>=p->aStack );
41644   assert( i>=0 && i<p->nCursor );
41645   assert( p->apCsr[i]!=0 );
41646   assert( pTos->flags & MEM_Blob );
41647   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
41648     assert( pC->isTable==0 );
41649     rc = ExpandBlob(pTos);
41650     if( rc==SQLITE_OK ){
41651       int nKey = pTos->n;
41652       const char *zKey = pTos->z;
41653       rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p2);
41654       assert( pC->deferredMoveto==0 );
41655       pC->cacheStatus = CACHE_STALE;
41656     }
41657   }
41658   Release(pTos);
41659   pTos--;
41660   break;
41661 }
41662
41663 /* Opcode: IdxDelete P1 * *
41664 **
41665 ** The top of the stack is an index key built using the either the
41666 ** MakeIdxRec or MakeRecord opcodes.
41667 ** This opcode removes that entry from the index.
41668 */
41669 case OP_IdxDelete: {        /* no-push */
41670   int i = pOp->p1;
41671   Cursor *pC;
41672   BtCursor *pCrsr;
41673   assert( pTos>=p->aStack );
41674   assert( pTos->flags & MEM_Blob );
41675   assert( i>=0 && i<p->nCursor );
41676   assert( p->apCsr[i]!=0 );
41677   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
41678     int res;
41679     rc = sqlite3BtreeMoveto(pCrsr, pTos->z, pTos->n, 0, &res);
41680     if( rc==SQLITE_OK && res==0 ){
41681       rc = sqlite3BtreeDelete(pCrsr);
41682     }
41683     assert( pC->deferredMoveto==0 );
41684     pC->cacheStatus = CACHE_STALE;
41685   }
41686   Release(pTos);
41687   pTos--;
41688   break;
41689 }
41690
41691 /* Opcode: IdxRowid P1 * *
41692 **
41693 ** Push onto the stack an integer which is the last entry in the record at
41694 ** the end of the index key pointed to by cursor P1.  This integer should be
41695 ** the rowid of the table entry to which this index entry points.
41696 **
41697 ** See also: Rowid, MakeIdxRec.
41698 */
41699 case OP_IdxRowid: {
41700   int i = pOp->p1;
41701   BtCursor *pCrsr;
41702   Cursor *pC;
41703
41704   assert( i>=0 && i<p->nCursor );
41705   assert( p->apCsr[i]!=0 );
41706   pTos++;
41707   pTos->flags = MEM_Null;
41708   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
41709     i64 rowid;
41710
41711     assert( pC->deferredMoveto==0 );
41712     assert( pC->isTable==0 );
41713     if( pC->nullRow ){
41714       pTos->flags = MEM_Null;
41715     }else{
41716       rc = sqlite3VdbeIdxRowid(pCrsr, &rowid);
41717       if( rc!=SQLITE_OK ){
41718         goto abort_due_to_error;
41719       }
41720       pTos->flags = MEM_Int;
41721       pTos->u.i = rowid;
41722     }
41723   }
41724   break;
41725 }
41726
41727 /* Opcode: IdxGT P1 P2 *
41728 **
41729 ** The top of the stack is an index entry that omits the ROWID.  Compare
41730 ** the top of stack against the index that P1 is currently pointing to.
41731 ** Ignore the ROWID on the P1 index.
41732 **
41733 ** The top of the stack might have fewer columns that P1.
41734 **
41735 ** If the P1 index entry is greater than the top of the stack
41736 ** then jump to P2.  Otherwise fall through to the next instruction.
41737 ** In either case, the stack is popped once.
41738 */
41739 /* Opcode: IdxGE P1 P2 P3
41740 **
41741 ** The top of the stack is an index entry that omits the ROWID.  Compare
41742 ** the top of stack against the index that P1 is currently pointing to.
41743 ** Ignore the ROWID on the P1 index.
41744 **
41745 ** If the P1 index entry is greater than or equal to the top of the stack
41746 ** then jump to P2.  Otherwise fall through to the next instruction.
41747 ** In either case, the stack is popped once.
41748 **
41749 ** If P3 is the "+" string (or any other non-NULL string) then the
41750 ** index taken from the top of the stack is temporarily increased by
41751 ** an epsilon prior to the comparison.  This make the opcode work
41752 ** like IdxGT except that if the key from the stack is a prefix of
41753 ** the key in the cursor, the result is false whereas it would be
41754 ** true with IdxGT.
41755 */
41756 /* Opcode: IdxLT P1 P2 P3
41757 **
41758 ** The top of the stack is an index entry that omits the ROWID.  Compare
41759 ** the top of stack against the index that P1 is currently pointing to.
41760 ** Ignore the ROWID on the P1 index.
41761 **
41762 ** If the P1 index entry is less than  the top of the stack
41763 ** then jump to P2.  Otherwise fall through to the next instruction.
41764 ** In either case, the stack is popped once.
41765 **
41766 ** If P3 is the "+" string (or any other non-NULL string) then the
41767 ** index taken from the top of the stack is temporarily increased by
41768 ** an epsilon prior to the comparison.  This makes the opcode work
41769 ** like IdxLE.
41770 */
41771 case OP_IdxLT:          /* no-push */
41772 case OP_IdxGT:          /* no-push */
41773 case OP_IdxGE: {        /* no-push */
41774   int i= pOp->p1;
41775   Cursor *pC;
41776
41777   assert( i>=0 && i<p->nCursor );
41778   assert( p->apCsr[i]!=0 );
41779   assert( pTos>=p->aStack );
41780   if( (pC = p->apCsr[i])->pCursor!=0 ){
41781     int res;
41782  
41783     assert( pTos->flags & MEM_Blob );  /* Created using OP_MakeRecord */
41784     assert( pC->deferredMoveto==0 );
41785     ExpandBlob(pTos);
41786     *pC->pIncrKey = pOp->p3!=0;
41787     assert( pOp->p3==0 || pOp->opcode!=OP_IdxGT );
41788     rc = sqlite3VdbeIdxKeyCompare(pC, pTos->n, (u8*)pTos->z, &res);
41789     *pC->pIncrKey = 0;
41790     if( rc!=SQLITE_OK ){
41791       break;
41792     }
41793     if( pOp->opcode==OP_IdxLT ){
41794       res = -res;
41795     }else if( pOp->opcode==OP_IdxGE ){
41796       res++;
41797     }
41798     if( res>0 ){
41799       pc = pOp->p2 - 1 ;
41800     }
41801   }
41802   Release(pTos);
41803   pTos--;
41804   break;
41805 }
41806
41807 /* Opcode: Destroy P1 P2 *
41808 **
41809 ** Delete an entire database table or index whose root page in the database
41810 ** file is given by P1.
41811 **
41812 ** The table being destroyed is in the main database file if P2==0.  If
41813 ** P2==1 then the table to be clear is in the auxiliary database file
41814 ** that is used to store tables create using CREATE TEMPORARY TABLE.
41815 **
41816 ** If AUTOVACUUM is enabled then it is possible that another root page
41817 ** might be moved into the newly deleted root page in order to keep all
41818 ** root pages contiguous at the beginning of the database.  The former
41819 ** value of the root page that moved - its value before the move occurred -
41820 ** is pushed onto the stack.  If no page movement was required (because
41821 ** the table being dropped was already the last one in the database) then
41822 ** a zero is pushed onto the stack.  If AUTOVACUUM is disabled
41823 ** then a zero is pushed onto the stack.
41824 **
41825 ** See also: Clear
41826 */
41827 case OP_Destroy: {
41828   int iMoved;
41829   int iCnt;
41830 #ifndef SQLITE_OMIT_VIRTUALTABLE
41831   Vdbe *pVdbe;
41832   iCnt = 0;
41833   for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
41834     if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->inVtabMethod<2 && pVdbe->pc>=0 ){
41835       iCnt++;
41836     }
41837   }
41838 #else
41839   iCnt = db->activeVdbeCnt;
41840 #endif
41841   if( iCnt>1 ){
41842     rc = SQLITE_LOCKED;
41843     p->errorAction = OE_Abort;
41844   }else{
41845     assert( iCnt==1 );
41846     assert( (p->btreeMask & (1<<pOp->p2))!=0 );
41847     rc = sqlite3BtreeDropTable(db->aDb[pOp->p2].pBt, pOp->p1, &iMoved);
41848     pTos++;
41849     pTos->flags = MEM_Int;
41850     pTos->u.i = iMoved;
41851 #ifndef SQLITE_OMIT_AUTOVACUUM
41852     if( rc==SQLITE_OK && iMoved!=0 ){
41853       sqlite3RootPageMoved(&db->aDb[pOp->p2], iMoved, pOp->p1);
41854     }
41855 #endif
41856   }
41857   break;
41858 }
41859
41860 /* Opcode: Clear P1 P2 *
41861 **
41862 ** Delete all contents of the database table or index whose root page
41863 ** in the database file is given by P1.  But, unlike Destroy, do not
41864 ** remove the table or index from the database file.
41865 **
41866 ** The table being clear is in the main database file if P2==0.  If
41867 ** P2==1 then the table to be clear is in the auxiliary database file
41868 ** that is used to store tables create using CREATE TEMPORARY TABLE.
41869 **
41870 ** See also: Destroy
41871 */
41872 case OP_Clear: {        /* no-push */
41873
41874   /* For consistency with the way other features of SQLite operate
41875   ** with a truncate, we will also skip the update callback.
41876   */
41877 #if 0
41878   Btree *pBt = db->aDb[pOp->p2].pBt;
41879   if( db->xUpdateCallback && pOp->p3 ){
41880     const char *zDb = db->aDb[pOp->p2].zName;
41881     const char *zTbl = pOp->p3;
41882     BtCursor *pCur = 0;
41883     int fin = 0;
41884
41885     rc = sqlite3BtreeCursor(pBt, pOp->p1, 0, 0, 0, &pCur);
41886     if( rc!=SQLITE_OK ){
41887       goto abort_due_to_error;
41888     }
41889     for(
41890       rc=sqlite3BtreeFirst(pCur, &fin); 
41891       rc==SQLITE_OK && !fin; 
41892       rc=sqlite3BtreeNext(pCur, &fin)
41893     ){
41894       i64 iKey;
41895       rc = sqlite3BtreeKeySize(pCur, &iKey);
41896       if( rc ){
41897         break;
41898       }
41899       iKey = keyToInt(iKey);
41900       db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
41901     }
41902     sqlite3BtreeCloseCursor(pCur);
41903     if( rc!=SQLITE_OK ){
41904       goto abort_due_to_error;
41905     }
41906   }
41907 #endif
41908   assert( (p->btreeMask & (1<<pOp->p2))!=0 );
41909   rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, pOp->p1);
41910   break;
41911 }
41912
41913 /* Opcode: CreateTable P1 * *
41914 **
41915 ** Allocate a new table in the main database file if P2==0 or in the
41916 ** auxiliary database file if P2==1.  Push the page number
41917 ** for the root page of the new table onto the stack.
41918 **
41919 ** The difference between a table and an index is this:  A table must
41920 ** have a 4-byte integer key and can have arbitrary data.  An index
41921 ** has an arbitrary key but no data.
41922 **
41923 ** See also: CreateIndex
41924 */
41925 /* Opcode: CreateIndex P1 * *
41926 **
41927 ** Allocate a new index in the main database file if P2==0 or in the
41928 ** auxiliary database file if P2==1.  Push the page number of the
41929 ** root page of the new index onto the stack.
41930 **
41931 ** See documentation on OP_CreateTable for additional information.
41932 */
41933 case OP_CreateIndex:
41934 case OP_CreateTable: {
41935   int pgno;
41936   int flags;
41937   Db *pDb;
41938   assert( pOp->p1>=0 && pOp->p1<db->nDb );
41939   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
41940   pDb = &db->aDb[pOp->p1];
41941   assert( pDb->pBt!=0 );
41942   if( pOp->opcode==OP_CreateTable ){
41943     /* flags = BTREE_INTKEY; */
41944     flags = BTREE_LEAFDATA|BTREE_INTKEY;
41945   }else{
41946     flags = BTREE_ZERODATA;
41947   }
41948   rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
41949   pTos++;
41950   if( rc==SQLITE_OK ){
41951     pTos->u.i = pgno;
41952     pTos->flags = MEM_Int;
41953   }else{
41954     pTos->flags = MEM_Null;
41955   }
41956   break;
41957 }
41958
41959 /* Opcode: ParseSchema P1 P2 P3
41960 **
41961 ** Read and parse all entries from the SQLITE_MASTER table of database P1
41962 ** that match the WHERE clause P3.  P2 is the "force" flag.   Always do
41963 ** the parsing if P2 is true.  If P2 is false, then this routine is a
41964 ** no-op if the schema is not currently loaded.  In other words, if P2
41965 ** is false, the SQLITE_MASTER table is only parsed if the rest of the
41966 ** schema is already loaded into the symbol table.
41967 **
41968 ** This opcode invokes the parser to create a new virtual machine,
41969 ** then runs the new virtual machine.  It is thus a reentrant opcode.
41970 */
41971 case OP_ParseSchema: {        /* no-push */
41972   char *zSql;
41973   int iDb = pOp->p1;
41974   const char *zMaster;
41975   InitData initData;
41976
41977   assert( iDb>=0 && iDb<db->nDb );
41978   if( !pOp->p2 && !DbHasProperty(db, iDb, DB_SchemaLoaded) ){
41979     break;
41980   }
41981   zMaster = SCHEMA_TABLE(iDb);
41982   initData.db = db;
41983   initData.iDb = pOp->p1;
41984   initData.pzErrMsg = &p->zErrMsg;
41985   zSql = sqlite3MPrintf(db,
41986      "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
41987      db->aDb[iDb].zName, zMaster, pOp->p3);
41988   if( zSql==0 ) goto no_mem;
41989   sqlite3SafetyOff(db);
41990   assert( db->init.busy==0 );
41991   db->init.busy = 1;
41992   assert( !db->mallocFailed );
41993   rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
41994   if( rc==SQLITE_ABORT ) rc = initData.rc;
41995   sqlite3_free(zSql);
41996   db->init.busy = 0;
41997   sqlite3SafetyOn(db);
41998   if( rc==SQLITE_NOMEM ){
41999     goto no_mem;
42000   }
42001   break;  
42002 }
42003
42004 #if !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)
42005 /* Opcode: LoadAnalysis P1 * *
42006 **
42007 ** Read the sqlite_stat1 table for database P1 and load the content
42008 ** of that table into the internal index hash table.  This will cause
42009 ** the analysis to be used when preparing all subsequent queries.
42010 */
42011 case OP_LoadAnalysis: {        /* no-push */
42012   int iDb = pOp->p1;
42013   assert( iDb>=0 && iDb<db->nDb );
42014   rc = sqlite3AnalysisLoad(db, iDb);
42015   break;  
42016 }
42017 #endif /* !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)  */
42018
42019 /* Opcode: DropTable P1 * P3
42020 **
42021 ** Remove the internal (in-memory) data structures that describe
42022 ** the table named P3 in database P1.  This is called after a table
42023 ** is dropped in order to keep the internal representation of the
42024 ** schema consistent with what is on disk.
42025 */
42026 case OP_DropTable: {        /* no-push */
42027   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p3);
42028   break;
42029 }
42030
42031 /* Opcode: DropIndex P1 * P3
42032 **
42033 ** Remove the internal (in-memory) data structures that describe
42034 ** the index named P3 in database P1.  This is called after an index
42035 ** is dropped in order to keep the internal representation of the
42036 ** schema consistent with what is on disk.
42037 */
42038 case OP_DropIndex: {        /* no-push */
42039   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p3);
42040   break;
42041 }
42042
42043 /* Opcode: DropTrigger P1 * P3
42044 **
42045 ** Remove the internal (in-memory) data structures that describe
42046 ** the trigger named P3 in database P1.  This is called after a trigger
42047 ** is dropped in order to keep the internal representation of the
42048 ** schema consistent with what is on disk.
42049 */
42050 case OP_DropTrigger: {        /* no-push */
42051   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p3);
42052   break;
42053 }
42054
42055
42056 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
42057 /* Opcode: IntegrityCk P1 P2 *
42058 **
42059 ** Do an analysis of the currently open database.  Push onto the
42060 ** stack the text of an error message describing any problems.
42061 ** If no problems are found, push a NULL onto the stack.
42062 **
42063 ** P1 is the address of a memory cell that contains the maximum
42064 ** number of allowed errors.  At most mem[P1] errors will be reported.
42065 ** In other words, the analysis stops as soon as mem[P1] errors are 
42066 ** seen.  Mem[P1] is updated with the number of errors remaining.
42067 **
42068 ** The root page numbers of all tables in the database are integer
42069 ** values on the stack.  This opcode pulls as many integers as it
42070 ** can off of the stack and uses those numbers as the root pages.
42071 **
42072 ** If P2 is not zero, the check is done on the auxiliary database
42073 ** file, not the main database file.
42074 **
42075 ** This opcode is used to implement the integrity_check pragma.
42076 */
42077 case OP_IntegrityCk: {
42078   int nRoot;
42079   int *aRoot;
42080   int j;
42081   int nErr;
42082   char *z;
42083   Mem *pnErr;
42084
42085   for(nRoot=0; &pTos[-nRoot]>=p->aStack; nRoot++){
42086     if( (pTos[-nRoot].flags & MEM_Int)==0 ) break;
42087   }
42088   assert( nRoot>0 );
42089   aRoot = sqlite3_malloc( sizeof(int)*(nRoot+1) );
42090   if( aRoot==0 ) goto no_mem;
42091   j = pOp->p1;
42092   assert( j>=0 && j<p->nMem );
42093   pnErr = &p->aMem[j];
42094   assert( (pnErr->flags & MEM_Int)!=0 );
42095   for(j=0; j<nRoot; j++){
42096     aRoot[j] = (pTos-j)->u.i;
42097   }
42098   aRoot[j] = 0;
42099   popStack(&pTos, nRoot);
42100   pTos++;
42101   assert( pOp->p2>=0 && pOp->p2<db->nDb );
42102   assert( (p->btreeMask & (1<<pOp->p2))!=0 );
42103   z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p2].pBt, aRoot, nRoot,
42104                                  pnErr->u.i, &nErr);
42105   pnErr->u.i -= nErr;
42106   if( nErr==0 ){
42107     assert( z==0 );
42108     pTos->flags = MEM_Null;
42109   }else{
42110     pTos->z = z;
42111     pTos->n = strlen(z);
42112     pTos->flags = MEM_Str | MEM_Dyn | MEM_Term;
42113     pTos->xDel = 0;
42114   }
42115   pTos->enc = SQLITE_UTF8;
42116   sqlite3VdbeChangeEncoding(pTos, encoding);
42117   sqlite3_free(aRoot);
42118   break;
42119 }
42120 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
42121
42122 /* Opcode: FifoWrite * * *
42123 **
42124 ** Write the integer on the top of the stack
42125 ** into the Fifo.
42126 */
42127 case OP_FifoWrite: {        /* no-push */
42128   assert( pTos>=p->aStack );
42129   sqlite3VdbeMemIntegerify(pTos);
42130   if( sqlite3VdbeFifoPush(&p->sFifo, pTos->u.i)==SQLITE_NOMEM ){
42131     goto no_mem;
42132   }
42133   assert( (pTos->flags & MEM_Dyn)==0 );
42134   pTos--;
42135   break;
42136 }
42137
42138 /* Opcode: FifoRead * P2 *
42139 **
42140 ** Attempt to read a single integer from the Fifo
42141 ** and push it onto the stack.  If the Fifo is empty
42142 ** push nothing but instead jump to P2.
42143 */
42144 case OP_FifoRead: {
42145   i64 v;
42146   CHECK_FOR_INTERRUPT;
42147   if( sqlite3VdbeFifoPop(&p->sFifo, &v)==SQLITE_DONE ){
42148     pc = pOp->p2 - 1;
42149   }else{
42150     pTos++;
42151     pTos->u.i = v;
42152     pTos->flags = MEM_Int;
42153   }
42154   break;
42155 }
42156
42157 #ifndef SQLITE_OMIT_TRIGGER
42158 /* Opcode: ContextPush * * * 
42159 **
42160 ** Save the current Vdbe context such that it can be restored by a ContextPop
42161 ** opcode. The context stores the last insert row id, the last statement change
42162 ** count, and the current statement change count.
42163 */
42164 case OP_ContextPush: {        /* no-push */
42165   int i = p->contextStackTop++;
42166   Context *pContext;
42167
42168   assert( i>=0 );
42169   /* FIX ME: This should be allocated as part of the vdbe at compile-time */
42170   if( i>=p->contextStackDepth ){
42171     p->contextStackDepth = i+1;
42172     p->contextStack = sqlite3DbReallocOrFree(db, p->contextStack,
42173                                           sizeof(Context)*(i+1));
42174     if( p->contextStack==0 ) goto no_mem;
42175   }
42176   pContext = &p->contextStack[i];
42177   pContext->lastRowid = db->lastRowid;
42178   pContext->nChange = p->nChange;
42179   pContext->sFifo = p->sFifo;
42180   sqlite3VdbeFifoInit(&p->sFifo);
42181   break;
42182 }
42183
42184 /* Opcode: ContextPop * * * 
42185 **
42186 ** Restore the Vdbe context to the state it was in when contextPush was last
42187 ** executed. The context stores the last insert row id, the last statement
42188 ** change count, and the current statement change count.
42189 */
42190 case OP_ContextPop: {        /* no-push */
42191   Context *pContext = &p->contextStack[--p->contextStackTop];
42192   assert( p->contextStackTop>=0 );
42193   db->lastRowid = pContext->lastRowid;
42194   p->nChange = pContext->nChange;
42195   sqlite3VdbeFifoClear(&p->sFifo);
42196   p->sFifo = pContext->sFifo;
42197   break;
42198 }
42199 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
42200
42201 /* Opcode: MemStore P1 P2 *
42202 **
42203 ** Write the top of the stack into memory location P1.
42204 ** P1 should be a small integer since space is allocated
42205 ** for all memory locations between 0 and P1 inclusive.
42206 **
42207 ** After the data is stored in the memory location, the
42208 ** stack is popped once if P2 is 1.  If P2 is zero, then
42209 ** the original data remains on the stack.
42210 */
42211 case OP_MemStore: {        /* no-push */
42212   assert( pTos>=p->aStack );
42213   assert( pOp->p1>=0 && pOp->p1<p->nMem );
42214   rc = sqlite3VdbeMemMove(&p->aMem[pOp->p1], pTos);
42215   pTos--;
42216
42217   /* If P2 is 0 then fall thru to the next opcode, OP_MemLoad, that will
42218   ** restore the top of the stack to its original value.
42219   */
42220   if( pOp->p2 ){
42221     break;
42222   }
42223 }
42224 /* Opcode: MemLoad P1 * *
42225 **
42226 ** Push a copy of the value in memory location P1 onto the stack.
42227 **
42228 ** If the value is a string, then the value pushed is a pointer to
42229 ** the string that is stored in the memory location.  If the memory
42230 ** location is subsequently changed (using OP_MemStore) then the
42231 ** value pushed onto the stack will change too.
42232 */
42233 case OP_MemLoad: {
42234   int i = pOp->p1;
42235   assert( i>=0 && i<p->nMem );
42236   pTos++;
42237   sqlite3VdbeMemShallowCopy(pTos, &p->aMem[i], MEM_Ephem);
42238   break;
42239 }
42240
42241 #ifndef SQLITE_OMIT_AUTOINCREMENT
42242 /* Opcode: MemMax P1 * *
42243 **
42244 ** Set the value of memory cell P1 to the maximum of its current value
42245 ** and the value on the top of the stack.  The stack is unchanged.
42246 **
42247 ** This instruction throws an error if the memory cell is not initially
42248 ** an integer.
42249 */
42250 case OP_MemMax: {        /* no-push */
42251   int i = pOp->p1;
42252   Mem *pMem;
42253   assert( pTos>=p->aStack );
42254   assert( i>=0 && i<p->nMem );
42255   pMem = &p->aMem[i];
42256   sqlite3VdbeMemIntegerify(pMem);
42257   sqlite3VdbeMemIntegerify(pTos);
42258   if( pMem->u.i<pTos->u.i){
42259     pMem->u.i = pTos->u.i;
42260   }
42261   break;
42262 }
42263 #endif /* SQLITE_OMIT_AUTOINCREMENT */
42264
42265 /* Opcode: MemIncr P1 P2 *
42266 **
42267 ** Increment the integer valued memory cell P2 by the value in P1.
42268 **
42269 ** It is illegal to use this instruction on a memory cell that does
42270 ** not contain an integer.  An assertion fault will result if you try.
42271 */
42272 case OP_MemIncr: {        /* no-push */
42273   int i = pOp->p2;
42274   Mem *pMem;
42275   assert( i>=0 && i<p->nMem );
42276   pMem = &p->aMem[i];
42277   assert( pMem->flags==MEM_Int );
42278   pMem->u.i += pOp->p1;
42279   break;
42280 }
42281
42282 /* Opcode: IfMemPos P1 P2 *
42283 **
42284 ** If the value of memory cell P1 is 1 or greater, jump to P2.
42285 **
42286 ** It is illegal to use this instruction on a memory cell that does
42287 ** not contain an integer.  An assertion fault will result if you try.
42288 */
42289 case OP_IfMemPos: {        /* no-push */
42290   int i = pOp->p1;
42291   Mem *pMem;
42292   assert( i>=0 && i<p->nMem );
42293   pMem = &p->aMem[i];
42294   assert( pMem->flags==MEM_Int );
42295   if( pMem->u.i>0 ){
42296      pc = pOp->p2 - 1;
42297   }
42298   break;
42299 }
42300
42301 /* Opcode: IfMemNeg P1 P2 *
42302 **
42303 ** If the value of memory cell P1 is less than zero, jump to P2. 
42304 **
42305 ** It is illegal to use this instruction on a memory cell that does
42306 ** not contain an integer.  An assertion fault will result if you try.
42307 */
42308 case OP_IfMemNeg: {        /* no-push */
42309   int i = pOp->p1;
42310   Mem *pMem;
42311   assert( i>=0 && i<p->nMem );
42312   pMem = &p->aMem[i];
42313   assert( pMem->flags==MEM_Int );
42314   if( pMem->u.i<0 ){
42315      pc = pOp->p2 - 1;
42316   }
42317   break;
42318 }
42319
42320 /* Opcode: IfMemZero P1 P2 *
42321 **
42322 ** If the value of memory cell P1 is exactly 0, jump to P2. 
42323 **
42324 ** It is illegal to use this instruction on a memory cell that does
42325 ** not contain an integer.  An assertion fault will result if you try.
42326 */
42327 case OP_IfMemZero: {        /* no-push */
42328   int i = pOp->p1;
42329   Mem *pMem;
42330   assert( i>=0 && i<p->nMem );
42331   pMem = &p->aMem[i];
42332   assert( pMem->flags==MEM_Int );
42333   if( pMem->u.i==0 ){
42334      pc = pOp->p2 - 1;
42335   }
42336   break;
42337 }
42338
42339 /* Opcode: MemNull P1 * *
42340 **
42341 ** Store a NULL in memory cell P1
42342 */
42343 case OP_MemNull: {
42344   assert( pOp->p1>=0 && pOp->p1<p->nMem );
42345   sqlite3VdbeMemSetNull(&p->aMem[pOp->p1]);
42346   break;
42347 }
42348
42349 /* Opcode: MemInt P1 P2 *
42350 **
42351 ** Store the integer value P1 in memory cell P2.
42352 */
42353 case OP_MemInt: {
42354   assert( pOp->p2>=0 && pOp->p2<p->nMem );
42355   sqlite3VdbeMemSetInt64(&p->aMem[pOp->p2], pOp->p1);
42356   break;
42357 }
42358
42359 /* Opcode: MemMove P1 P2 *
42360 **
42361 ** Move the content of memory cell P2 over to memory cell P1.
42362 ** Any prior content of P1 is erased.  Memory cell P2 is left
42363 ** containing a NULL.
42364 */
42365 case OP_MemMove: {
42366   assert( pOp->p1>=0 && pOp->p1<p->nMem );
42367   assert( pOp->p2>=0 && pOp->p2<p->nMem );
42368   rc = sqlite3VdbeMemMove(&p->aMem[pOp->p1], &p->aMem[pOp->p2]);
42369   break;
42370 }
42371
42372 /* Opcode: AggStep P1 P2 P3
42373 **
42374 ** Execute the step function for an aggregate.  The
42375 ** function has P2 arguments.  P3 is a pointer to the FuncDef
42376 ** structure that specifies the function.  Use memory location
42377 ** P1 as the accumulator.
42378 **
42379 ** The P2 arguments are popped from the stack.
42380 */
42381 case OP_AggStep: {        /* no-push */
42382   int n = pOp->p2;
42383   int i;
42384   Mem *pMem, *pRec;
42385   sqlite3_context ctx;
42386   sqlite3_value **apVal;
42387
42388   assert( n>=0 );
42389   pRec = &pTos[1-n];
42390   assert( pRec>=p->aStack );
42391   apVal = p->apArg;
42392   assert( apVal || n==0 );
42393   for(i=0; i<n; i++, pRec++){
42394     apVal[i] = pRec;
42395     storeTypeInfo(pRec, encoding);
42396   }
42397   ctx.pFunc = (FuncDef*)pOp->p3;
42398   assert( pOp->p1>=0 && pOp->p1<p->nMem );
42399   ctx.pMem = pMem = &p->aMem[pOp->p1];
42400   pMem->n++;
42401   ctx.s.flags = MEM_Null;
42402   ctx.s.z = 0;
42403   ctx.s.xDel = 0;
42404   ctx.s.db = db;
42405   ctx.isError = 0;
42406   ctx.pColl = 0;
42407   if( ctx.pFunc->needCollSeq ){
42408     assert( pOp>p->aOp );
42409     assert( pOp[-1].p3type==P3_COLLSEQ );
42410     assert( pOp[-1].opcode==OP_CollSeq );
42411     ctx.pColl = (CollSeq *)pOp[-1].p3;
42412   }
42413   (ctx.pFunc->xStep)(&ctx, n, apVal);
42414   popStack(&pTos, n);
42415   if( ctx.isError ){
42416     sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0);
42417     rc = SQLITE_ERROR;
42418   }
42419   sqlite3VdbeMemRelease(&ctx.s);
42420   break;
42421 }
42422
42423 /* Opcode: AggFinal P1 P2 P3
42424 **
42425 ** Execute the finalizer function for an aggregate.  P1 is
42426 ** the memory location that is the accumulator for the aggregate.
42427 **
42428 ** P2 is the number of arguments that the step function takes and
42429 ** P3 is a pointer to the FuncDef for this function.  The P2
42430 ** argument is not used by this opcode.  It is only there to disambiguate
42431 ** functions that can take varying numbers of arguments.  The
42432 ** P3 argument is only needed for the degenerate case where
42433 ** the step function was not previously called.
42434 */
42435 case OP_AggFinal: {        /* no-push */
42436   Mem *pMem;
42437   assert( pOp->p1>=0 && pOp->p1<p->nMem );
42438   pMem = &p->aMem[pOp->p1];
42439   assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
42440   rc = sqlite3VdbeMemFinalize(pMem, (FuncDef*)pOp->p3);
42441   if( rc==SQLITE_ERROR ){
42442     sqlite3SetString(&p->zErrMsg, sqlite3_value_text(pMem), (char*)0);
42443   }
42444   if( sqlite3VdbeMemTooBig(pMem) ){
42445     goto too_big;
42446   }
42447   break;
42448 }
42449
42450
42451 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
42452 /* Opcode: Vacuum * * *
42453 **
42454 ** Vacuum the entire database.  This opcode will cause other virtual
42455 ** machines to be created and run.  It may not be called from within
42456 ** a transaction.
42457 */
42458 case OP_Vacuum: {        /* no-push */
42459   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; 
42460   rc = sqlite3RunVacuum(&p->zErrMsg, db);
42461   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
42462   break;
42463 }
42464 #endif
42465
42466 #if !defined(SQLITE_OMIT_AUTOVACUUM)
42467 /* Opcode: IncrVacuum P1 P2 *
42468 **
42469 ** Perform a single step of the incremental vacuum procedure on
42470 ** the P1 database. If the vacuum has finished, jump to instruction
42471 ** P2. Otherwise, fall through to the next instruction.
42472 */
42473 case OP_IncrVacuum: {        /* no-push */
42474   Btree *pBt;
42475
42476   assert( pOp->p1>=0 && pOp->p1<db->nDb );
42477   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
42478   pBt = db->aDb[pOp->p1].pBt;
42479   rc = sqlite3BtreeIncrVacuum(pBt);
42480   if( rc==SQLITE_DONE ){
42481     pc = pOp->p2 - 1;
42482     rc = SQLITE_OK;
42483   }
42484   break;
42485 }
42486 #endif
42487
42488 /* Opcode: Expire P1 * *
42489 **
42490 ** Cause precompiled statements to become expired. An expired statement
42491 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
42492 ** (via sqlite3_step()).
42493 ** 
42494 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
42495 ** then only the currently executing statement is affected. 
42496 */
42497 case OP_Expire: {        /* no-push */
42498   if( !pOp->p1 ){
42499     sqlite3ExpirePreparedStatements(db);
42500   }else{
42501     p->expired = 1;
42502   }
42503   break;
42504 }
42505
42506 #ifndef SQLITE_OMIT_SHARED_CACHE
42507 /* Opcode: TableLock P1 P2 P3
42508 **
42509 ** Obtain a lock on a particular table. This instruction is only used when
42510 ** the shared-cache feature is enabled. 
42511 **
42512 ** If P1 is not negative, then it is the index of the database
42513 ** in sqlite3.aDb[] and a read-lock is required. If P1 is negative, a 
42514 ** write-lock is required. In this case the index of the database is the 
42515 ** absolute value of P1 minus one (iDb = abs(P1) - 1;) and a write-lock is
42516 ** required. 
42517 **
42518 ** P2 contains the root-page of the table to lock.
42519 **
42520 ** P3 contains a pointer to the name of the table being locked. This is only
42521 ** used to generate an error message if the lock cannot be obtained.
42522 */
42523 case OP_TableLock: {        /* no-push */
42524   int p1 = pOp->p1; 
42525   u8 isWriteLock = (p1<0);
42526   if( isWriteLock ){
42527     p1 = (-1*p1)-1;
42528   }
42529   assert( p1>=0 && p1<db->nDb );
42530   assert( (p->btreeMask & (1<<p1))!=0 );
42531   rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
42532   if( rc==SQLITE_LOCKED ){
42533     const char *z = (const char *)pOp->p3;
42534     sqlite3SetString(&p->zErrMsg, "database table is locked: ", z, (char*)0);
42535   }
42536   break;
42537 }
42538 #endif /* SQLITE_OMIT_SHARED_CACHE */
42539
42540 #ifndef SQLITE_OMIT_VIRTUALTABLE
42541 /* Opcode: VBegin * * P3
42542 **
42543 ** P3 a pointer to an sqlite3_vtab structure. Call the xBegin method 
42544 ** for that table.
42545 */
42546 case OP_VBegin: {   /* no-push */
42547   rc = sqlite3VtabBegin(db, (sqlite3_vtab *)pOp->p3);
42548   break;
42549 }
42550 #endif /* SQLITE_OMIT_VIRTUALTABLE */
42551
42552 #ifndef SQLITE_OMIT_VIRTUALTABLE
42553 /* Opcode: VCreate P1 * P3
42554 **
42555 ** P3 is the name of a virtual table in database P1. Call the xCreate method
42556 ** for that table.
42557 */
42558 case OP_VCreate: {   /* no-push */
42559   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p3, &p->zErrMsg);
42560   break;
42561 }
42562 #endif /* SQLITE_OMIT_VIRTUALTABLE */
42563
42564 #ifndef SQLITE_OMIT_VIRTUALTABLE
42565 /* Opcode: VDestroy P1 * P3
42566 **
42567 ** P3 is the name of a virtual table in database P1.  Call the xDestroy method
42568 ** of that table.
42569 */
42570 case OP_VDestroy: {   /* no-push */
42571   p->inVtabMethod = 2;
42572   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p3);
42573   p->inVtabMethod = 0;
42574   break;
42575 }
42576 #endif /* SQLITE_OMIT_VIRTUALTABLE */
42577
42578 #ifndef SQLITE_OMIT_VIRTUALTABLE
42579 /* Opcode: VOpen P1 * P3
42580 **
42581 ** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
42582 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
42583 ** table and stores that cursor in P1.
42584 */
42585 case OP_VOpen: {   /* no-push */
42586   Cursor *pCur = 0;
42587   sqlite3_vtab_cursor *pVtabCursor = 0;
42588
42589   sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3);
42590   sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
42591
42592   assert(pVtab && pModule);
42593   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
42594   rc = pModule->xOpen(pVtab, &pVtabCursor);
42595   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
42596   if( SQLITE_OK==rc ){
42597     /* Initialise sqlite3_vtab_cursor base class */
42598     pVtabCursor->pVtab = pVtab;
42599
42600     /* Initialise vdbe cursor object */
42601     pCur = allocateCursor(p, pOp->p1, -1);
42602     if( pCur ){
42603       pCur->pVtabCursor = pVtabCursor;
42604       pCur->pModule = pVtabCursor->pVtab->pModule;
42605     }else{
42606       db->mallocFailed = 1;
42607       pModule->xClose(pVtabCursor);
42608     }
42609   }
42610   break;
42611 }
42612 #endif /* SQLITE_OMIT_VIRTUALTABLE */
42613
42614 #ifndef SQLITE_OMIT_VIRTUALTABLE
42615 /* Opcode: VFilter P1 P2 P3
42616 **
42617 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
42618 ** the filtered result set is empty.
42619 **
42620 ** P3 is either NULL or a string that was generated by the xBestIndex
42621 ** method of the module.  The interpretation of the P3 string is left
42622 ** to the module implementation.
42623 **
42624 ** This opcode invokes the xFilter method on the virtual table specified
42625 ** by P1.  The integer query plan parameter to xFilter is the top of the
42626 ** stack.  Next down on the stack is the argc parameter.  Beneath the
42627 ** next of stack are argc additional parameters which are passed to
42628 ** xFilter as argv. The topmost parameter (i.e. 3rd element popped from
42629 ** the stack) becomes argv[argc-1] when passed to xFilter.
42630 **
42631 ** The integer query plan parameter, argc, and all argv stack values 
42632 ** are popped from the stack before this instruction completes.
42633 **
42634 ** A jump is made to P2 if the result set after filtering would be 
42635 ** empty.
42636 */
42637 case OP_VFilter: {   /* no-push */
42638   int nArg;
42639
42640   const sqlite3_module *pModule;
42641
42642   Cursor *pCur = p->apCsr[pOp->p1];
42643   assert( pCur->pVtabCursor );
42644   pModule = pCur->pVtabCursor->pVtab->pModule;
42645
42646   /* Grab the index number and argc parameters off the top of the stack. */
42647   assert( (&pTos[-1])>=p->aStack );
42648   assert( (pTos[0].flags&MEM_Int)!=0 && pTos[-1].flags==MEM_Int );
42649   nArg = pTos[-1].u.i;
42650
42651   /* Invoke the xFilter method */
42652   {
42653     int res = 0;
42654     int i;
42655     Mem **apArg = p->apArg;
42656     for(i = 0; i<nArg; i++){
42657       apArg[i] = &pTos[i+1-2-nArg];
42658       storeTypeInfo(apArg[i], 0);
42659     }
42660
42661     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
42662     p->inVtabMethod = 1;
42663     rc = pModule->xFilter(pCur->pVtabCursor, pTos->u.i, pOp->p3, nArg, apArg);
42664     p->inVtabMethod = 0;
42665     if( rc==SQLITE_OK ){
42666       res = pModule->xEof(pCur->pVtabCursor);
42667     }
42668     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
42669
42670     if( res ){
42671       pc = pOp->p2 - 1;
42672     }
42673   }
42674
42675   /* Pop the index number, argc value and parameters off the stack */
42676   popStack(&pTos, 2+nArg);
42677   break;
42678 }
42679 #endif /* SQLITE_OMIT_VIRTUALTABLE */
42680
42681 #ifndef SQLITE_OMIT_VIRTUALTABLE
42682 /* Opcode: VRowid P1 * *
42683 **
42684 ** Push an integer onto the stack which is the rowid of
42685 ** the virtual-table that the P1 cursor is pointing to.
42686 */
42687 case OP_VRowid: {
42688   const sqlite3_module *pModule;
42689
42690   Cursor *pCur = p->apCsr[pOp->p1];
42691   assert( pCur->pVtabCursor );
42692   pModule = pCur->pVtabCursor->pVtab->pModule;
42693   if( pModule->xRowid==0 ){
42694     sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xRowid", 0);
42695     rc = SQLITE_ERROR;
42696   } else {
42697     sqlite_int64 iRow;
42698
42699     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
42700     rc = pModule->xRowid(pCur->pVtabCursor, &iRow);
42701     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
42702
42703     pTos++;
42704     pTos->flags = MEM_Int;
42705     pTos->u.i = iRow;
42706   }
42707
42708   break;
42709 }
42710 #endif /* SQLITE_OMIT_VIRTUALTABLE */
42711
42712 #ifndef SQLITE_OMIT_VIRTUALTABLE
42713 /* Opcode: VColumn P1 P2 *
42714 **
42715 ** Push onto the stack the value of the P2-th column of
42716 ** the row of the virtual-table that the P1 cursor is pointing to.
42717 */
42718 case OP_VColumn: {
42719   const sqlite3_module *pModule;
42720
42721   Cursor *pCur = p->apCsr[pOp->p1];
42722   assert( pCur->pVtabCursor );
42723   pModule = pCur->pVtabCursor->pVtab->pModule;
42724   if( pModule->xColumn==0 ){
42725     sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xColumn", 0);
42726     rc = SQLITE_ERROR;
42727   } else {
42728     sqlite3_context sContext;
42729     memset(&sContext, 0, sizeof(sContext));
42730     sContext.s.flags = MEM_Null;
42731     sContext.s.db = db;
42732     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
42733     rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
42734
42735     /* Copy the result of the function to the top of the stack. We
42736     ** do this regardless of whether or not an error occured to ensure any
42737     ** dynamic allocation in sContext.s (a Mem struct) is  released.
42738     */
42739     sqlite3VdbeChangeEncoding(&sContext.s, encoding);
42740     pTos++;
42741     pTos->flags = 0;
42742     sqlite3VdbeMemMove(pTos, &sContext.s);
42743
42744     if( sqlite3SafetyOn(db) ){
42745       goto abort_due_to_misuse;
42746     }
42747     if( sqlite3VdbeMemTooBig(pTos) ){
42748       goto too_big;
42749     }
42750   }
42751   
42752   break;
42753 }
42754 #endif /* SQLITE_OMIT_VIRTUALTABLE */
42755
42756 #ifndef SQLITE_OMIT_VIRTUALTABLE
42757 /* Opcode: VNext P1 P2 *
42758 **
42759 ** Advance virtual table P1 to the next row in its result set and
42760 ** jump to instruction P2.  Or, if the virtual table has reached
42761 ** the end of its result set, then fall through to the next instruction.
42762 */
42763 case OP_VNext: {   /* no-push */
42764   const sqlite3_module *pModule;
42765   int res = 0;
42766
42767   Cursor *pCur = p->apCsr[pOp->p1];
42768   assert( pCur->pVtabCursor );
42769   pModule = pCur->pVtabCursor->pVtab->pModule;
42770   if( pModule->xNext==0 ){
42771     sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xNext", 0);
42772     rc = SQLITE_ERROR;
42773   } else {
42774     /* Invoke the xNext() method of the module. There is no way for the
42775     ** underlying implementation to return an error if one occurs during
42776     ** xNext(). Instead, if an error occurs, true is returned (indicating that 
42777     ** data is available) and the error code returned when xColumn or
42778     ** some other method is next invoked on the save virtual table cursor.
42779     */
42780     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
42781     p->inVtabMethod = 1;
42782     rc = pModule->xNext(pCur->pVtabCursor);
42783     p->inVtabMethod = 0;
42784     if( rc==SQLITE_OK ){
42785       res = pModule->xEof(pCur->pVtabCursor);
42786     }
42787     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
42788
42789     if( !res ){
42790       /* If there is data, jump to P2 */
42791       pc = pOp->p2 - 1;
42792     }
42793   }
42794
42795   break;
42796 }
42797 #endif /* SQLITE_OMIT_VIRTUALTABLE */
42798
42799 #ifndef SQLITE_OMIT_VIRTUALTABLE
42800 /* Opcode: VRename * * P3
42801 **
42802 ** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
42803 ** This opcode invokes the corresponding xRename method. The value
42804 ** on the top of the stack is popped and passed as the zName argument
42805 ** to the xRename method.
42806 */
42807 case OP_VRename: {   /* no-push */
42808   sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3);
42809   assert( pVtab->pModule->xRename );
42810
42811   Stringify(pTos, encoding);
42812
42813   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
42814   sqlite3VtabLock(pVtab);
42815   rc = pVtab->pModule->xRename(pVtab, pTos->z);
42816   sqlite3VtabUnlock(db, pVtab);
42817   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
42818
42819   popStack(&pTos, 1);
42820   break;
42821 }
42822 #endif
42823
42824 #ifndef SQLITE_OMIT_VIRTUALTABLE
42825 /* Opcode: VUpdate P1 P2 P3
42826 **
42827 ** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
42828 ** This opcode invokes the corresponding xUpdate method. P2 values
42829 ** are taken from the stack to pass to the xUpdate invocation. The
42830 ** value on the top of the stack corresponds to the p2th element 
42831 ** of the argv array passed to xUpdate.
42832 **
42833 ** The xUpdate method will do a DELETE or an INSERT or both.
42834 ** The argv[0] element (which corresponds to the P2-th element down
42835 ** on the stack) is the rowid of a row to delete.  If argv[0] is
42836 ** NULL then no deletion occurs.  The argv[1] element is the rowid
42837 ** of the new row.  This can be NULL to have the virtual table
42838 ** select the new rowid for itself.  The higher elements in the
42839 ** stack are the values of columns in the new row.
42840 **
42841 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
42842 ** a row to delete.
42843 **
42844 ** P1 is a boolean flag. If it is set to true and the xUpdate call
42845 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
42846 ** is set to the value of the rowid for the row just inserted.
42847 */
42848 case OP_VUpdate: {   /* no-push */
42849   sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3);
42850   sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
42851   int nArg = pOp->p2;
42852   assert( pOp->p3type==P3_VTAB );
42853   if( pModule->xUpdate==0 ){
42854     sqlite3SetString(&p->zErrMsg, "read-only table", 0);
42855     rc = SQLITE_ERROR;
42856   }else{
42857     int i;
42858     sqlite_int64 rowid;
42859     Mem **apArg = p->apArg;
42860     Mem *pX = &pTos[1-nArg];
42861     for(i = 0; i<nArg; i++, pX++){
42862       storeTypeInfo(pX, 0);
42863       apArg[i] = pX;
42864     }
42865     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
42866     sqlite3VtabLock(pVtab);
42867     rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
42868     sqlite3VtabUnlock(db, pVtab);
42869     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
42870     if( pOp->p1 && rc==SQLITE_OK ){
42871       assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
42872       db->lastRowid = rowid;
42873     }
42874   }
42875   popStack(&pTos, nArg);
42876   break;
42877 }
42878 #endif /* SQLITE_OMIT_VIRTUALTABLE */
42879
42880 /* An other opcode is illegal...
42881 */
42882 default: {
42883   assert( 0 );
42884   break;
42885 }
42886
42887 /*****************************************************************************
42888 ** The cases of the switch statement above this line should all be indented
42889 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
42890 ** readability.  From this point on down, the normal indentation rules are
42891 ** restored.
42892 *****************************************************************************/
42893     }
42894
42895     /* Make sure the stack limit was not exceeded */
42896     assert( pTos<=pStackLimit );
42897
42898 #ifdef VDBE_PROFILE
42899     {
42900       long long elapse = hwtime() - start;
42901       pOp->cycles += elapse;
42902       pOp->cnt++;
42903 #if 0
42904         fprintf(stdout, "%10lld ", elapse);
42905         sqlite3VdbePrintOp(stdout, origPc, &p->aOp[origPc]);
42906 #endif
42907     }
42908 #endif
42909
42910 #ifdef SQLITE_TEST
42911     /* Keep track of the size of the largest BLOB or STR that has appeared
42912     ** on the top of the VDBE stack.
42913     */
42914     if( pTos>=p->aStack && (pTos->flags & (MEM_Blob|MEM_Str))!=0
42915          && pTos->n>sqlite3_max_blobsize ){
42916       sqlite3_max_blobsize = pTos->n;
42917     }
42918 #endif
42919
42920     /* The following code adds nothing to the actual functionality
42921     ** of the program.  It is only here for testing and debugging.
42922     ** On the other hand, it does burn CPU cycles every time through
42923     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
42924     */
42925 #ifndef NDEBUG
42926     /* Sanity checking on the top element of the stack. If the previous
42927     ** instruction was VNoChange, then the flags field of the top
42928     ** of the stack is set to 0. This is technically invalid for a memory
42929     ** cell, so avoid calling MemSanity() in this case.
42930     */
42931     if( pTos>=p->aStack && pTos->flags ){
42932       assert( pTos->db==db );
42933       sqlite3VdbeMemSanity(pTos);
42934       assert( !sqlite3VdbeMemTooBig(pTos) );
42935     }
42936     assert( pc>=-1 && pc<p->nOp );
42937
42938 #ifdef SQLITE_DEBUG
42939     /* Code for tracing the vdbe stack. */
42940     if( p->trace && pTos>=p->aStack ){
42941       int i;
42942       fprintf(p->trace, "Stack:");
42943       for(i=0; i>-5 && &pTos[i]>=p->aStack; i--){
42944         if( pTos[i].flags & MEM_Null ){
42945           fprintf(p->trace, " NULL");
42946         }else if( (pTos[i].flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
42947           fprintf(p->trace, " si:%lld", pTos[i].u.i);
42948         }else if( pTos[i].flags & MEM_Int ){
42949           fprintf(p->trace, " i:%lld", pTos[i].u.i);
42950         }else if( pTos[i].flags & MEM_Real ){
42951           fprintf(p->trace, " r:%g", pTos[i].r);
42952         }else{
42953           char zBuf[200];
42954           sqlite3VdbeMemPrettyPrint(&pTos[i], zBuf);
42955           fprintf(p->trace, " ");
42956           fprintf(p->trace, "%s", zBuf);
42957         }
42958       }
42959       if( rc!=0 ) fprintf(p->trace," rc=%d",rc);
42960       fprintf(p->trace,"\n");
42961     }
42962 #endif  /* SQLITE_DEBUG */
42963 #endif  /* NDEBUG */
42964   }  /* The end of the for(;;) loop the loops through opcodes */
42965
42966   /* If we reach this point, it means that execution is finished.
42967   */
42968 vdbe_halt:
42969   if( rc ){
42970     p->rc = rc;
42971     rc = SQLITE_ERROR;
42972   }else{
42973     rc = SQLITE_DONE;
42974   }
42975   sqlite3VdbeHalt(p);
42976   p->pTos = pTos;
42977
42978   /* This is the only way out of this procedure.  We have to
42979   ** release the mutexes on btrees that were acquired at the
42980   ** top. */
42981 vdbe_return:
42982   sqlite3BtreeMutexArrayLeave(&p->aMutex);
42983   return rc;
42984
42985   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
42986   ** is encountered.
42987   */
42988 too_big:
42989   sqlite3SetString(&p->zErrMsg, "string or blob too big", (char*)0);
42990   rc = SQLITE_TOOBIG;
42991   goto vdbe_halt;
42992
42993   /* Jump to here if a malloc() fails.
42994   */
42995 no_mem:
42996   db->mallocFailed = 1;
42997   sqlite3SetString(&p->zErrMsg, "out of memory", (char*)0);
42998   rc = SQLITE_NOMEM;
42999   goto vdbe_halt;
43000
43001   /* Jump to here for an SQLITE_MISUSE error.
43002   */
43003 abort_due_to_misuse:
43004   rc = SQLITE_MISUSE;
43005   /* Fall thru into abort_due_to_error */
43006
43007   /* Jump to here for any other kind of fatal error.  The "rc" variable
43008   ** should hold the error number.
43009   */
43010 abort_due_to_error:
43011   if( p->zErrMsg==0 ){
43012     if( db->mallocFailed ) rc = SQLITE_NOMEM;
43013     sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
43014   }
43015   goto vdbe_halt;
43016
43017   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
43018   ** flag.
43019   */
43020 abort_due_to_interrupt:
43021   assert( db->u1.isInterrupted );
43022   if( db->magic!=SQLITE_MAGIC_BUSY ){
43023     rc = SQLITE_MISUSE;
43024   }else{
43025     rc = SQLITE_INTERRUPT;
43026   }
43027   p->rc = rc;
43028   sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
43029   goto vdbe_halt;
43030 }
43031
43032 /************** End of vdbe.c ************************************************/
43033 /************** Begin file vdbeblob.c ****************************************/
43034 /*
43035 ** 2007 May 1
43036 **
43037 ** The author disclaims copyright to this source code.  In place of
43038 ** a legal notice, here is a blessing:
43039 **
43040 **    May you do good and not evil.
43041 **    May you find forgiveness for yourself and forgive others.
43042 **    May you share freely, never taking more than you give.
43043 **
43044 *************************************************************************
43045 **
43046 ** This file contains code used to implement incremental BLOB I/O.
43047 **
43048 ** $Id: vdbeblob.c,v 1.16 2007/08/30 01:19:59 drh Exp $
43049 */
43050
43051
43052 #ifndef SQLITE_OMIT_INCRBLOB
43053
43054 /*
43055 ** Valid sqlite3_blob* handles point to Incrblob structures.
43056 */
43057 typedef struct Incrblob Incrblob;
43058 struct Incrblob {
43059   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
43060   int nByte;              /* Size of open blob, in bytes */
43061   int iOffset;            /* Byte offset of blob in cursor data */
43062   BtCursor *pCsr;         /* Cursor pointing at blob row */
43063   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
43064   sqlite3 *db;            /* The associated database */
43065 };
43066
43067 /*
43068 ** Open a blob handle.
43069 */
43070 SQLITE_API int sqlite3_blob_open(
43071   sqlite3* db,            /* The database connection */
43072   const char *zDb,        /* The attached database containing the blob */
43073   const char *zTable,     /* The table containing the blob */
43074   const char *zColumn,    /* The column containing the blob */
43075   sqlite_int64 iRow,      /* The row containing the glob */
43076   int flags,              /* True -> read/write access, false -> read-only */
43077   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
43078 ){
43079   int nAttempt = 0;
43080   int iCol;               /* Index of zColumn in row-record */
43081
43082   /* This VDBE program seeks a btree cursor to the identified 
43083   ** db/table/row entry. The reason for using a vdbe program instead
43084   ** of writing code to use the b-tree layer directly is that the
43085   ** vdbe program will take advantage of the various transaction,
43086   ** locking and error handling infrastructure built into the vdbe.
43087   **
43088   ** After seeking the cursor, the vdbe executes an OP_Callback.
43089   ** Code external to the Vdbe then "borrows" the b-tree cursor and
43090   ** uses it to implement the blob_read(), blob_write() and 
43091   ** blob_bytes() functions.
43092   **
43093   ** The sqlite3_blob_close() function finalizes the vdbe program,
43094   ** which closes the b-tree cursor and (possibly) commits the 
43095   ** transaction.
43096   */
43097   static const VdbeOpList openBlob[] = {
43098     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
43099     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
43100     {OP_Integer, 0, 0, 0},         /* 2: Database number */
43101
43102     /* One of the following two instructions is replaced by an
43103     ** OP_Noop before exection.
43104     */
43105     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
43106     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
43107     {OP_SetNumColumns, 0, 0, 0},   /* 5: Num cols for cursor */
43108
43109     {OP_Variable, 1, 0, 0},        /* 6: Push the rowid to the stack */
43110     {OP_NotExists, 0, 10, 0},      /* 7: Seek the cursor */
43111     {OP_Column, 0, 0, 0},          /* 8  */
43112     {OP_Callback, 0, 0, 0},        /* 9  */
43113     {OP_Close, 0, 0, 0},           /* 10 */
43114     {OP_Halt, 0, 0, 0},            /* 11 */
43115   };
43116
43117   Vdbe *v = 0;
43118   int rc = SQLITE_OK;
43119   char zErr[128];
43120
43121   zErr[0] = 0;
43122   sqlite3_mutex_enter(db->mutex);
43123   do {
43124     Parse sParse;
43125     Table *pTab;
43126
43127     memset(&sParse, 0, sizeof(Parse));
43128     sParse.db = db;
43129
43130     rc = sqlite3SafetyOn(db);
43131     if( rc!=SQLITE_OK ){
43132       sqlite3_mutex_leave(db->mutex);
43133       return rc;
43134     }
43135
43136     sqlite3BtreeEnterAll(db);
43137     pTab = sqlite3LocateTable(&sParse, zTable, zDb);
43138     if( !pTab ){
43139       if( sParse.zErrMsg ){
43140         sqlite3_snprintf(sizeof(zErr), zErr, "%s", sParse.zErrMsg);
43141       }
43142       sqlite3_free(sParse.zErrMsg);
43143       rc = SQLITE_ERROR;
43144       sqlite3SafetyOff(db);
43145       sqlite3BtreeLeaveAll(db);
43146       goto blob_open_out;
43147     }
43148
43149     /* Now search pTab for the exact column. */
43150     for(iCol=0; iCol < pTab->nCol; iCol++) {
43151       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
43152         break;
43153       }
43154     }
43155     if( iCol==pTab->nCol ){
43156       sqlite3_snprintf(sizeof(zErr), zErr, "no such column: \"%s\"", zColumn);
43157       rc = SQLITE_ERROR;
43158       sqlite3SafetyOff(db);
43159       sqlite3BtreeLeaveAll(db);
43160       goto blob_open_out;
43161     }
43162
43163     /* If the value is being opened for writing, check that the
43164     ** column is not indexed. It is against the rules to open an
43165     ** indexed column for writing.
43166     */
43167     if( flags ){
43168       Index *pIdx;
43169       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
43170         int j;
43171         for(j=0; j<pIdx->nColumn; j++){
43172           if( pIdx->aiColumn[j]==iCol ){
43173             sqlite3_snprintf(sizeof(zErr), zErr,
43174                              "cannot open indexed column for writing");
43175             rc = SQLITE_ERROR;
43176             sqlite3SafetyOff(db);
43177             sqlite3BtreeLeaveAll(db);
43178             goto blob_open_out;
43179           }
43180         }
43181       }
43182     }
43183
43184     v = sqlite3VdbeCreate(db);
43185     if( v ){
43186       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
43187       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
43188
43189       /* Configure the OP_Transaction */
43190       sqlite3VdbeChangeP1(v, 0, iDb);
43191       sqlite3VdbeChangeP2(v, 0, (flags ? 1 : 0));
43192
43193       /* Configure the OP_VerifyCookie */
43194       sqlite3VdbeChangeP1(v, 1, iDb);
43195       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
43196
43197       /* Make sure a mutex is held on the table to be accessed */
43198       sqlite3VdbeUsesBtree(v, iDb); 
43199
43200       /* Configure the db number pushed onto the stack */
43201       sqlite3VdbeChangeP1(v, 2, iDb);
43202
43203       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
43204       ** parameter of the other to pTab->tnum. 
43205       */
43206       sqlite3VdbeChangeToNoop(v, (flags ? 3 : 4), 1);
43207       sqlite3VdbeChangeP2(v, (flags ? 4 : 3), pTab->tnum);
43208
43209       /* Configure the OP_SetNumColumns. Configure the cursor to
43210       ** think that the table has one more column than it really
43211       ** does. An OP_Column to retrieve this imaginary column will
43212       ** always return an SQL NULL. This is useful because it means
43213       ** we can invoke OP_Column to fill in the vdbe cursors type 
43214       ** and offset cache without causing any IO.
43215       */
43216       sqlite3VdbeChangeP2(v, 5, pTab->nCol+1);
43217       if( !db->mallocFailed ){
43218         sqlite3VdbeMakeReady(v, 1, 0, 1, 0);
43219       }
43220     }
43221    
43222     sqlite3BtreeLeaveAll(db);
43223     rc = sqlite3SafetyOff(db);
43224     if( rc!=SQLITE_OK || db->mallocFailed ){
43225       goto blob_open_out;
43226     }
43227
43228     sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
43229     rc = sqlite3_step((sqlite3_stmt *)v);
43230     if( rc!=SQLITE_ROW ){
43231       nAttempt++;
43232       rc = sqlite3_finalize((sqlite3_stmt *)v);
43233       sqlite3_snprintf(sizeof(zErr), zErr, sqlite3_errmsg(db));
43234       v = 0;
43235     }
43236   } while( nAttempt<5 && rc==SQLITE_SCHEMA );
43237
43238   if( rc==SQLITE_ROW ){
43239     /* The row-record has been opened successfully. Check that the
43240     ** column in question contains text or a blob. If it contains
43241     ** text, it is up to the caller to get the encoding right.
43242     */
43243     Incrblob *pBlob;
43244     u32 type = v->apCsr[0]->aType[iCol];
43245
43246     if( type<12 ){
43247       sqlite3_snprintf(sizeof(zErr), zErr, "cannot open value of type %s",
43248           type==0?"null": type==7?"real": "integer"
43249       );
43250       rc = SQLITE_ERROR;
43251       goto blob_open_out;
43252     }
43253     pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
43254     if( db->mallocFailed ){
43255       sqlite3_free(pBlob);
43256       goto blob_open_out;
43257     }
43258     pBlob->flags = flags;
43259     pBlob->pCsr =  v->apCsr[0]->pCursor;
43260     sqlite3BtreeEnterCursor(pBlob->pCsr);
43261     sqlite3BtreeCacheOverflow(pBlob->pCsr);
43262     sqlite3BtreeLeaveCursor(pBlob->pCsr);
43263     pBlob->pStmt = (sqlite3_stmt *)v;
43264     pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
43265     pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
43266     pBlob->db = db;
43267     *ppBlob = (sqlite3_blob *)pBlob;
43268     rc = SQLITE_OK;
43269   }else if( rc==SQLITE_OK ){
43270     sqlite3_snprintf(sizeof(zErr), zErr, "no such rowid: %lld", iRow);
43271     rc = SQLITE_ERROR;
43272   }
43273
43274 blob_open_out:
43275   zErr[sizeof(zErr)-1] = '\0';
43276   if( rc!=SQLITE_OK || db->mallocFailed ){
43277     sqlite3_finalize((sqlite3_stmt *)v);
43278   }
43279   sqlite3Error(db, rc, (rc==SQLITE_OK?0:zErr));
43280   rc = sqlite3ApiExit(db, rc);
43281   sqlite3_mutex_leave(db->mutex);
43282   return rc;
43283 }
43284
43285 /*
43286 ** Close a blob handle that was previously created using
43287 ** sqlite3_blob_open().
43288 */
43289 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
43290   Incrblob *p = (Incrblob *)pBlob;
43291   int rc;
43292
43293   rc = sqlite3_finalize(p->pStmt);
43294   sqlite3_free(p);
43295   return rc;
43296 }
43297
43298 /*
43299 ** Perform a read or write operation on a blob
43300 */
43301 static int blobReadWrite(
43302   sqlite3_blob *pBlob, 
43303   void *z, 
43304   int n, 
43305   int iOffset, 
43306   int (*xCall)(BtCursor*, u32, u32, void*)
43307 ){
43308   int rc;
43309   Incrblob *p = (Incrblob *)pBlob;
43310   Vdbe *v;
43311   sqlite3 *db = p->db;  
43312
43313   /* Request is out of range. Return a transient error. */
43314   if( (iOffset+n)>p->nByte ){
43315     return SQLITE_ERROR;
43316   }
43317   sqlite3_mutex_enter(db->mutex);
43318
43319   /* If there is no statement handle, then the blob-handle has
43320   ** already been invalidated. Return SQLITE_ABORT in this case.
43321   */
43322   v = (Vdbe*)p->pStmt;
43323   if( v==0 ){
43324     rc = SQLITE_ABORT;
43325   }else{
43326     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
43327     ** returned, clean-up the statement handle.
43328     */
43329     assert( db == v->db );
43330     sqlite3BtreeEnterCursor(p->pCsr);
43331     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
43332     sqlite3BtreeLeaveCursor(p->pCsr);
43333     if( rc==SQLITE_ABORT ){
43334       sqlite3VdbeFinalize(v);
43335       p->pStmt = 0;
43336     }else{
43337       db->errCode = rc;
43338       v->rc = rc;
43339     }
43340   }
43341   rc = sqlite3ApiExit(db, rc);
43342   sqlite3_mutex_leave(db->mutex);
43343   return rc;
43344 }
43345
43346 /*
43347 ** Read data from a blob handle.
43348 */
43349 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
43350   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
43351 }
43352
43353 /*
43354 ** Write data to a blob handle.
43355 */
43356 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
43357   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
43358 }
43359
43360 /*
43361 ** Query a blob handle for the size of the data.
43362 **
43363 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
43364 ** so no mutex is required for access.
43365 */
43366 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
43367   Incrblob *p = (Incrblob *)pBlob;
43368   return p->nByte;
43369 }
43370
43371 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
43372
43373 /************** End of vdbeblob.c ********************************************/
43374 /************** Begin file journal.c *****************************************/
43375 /*
43376 ** 2007 August 22
43377 **
43378 ** The author disclaims copyright to this source code.  In place of
43379 ** a legal notice, here is a blessing:
43380 **
43381 **    May you do good and not evil.
43382 **    May you find forgiveness for yourself and forgive others.
43383 **    May you share freely, never taking more than you give.
43384 **
43385 *************************************************************************
43386 **
43387 ** @(#) $Id: journal.c,v 1.7 2007/09/06 13:49:37 drh Exp $
43388 */
43389
43390 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
43391
43392 /*
43393 ** This file implements a special kind of sqlite3_file object used
43394 ** by SQLite to create journal files if the atomic-write optimization
43395 ** is enabled.
43396 **
43397 ** The distinctive characteristic of this sqlite3_file is that the
43398 ** actual on disk file is created lazily. When the file is created,
43399 ** the caller specifies a buffer size for an in-memory buffer to
43400 ** be used to service read() and write() requests. The actual file
43401 ** on disk is not created or populated until either:
43402 **
43403 **   1) The in-memory representation grows too large for the allocated 
43404 **      buffer, or
43405 **   2) The xSync() method is called.
43406 */
43407
43408
43409
43410 /*
43411 ** A JournalFile object is a subclass of sqlite3_file used by
43412 ** as an open file handle for journal files.
43413 */
43414 struct JournalFile {
43415   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
43416   int nBuf;                       /* Size of zBuf[] in bytes */
43417   char *zBuf;                     /* Space to buffer journal writes */
43418   int iSize;                      /* Amount of zBuf[] currently used */
43419   int flags;                      /* xOpen flags */
43420   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
43421   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
43422   const char *zJournal;           /* Name of the journal file */
43423 };
43424 typedef struct JournalFile JournalFile;
43425
43426 /*
43427 ** If it does not already exists, create and populate the on-disk file 
43428 ** for JournalFile p.
43429 */
43430 static int createFile(JournalFile *p){
43431   int rc = SQLITE_OK;
43432   if( !p->pReal ){
43433     sqlite3_file *pReal = (sqlite3_file *)&p[1];
43434     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
43435     if( rc==SQLITE_OK ){
43436       p->pReal = pReal;
43437       if( p->iSize>0 ){
43438         assert(p->iSize<=p->nBuf);
43439         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
43440       }
43441     }
43442   }
43443   return rc;
43444 }
43445
43446 /*
43447 ** Close the file.
43448 */
43449 static int jrnlClose(sqlite3_file *pJfd){
43450   JournalFile *p = (JournalFile *)pJfd;
43451   if( p->pReal ){
43452     sqlite3OsClose(p->pReal);
43453   }
43454   sqlite3_free(p->zBuf);
43455   return SQLITE_OK;
43456 }
43457
43458 /*
43459 ** Read data from the file.
43460 */
43461 static int jrnlRead(
43462   sqlite3_file *pJfd,    /* The journal file from which to read */
43463   void *zBuf,            /* Put the results here */
43464   int iAmt,              /* Number of bytes to read */
43465   sqlite_int64 iOfst     /* Begin reading at this offset */
43466 ){
43467   int rc = SQLITE_OK;
43468   JournalFile *p = (JournalFile *)pJfd;
43469   if( p->pReal ){
43470     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
43471   }else{
43472     assert( iAmt+iOfst<=p->iSize );
43473     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
43474   }
43475   return rc;
43476 }
43477
43478 /*
43479 ** Write data to the file.
43480 */
43481 static int jrnlWrite(
43482   sqlite3_file *pJfd,    /* The journal file into which to write */
43483   const void *zBuf,      /* Take data to be written from here */
43484   int iAmt,              /* Number of bytes to write */
43485   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
43486 ){
43487   int rc = SQLITE_OK;
43488   JournalFile *p = (JournalFile *)pJfd;
43489   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
43490     rc = createFile(p);
43491   }
43492   if( rc==SQLITE_OK ){
43493     if( p->pReal ){
43494       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
43495     }else{
43496       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
43497       if( p->iSize<(iOfst+iAmt) ){
43498         p->iSize = (iOfst+iAmt);
43499       }
43500     }
43501   }
43502   return rc;
43503 }
43504
43505 /*
43506 ** Truncate the file.
43507 */
43508 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
43509   int rc = SQLITE_OK;
43510   JournalFile *p = (JournalFile *)pJfd;
43511   if( p->pReal ){
43512     rc = sqlite3OsTruncate(p->pReal, size);
43513   }else if( size<p->iSize ){
43514     p->iSize = size;
43515   }
43516   return rc;
43517 }
43518
43519 /*
43520 ** Sync the file.
43521 */
43522 static int jrnlSync(sqlite3_file *pJfd, int flags){
43523   int rc;
43524   JournalFile *p = (JournalFile *)pJfd;
43525   rc = createFile(p);
43526   if( rc==SQLITE_OK ){
43527     rc = sqlite3OsSync(p->pReal, flags);
43528   }
43529   return rc;
43530 }
43531
43532 /*
43533 ** Query the size of the file in bytes.
43534 */
43535 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
43536   int rc = SQLITE_OK;
43537   JournalFile *p = (JournalFile *)pJfd;
43538   if( p->pReal ){
43539     rc = sqlite3OsFileSize(p->pReal, pSize);
43540   }else{
43541     *pSize = (sqlite_int64) p->iSize;
43542   }
43543   return rc;
43544 }
43545
43546 /*
43547 ** Table of methods for JournalFile sqlite3_file object.
43548 */
43549 static struct sqlite3_io_methods JournalFileMethods = {
43550   1,             /* iVersion */
43551   jrnlClose,     /* xClose */
43552   jrnlRead,      /* xRead */
43553   jrnlWrite,     /* xWrite */
43554   jrnlTruncate,  /* xTruncate */
43555   jrnlSync,      /* xSync */
43556   jrnlFileSize,  /* xFileSize */
43557   0,             /* xLock */
43558   0,             /* xUnlock */
43559   0,             /* xCheckReservedLock */
43560   0,             /* xFileControl */
43561   0,             /* xSectorSize */
43562   0              /* xDeviceCharacteristics */
43563 };
43564
43565 /* 
43566 ** Open a journal file.
43567 */
43568 SQLITE_PRIVATE int sqlite3JournalOpen(
43569   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
43570   const char *zName,         /* Name of the journal file */
43571   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
43572   int flags,                 /* Opening flags */
43573   int nBuf                   /* Bytes buffered before opening the file */
43574 ){
43575   JournalFile *p = (JournalFile *)pJfd;
43576   memset(p, 0, sqlite3JournalSize(pVfs));
43577   if( nBuf>0 ){
43578     p->zBuf = sqlite3MallocZero(nBuf);
43579     if( !p->zBuf ){
43580       return SQLITE_NOMEM;
43581     }
43582   }else{
43583     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
43584   }
43585   p->pMethod = &JournalFileMethods;
43586   p->nBuf = nBuf;
43587   p->flags = flags;
43588   p->zJournal = zName;
43589   p->pVfs = pVfs;
43590   return SQLITE_OK;
43591 }
43592
43593 /*
43594 ** If the argument p points to a JournalFile structure, and the underlying
43595 ** file has not yet been created, create it now.
43596 */
43597 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
43598   if( p->pMethods!=&JournalFileMethods ){
43599     return SQLITE_OK;
43600   }
43601   return createFile((JournalFile *)p);
43602 }
43603
43604 /* 
43605 ** Return the number of bytes required to store a JournalFile that uses vfs
43606 ** pVfs to create the underlying on-disk files.
43607 */
43608 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
43609   return (pVfs->szOsFile+sizeof(JournalFile));
43610 }
43611 #endif
43612
43613 /************** End of journal.c *********************************************/
43614 /************** Begin file expr.c ********************************************/
43615 /*
43616 ** 2001 September 15
43617 **
43618 ** The author disclaims copyright to this source code.  In place of
43619 ** a legal notice, here is a blessing:
43620 **
43621 **    May you do good and not evil.
43622 **    May you find forgiveness for yourself and forgive others.
43623 **    May you share freely, never taking more than you give.
43624 **
43625 *************************************************************************
43626 ** This file contains routines used for analyzing expressions and
43627 ** for generating VDBE code that evaluates expressions in SQLite.
43628 **
43629 ** $Id: expr.c,v 1.320 2007/12/14 15:12:21 drh Exp $
43630 */
43631
43632 /*
43633 ** Return the 'affinity' of the expression pExpr if any.
43634 **
43635 ** If pExpr is a column, a reference to a column via an 'AS' alias,
43636 ** or a sub-select with a column as the return value, then the 
43637 ** affinity of that column is returned. Otherwise, 0x00 is returned,
43638 ** indicating no affinity for the expression.
43639 **
43640 ** i.e. the WHERE clause expresssions in the following statements all
43641 ** have an affinity:
43642 **
43643 ** CREATE TABLE t1(a);
43644 ** SELECT * FROM t1 WHERE a;
43645 ** SELECT a AS b FROM t1 WHERE b;
43646 ** SELECT * FROM t1 WHERE (select a from t1);
43647 */
43648 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
43649   int op = pExpr->op;
43650   if( op==TK_SELECT ){
43651     return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
43652   }
43653 #ifndef SQLITE_OMIT_CAST
43654   if( op==TK_CAST ){
43655     return sqlite3AffinityType(&pExpr->token);
43656   }
43657 #endif
43658   return pExpr->affinity;
43659 }
43660
43661 /*
43662 ** Set the collating sequence for expression pExpr to be the collating
43663 ** sequence named by pToken.   Return a pointer to the revised expression.
43664 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
43665 ** flag.  An explicit collating sequence will override implicit
43666 ** collating sequences.
43667 */
43668 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pName){
43669   char *zColl = 0;            /* Dequoted name of collation sequence */
43670   CollSeq *pColl;
43671   zColl = sqlite3NameFromToken(pParse->db, pName);
43672   if( pExpr && zColl ){
43673     pColl = sqlite3LocateCollSeq(pParse, zColl, -1);
43674     if( pColl ){
43675       pExpr->pColl = pColl;
43676       pExpr->flags |= EP_ExpCollate;
43677     }
43678   }
43679   sqlite3_free(zColl);
43680   return pExpr;
43681 }
43682
43683 /*
43684 ** Return the default collation sequence for the expression pExpr. If
43685 ** there is no default collation type, return 0.
43686 */
43687 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
43688   CollSeq *pColl = 0;
43689   if( pExpr ){
43690     int op;
43691     pColl = pExpr->pColl;
43692     op = pExpr->op;
43693     if( (op==TK_CAST || op==TK_UPLUS) && !pColl ){
43694       return sqlite3ExprCollSeq(pParse, pExpr->pLeft);
43695     }
43696   }
43697   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
43698     pColl = 0;
43699   }
43700   return pColl;
43701 }
43702
43703 /*
43704 ** pExpr is an operand of a comparison operator.  aff2 is the
43705 ** type affinity of the other operand.  This routine returns the
43706 ** type affinity that should be used for the comparison operator.
43707 */
43708 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
43709   char aff1 = sqlite3ExprAffinity(pExpr);
43710   if( aff1 && aff2 ){
43711     /* Both sides of the comparison are columns. If one has numeric
43712     ** affinity, use that. Otherwise use no affinity.
43713     */
43714     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
43715       return SQLITE_AFF_NUMERIC;
43716     }else{
43717       return SQLITE_AFF_NONE;
43718     }
43719   }else if( !aff1 && !aff2 ){
43720     /* Neither side of the comparison is a column.  Compare the
43721     ** results directly.
43722     */
43723     return SQLITE_AFF_NONE;
43724   }else{
43725     /* One side is a column, the other is not. Use the columns affinity. */
43726     assert( aff1==0 || aff2==0 );
43727     return (aff1 + aff2);
43728   }
43729 }
43730
43731 /*
43732 ** pExpr is a comparison operator.  Return the type affinity that should
43733 ** be applied to both operands prior to doing the comparison.
43734 */
43735 static char comparisonAffinity(Expr *pExpr){
43736   char aff;
43737   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
43738           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
43739           pExpr->op==TK_NE );
43740   assert( pExpr->pLeft );
43741   aff = sqlite3ExprAffinity(pExpr->pLeft);
43742   if( pExpr->pRight ){
43743     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
43744   }
43745   else if( pExpr->pSelect ){
43746     aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
43747   }
43748   else if( !aff ){
43749     aff = SQLITE_AFF_NONE;
43750   }
43751   return aff;
43752 }
43753
43754 /*
43755 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
43756 ** idx_affinity is the affinity of an indexed column. Return true
43757 ** if the index with affinity idx_affinity may be used to implement
43758 ** the comparison in pExpr.
43759 */
43760 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
43761   char aff = comparisonAffinity(pExpr);
43762   switch( aff ){
43763     case SQLITE_AFF_NONE:
43764       return 1;
43765     case SQLITE_AFF_TEXT:
43766       return idx_affinity==SQLITE_AFF_TEXT;
43767     default:
43768       return sqlite3IsNumericAffinity(idx_affinity);
43769   }
43770 }
43771
43772 /*
43773 ** Return the P1 value that should be used for a binary comparison
43774 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
43775 ** If jumpIfNull is true, then set the low byte of the returned
43776 ** P1 value to tell the opcode to jump if either expression
43777 ** evaluates to NULL.
43778 */
43779 static int binaryCompareP1(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
43780   char aff = sqlite3ExprAffinity(pExpr2);
43781   return ((int)sqlite3CompareAffinity(pExpr1, aff))+(jumpIfNull?0x100:0);
43782 }
43783
43784 /*
43785 ** Return a pointer to the collation sequence that should be used by
43786 ** a binary comparison operator comparing pLeft and pRight.
43787 **
43788 ** If the left hand expression has a collating sequence type, then it is
43789 ** used. Otherwise the collation sequence for the right hand expression
43790 ** is used, or the default (BINARY) if neither expression has a collating
43791 ** type.
43792 **
43793 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
43794 ** it is not considered.
43795 */
43796 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
43797   Parse *pParse, 
43798   Expr *pLeft, 
43799   Expr *pRight
43800 ){
43801   CollSeq *pColl;
43802   assert( pLeft );
43803   if( pLeft->flags & EP_ExpCollate ){
43804     assert( pLeft->pColl );
43805     pColl = pLeft->pColl;
43806   }else if( pRight && pRight->flags & EP_ExpCollate ){
43807     assert( pRight->pColl );
43808     pColl = pRight->pColl;
43809   }else{
43810     pColl = sqlite3ExprCollSeq(pParse, pLeft);
43811     if( !pColl ){
43812       pColl = sqlite3ExprCollSeq(pParse, pRight);
43813     }
43814   }
43815   return pColl;
43816 }
43817
43818 /*
43819 ** Generate code for a comparison operator.
43820 */
43821 static int codeCompare(
43822   Parse *pParse,    /* The parsing (and code generating) context */
43823   Expr *pLeft,      /* The left operand */
43824   Expr *pRight,     /* The right operand */
43825   int opcode,       /* The comparison opcode */
43826   int dest,         /* Jump here if true.  */
43827   int jumpIfNull    /* If true, jump if either operand is NULL */
43828 ){
43829   int p1 = binaryCompareP1(pLeft, pRight, jumpIfNull);
43830   CollSeq *p3 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
43831   return sqlite3VdbeOp3(pParse->pVdbe, opcode, p1, dest, (void*)p3, P3_COLLSEQ);
43832 }
43833
43834 /*
43835 ** Construct a new expression node and return a pointer to it.  Memory
43836 ** for this node is obtained from sqlite3_malloc().  The calling function
43837 ** is responsible for making sure the node eventually gets freed.
43838 */
43839 SQLITE_PRIVATE Expr *sqlite3Expr(
43840   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
43841   int op,                 /* Expression opcode */
43842   Expr *pLeft,            /* Left operand */
43843   Expr *pRight,           /* Right operand */
43844   const Token *pToken     /* Argument token */
43845 ){
43846   Expr *pNew;
43847   pNew = sqlite3DbMallocZero(db, sizeof(Expr));
43848   if( pNew==0 ){
43849     /* When malloc fails, delete pLeft and pRight. Expressions passed to 
43850     ** this function must always be allocated with sqlite3Expr() for this 
43851     ** reason. 
43852     */
43853     sqlite3ExprDelete(pLeft);
43854     sqlite3ExprDelete(pRight);
43855     return 0;
43856   }
43857   pNew->op = op;
43858   pNew->pLeft = pLeft;
43859   pNew->pRight = pRight;
43860   pNew->iAgg = -1;
43861   if( pToken ){
43862     assert( pToken->dyn==0 );
43863     pNew->span = pNew->token = *pToken;
43864   }else if( pLeft ){
43865     if( pRight ){
43866       sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
43867       if( pRight->flags & EP_ExpCollate ){
43868         pNew->flags |= EP_ExpCollate;
43869         pNew->pColl = pRight->pColl;
43870       }
43871     }
43872     if( pLeft->flags & EP_ExpCollate ){
43873       pNew->flags |= EP_ExpCollate;
43874       pNew->pColl = pLeft->pColl;
43875     }
43876   }
43877
43878   sqlite3ExprSetHeight(pNew);
43879   return pNew;
43880 }
43881
43882 /*
43883 ** Works like sqlite3Expr() except that it takes an extra Parse*
43884 ** argument and notifies the associated connection object if malloc fails.
43885 */
43886 SQLITE_PRIVATE Expr *sqlite3PExpr(
43887   Parse *pParse,          /* Parsing context */
43888   int op,                 /* Expression opcode */
43889   Expr *pLeft,            /* Left operand */
43890   Expr *pRight,           /* Right operand */
43891   const Token *pToken     /* Argument token */
43892 ){
43893   return sqlite3Expr(pParse->db, op, pLeft, pRight, pToken);
43894 }
43895
43896 /*
43897 ** When doing a nested parse, you can include terms in an expression
43898 ** that look like this:   #0 #1 #2 ...  These terms refer to elements
43899 ** on the stack.  "#0" means the top of the stack.
43900 ** "#1" means the next down on the stack.  And so forth.
43901 **
43902 ** This routine is called by the parser to deal with on of those terms.
43903 ** It immediately generates code to store the value in a memory location.
43904 ** The returns an expression that will code to extract the value from
43905 ** that memory location as needed.
43906 */
43907 SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
43908   Vdbe *v = pParse->pVdbe;
43909   Expr *p;
43910   int depth;
43911   if( pParse->nested==0 ){
43912     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
43913     return sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
43914   }
43915   if( v==0 ) return 0;
43916   p = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, pToken);
43917   if( p==0 ){
43918     return 0;  /* Malloc failed */
43919   }
43920   depth = atoi((char*)&pToken->z[1]);
43921   p->iTable = pParse->nMem++;
43922   sqlite3VdbeAddOp(v, OP_Dup, depth, 0);
43923   sqlite3VdbeAddOp(v, OP_MemStore, p->iTable, 1);
43924   return p;
43925 }
43926
43927 /*
43928 ** Join two expressions using an AND operator.  If either expression is
43929 ** NULL, then just return the other expression.
43930 */
43931 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
43932   if( pLeft==0 ){
43933     return pRight;
43934   }else if( pRight==0 ){
43935     return pLeft;
43936   }else{
43937     return sqlite3Expr(db, TK_AND, pLeft, pRight, 0);
43938   }
43939 }
43940
43941 /*
43942 ** Set the Expr.span field of the given expression to span all
43943 ** text between the two given tokens.
43944 */
43945 SQLITE_PRIVATE void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
43946   assert( pRight!=0 );
43947   assert( pLeft!=0 );
43948   if( pExpr && pRight->z && pLeft->z ){
43949     assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
43950     if( pLeft->dyn==0 && pRight->dyn==0 ){
43951       pExpr->span.z = pLeft->z;
43952       pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
43953     }else{
43954       pExpr->span.z = 0;
43955     }
43956   }
43957 }
43958
43959 /*
43960 ** Construct a new expression node for a function with multiple
43961 ** arguments.
43962 */
43963 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
43964   Expr *pNew;
43965   assert( pToken );
43966   pNew = sqlite3DbMallocZero(pParse->db, sizeof(Expr) );
43967   if( pNew==0 ){
43968     sqlite3ExprListDelete(pList); /* Avoid leaking memory when malloc fails */
43969     return 0;
43970   }
43971   pNew->op = TK_FUNCTION;
43972   pNew->pList = pList;
43973   assert( pToken->dyn==0 );
43974   pNew->token = *pToken;
43975   pNew->span = pNew->token;
43976
43977   sqlite3ExprSetHeight(pNew);
43978   return pNew;
43979 }
43980
43981 /*
43982 ** Assign a variable number to an expression that encodes a wildcard
43983 ** in the original SQL statement.  
43984 **
43985 ** Wildcards consisting of a single "?" are assigned the next sequential
43986 ** variable number.
43987 **
43988 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
43989 ** sure "nnn" is not too be to avoid a denial of service attack when
43990 ** the SQL statement comes from an external source.
43991 **
43992 ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
43993 ** as the previous instance of the same wildcard.  Or if this is the first
43994 ** instance of the wildcard, the next sequenial variable number is
43995 ** assigned.
43996 */
43997 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
43998   Token *pToken;
43999   sqlite3 *db = pParse->db;
44000
44001   if( pExpr==0 ) return;
44002   pToken = &pExpr->token;
44003   assert( pToken->n>=1 );
44004   assert( pToken->z!=0 );
44005   assert( pToken->z[0]!=0 );
44006   if( pToken->n==1 ){
44007     /* Wildcard of the form "?".  Assign the next variable number */
44008     pExpr->iTable = ++pParse->nVar;
44009   }else if( pToken->z[0]=='?' ){
44010     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
44011     ** use it as the variable number */
44012     int i;
44013     pExpr->iTable = i = atoi((char*)&pToken->z[1]);
44014     if( i<1 || i>SQLITE_MAX_VARIABLE_NUMBER ){
44015       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
44016           SQLITE_MAX_VARIABLE_NUMBER);
44017     }
44018     if( i>pParse->nVar ){
44019       pParse->nVar = i;
44020     }
44021   }else{
44022     /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
44023     ** number as the prior appearance of the same name, or if the name
44024     ** has never appeared before, reuse the same variable number
44025     */
44026     int i, n;
44027     n = pToken->n;
44028     for(i=0; i<pParse->nVarExpr; i++){
44029       Expr *pE;
44030       if( (pE = pParse->apVarExpr[i])!=0
44031           && pE->token.n==n
44032           && memcmp(pE->token.z, pToken->z, n)==0 ){
44033         pExpr->iTable = pE->iTable;
44034         break;
44035       }
44036     }
44037     if( i>=pParse->nVarExpr ){
44038       pExpr->iTable = ++pParse->nVar;
44039       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
44040         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
44041         pParse->apVarExpr =
44042             sqlite3DbReallocOrFree(
44043               db,
44044               pParse->apVarExpr,
44045               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
44046             );
44047       }
44048       if( !db->mallocFailed ){
44049         assert( pParse->apVarExpr!=0 );
44050         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
44051       }
44052     }
44053   } 
44054   if( !pParse->nErr && pParse->nVar>SQLITE_MAX_VARIABLE_NUMBER ){
44055     sqlite3ErrorMsg(pParse, "too many SQL variables");
44056   }
44057 }
44058
44059 /*
44060 ** Recursively delete an expression tree.
44061 */
44062 SQLITE_PRIVATE void sqlite3ExprDelete(Expr *p){
44063   if( p==0 ) return;
44064   if( p->span.dyn ) sqlite3_free((char*)p->span.z);
44065   if( p->token.dyn ) sqlite3_free((char*)p->token.z);
44066   sqlite3ExprDelete(p->pLeft);
44067   sqlite3ExprDelete(p->pRight);
44068   sqlite3ExprListDelete(p->pList);
44069   sqlite3SelectDelete(p->pSelect);
44070   sqlite3_free(p);
44071 }
44072
44073 /*
44074 ** The Expr.token field might be a string literal that is quoted.
44075 ** If so, remove the quotation marks.
44076 */
44077 SQLITE_PRIVATE void sqlite3DequoteExpr(sqlite3 *db, Expr *p){
44078   if( ExprHasAnyProperty(p, EP_Dequoted) ){
44079     return;
44080   }
44081   ExprSetProperty(p, EP_Dequoted);
44082   if( p->token.dyn==0 ){
44083     sqlite3TokenCopy(db, &p->token, &p->token);
44084   }
44085   sqlite3Dequote((char*)p->token.z);
44086 }
44087
44088
44089 /*
44090 ** The following group of routines make deep copies of expressions,
44091 ** expression lists, ID lists, and select statements.  The copies can
44092 ** be deleted (by being passed to their respective ...Delete() routines)
44093 ** without effecting the originals.
44094 **
44095 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
44096 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
44097 ** by subsequent calls to sqlite*ListAppend() routines.
44098 **
44099 ** Any tables that the SrcList might point to are not duplicated.
44100 */
44101 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p){
44102   Expr *pNew;
44103   if( p==0 ) return 0;
44104   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
44105   if( pNew==0 ) return 0;
44106   memcpy(pNew, p, sizeof(*pNew));
44107   if( p->token.z!=0 ){
44108     pNew->token.z = (u8*)sqlite3DbStrNDup(db, (char*)p->token.z, p->token.n);
44109     pNew->token.dyn = 1;
44110   }else{
44111     assert( pNew->token.z==0 );
44112   }
44113   pNew->span.z = 0;
44114   pNew->pLeft = sqlite3ExprDup(db, p->pLeft);
44115   pNew->pRight = sqlite3ExprDup(db, p->pRight);
44116   pNew->pList = sqlite3ExprListDup(db, p->pList);
44117   pNew->pSelect = sqlite3SelectDup(db, p->pSelect);
44118   return pNew;
44119 }
44120 SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3 *db, Token *pTo, Token *pFrom){
44121   if( pTo->dyn ) sqlite3_free((char*)pTo->z);
44122   if( pFrom->z ){
44123     pTo->n = pFrom->n;
44124     pTo->z = (u8*)sqlite3DbStrNDup(db, (char*)pFrom->z, pFrom->n);
44125     pTo->dyn = 1;
44126   }else{
44127     pTo->z = 0;
44128   }
44129 }
44130 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p){
44131   ExprList *pNew;
44132   struct ExprList_item *pItem, *pOldItem;
44133   int i;
44134   if( p==0 ) return 0;
44135   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
44136   if( pNew==0 ) return 0;
44137   pNew->iECursor = 0;
44138   pNew->nExpr = pNew->nAlloc = p->nExpr;
44139   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
44140   if( pItem==0 ){
44141     sqlite3_free(pNew);
44142     return 0;
44143   } 
44144   pOldItem = p->a;
44145   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
44146     Expr *pNewExpr, *pOldExpr;
44147     pItem->pExpr = pNewExpr = sqlite3ExprDup(db, pOldExpr = pOldItem->pExpr);
44148     if( pOldExpr->span.z!=0 && pNewExpr ){
44149       /* Always make a copy of the span for top-level expressions in the
44150       ** expression list.  The logic in SELECT processing that determines
44151       ** the names of columns in the result set needs this information */
44152       sqlite3TokenCopy(db, &pNewExpr->span, &pOldExpr->span);
44153     }
44154     assert( pNewExpr==0 || pNewExpr->span.z!=0 
44155             || pOldExpr->span.z==0
44156             || db->mallocFailed );
44157     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
44158     pItem->sortOrder = pOldItem->sortOrder;
44159     pItem->isAgg = pOldItem->isAgg;
44160     pItem->done = 0;
44161   }
44162   return pNew;
44163 }
44164
44165 /*
44166 ** If cursors, triggers, views and subqueries are all omitted from
44167 ** the build, then none of the following routines, except for 
44168 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
44169 ** called with a NULL argument.
44170 */
44171 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
44172  || !defined(SQLITE_OMIT_SUBQUERY)
44173 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p){
44174   SrcList *pNew;
44175   int i;
44176   int nByte;
44177   if( p==0 ) return 0;
44178   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
44179   pNew = sqlite3DbMallocRaw(db, nByte );
44180   if( pNew==0 ) return 0;
44181   pNew->nSrc = pNew->nAlloc = p->nSrc;
44182   for(i=0; i<p->nSrc; i++){
44183     struct SrcList_item *pNewItem = &pNew->a[i];
44184     struct SrcList_item *pOldItem = &p->a[i];
44185     Table *pTab;
44186     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
44187     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
44188     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
44189     pNewItem->jointype = pOldItem->jointype;
44190     pNewItem->iCursor = pOldItem->iCursor;
44191     pNewItem->isPopulated = pOldItem->isPopulated;
44192     pTab = pNewItem->pTab = pOldItem->pTab;
44193     if( pTab ){
44194       pTab->nRef++;
44195     }
44196     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect);
44197     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn);
44198     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
44199     pNewItem->colUsed = pOldItem->colUsed;
44200   }
44201   return pNew;
44202 }
44203 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
44204   IdList *pNew;
44205   int i;
44206   if( p==0 ) return 0;
44207   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
44208   if( pNew==0 ) return 0;
44209   pNew->nId = pNew->nAlloc = p->nId;
44210   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
44211   if( pNew->a==0 ){
44212     sqlite3_free(pNew);
44213     return 0;
44214   }
44215   for(i=0; i<p->nId; i++){
44216     struct IdList_item *pNewItem = &pNew->a[i];
44217     struct IdList_item *pOldItem = &p->a[i];
44218     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
44219     pNewItem->idx = pOldItem->idx;
44220   }
44221   return pNew;
44222 }
44223 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p){
44224   Select *pNew;
44225   if( p==0 ) return 0;
44226   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
44227   if( pNew==0 ) return 0;
44228   pNew->isDistinct = p->isDistinct;
44229   pNew->pEList = sqlite3ExprListDup(db, p->pEList);
44230   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc);
44231   pNew->pWhere = sqlite3ExprDup(db, p->pWhere);
44232   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy);
44233   pNew->pHaving = sqlite3ExprDup(db, p->pHaving);
44234   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy);
44235   pNew->op = p->op;
44236   pNew->pPrior = sqlite3SelectDup(db, p->pPrior);
44237   pNew->pLimit = sqlite3ExprDup(db, p->pLimit);
44238   pNew->pOffset = sqlite3ExprDup(db, p->pOffset);
44239   pNew->iLimit = -1;
44240   pNew->iOffset = -1;
44241   pNew->isResolved = p->isResolved;
44242   pNew->isAgg = p->isAgg;
44243   pNew->usesEphm = 0;
44244   pNew->disallowOrderBy = 0;
44245   pNew->pRightmost = 0;
44246   pNew->addrOpenEphm[0] = -1;
44247   pNew->addrOpenEphm[1] = -1;
44248   pNew->addrOpenEphm[2] = -1;
44249   return pNew;
44250 }
44251 #else
44252 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p){
44253   assert( p==0 );
44254   return 0;
44255 }
44256 #endif
44257
44258
44259 /*
44260 ** Add a new element to the end of an expression list.  If pList is
44261 ** initially NULL, then create a new expression list.
44262 */
44263 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
44264   Parse *pParse,          /* Parsing context */
44265   ExprList *pList,        /* List to which to append. Might be NULL */
44266   Expr *pExpr,            /* Expression to be appended */
44267   Token *pName            /* AS keyword for the expression */
44268 ){
44269   sqlite3 *db = pParse->db;
44270   if( pList==0 ){
44271     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
44272     if( pList==0 ){
44273       goto no_mem;
44274     }
44275     assert( pList->nAlloc==0 );
44276   }
44277   if( pList->nAlloc<=pList->nExpr ){
44278     struct ExprList_item *a;
44279     int n = pList->nAlloc*2 + 4;
44280     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
44281     if( a==0 ){
44282       goto no_mem;
44283     }
44284     pList->a = a;
44285     pList->nAlloc = n;
44286   }
44287   assert( pList->a!=0 );
44288   if( pExpr || pName ){
44289     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
44290     memset(pItem, 0, sizeof(*pItem));
44291     pItem->zName = sqlite3NameFromToken(db, pName);
44292     pItem->pExpr = pExpr;
44293   }
44294   return pList;
44295
44296 no_mem:     
44297   /* Avoid leaking memory if malloc has failed. */
44298   sqlite3ExprDelete(pExpr);
44299   sqlite3ExprListDelete(pList);
44300   return 0;
44301 }
44302
44303 /*
44304 ** If the expression list pEList contains more than iLimit elements,
44305 ** leave an error message in pParse.
44306 */
44307 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
44308   Parse *pParse,
44309   ExprList *pEList,
44310   int iLimit,
44311   const char *zObject
44312 ){
44313   if( pEList && pEList->nExpr>iLimit ){
44314     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
44315   }
44316 }
44317
44318
44319 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
44320 /* The following three functions, heightOfExpr(), heightOfExprList()
44321 ** and heightOfSelect(), are used to determine the maximum height
44322 ** of any expression tree referenced by the structure passed as the
44323 ** first argument.
44324 **
44325 ** If this maximum height is greater than the current value pointed
44326 ** to by pnHeight, the second parameter, then set *pnHeight to that
44327 ** value.
44328 */
44329 static void heightOfExpr(Expr *p, int *pnHeight){
44330   if( p ){
44331     if( p->nHeight>*pnHeight ){
44332       *pnHeight = p->nHeight;
44333     }
44334   }
44335 }
44336 static void heightOfExprList(ExprList *p, int *pnHeight){
44337   if( p ){
44338     int i;
44339     for(i=0; i<p->nExpr; i++){
44340       heightOfExpr(p->a[i].pExpr, pnHeight);
44341     }
44342   }
44343 }
44344 static void heightOfSelect(Select *p, int *pnHeight){
44345   if( p ){
44346     heightOfExpr(p->pWhere, pnHeight);
44347     heightOfExpr(p->pHaving, pnHeight);
44348     heightOfExpr(p->pLimit, pnHeight);
44349     heightOfExpr(p->pOffset, pnHeight);
44350     heightOfExprList(p->pEList, pnHeight);
44351     heightOfExprList(p->pGroupBy, pnHeight);
44352     heightOfExprList(p->pOrderBy, pnHeight);
44353     heightOfSelect(p->pPrior, pnHeight);
44354   }
44355 }
44356
44357 /*
44358 ** Set the Expr.nHeight variable in the structure passed as an 
44359 ** argument. An expression with no children, Expr.pList or 
44360 ** Expr.pSelect member has a height of 1. Any other expression
44361 ** has a height equal to the maximum height of any other 
44362 ** referenced Expr plus one.
44363 */
44364 SQLITE_PRIVATE void sqlite3ExprSetHeight(Expr *p){
44365   int nHeight = 0;
44366   heightOfExpr(p->pLeft, &nHeight);
44367   heightOfExpr(p->pRight, &nHeight);
44368   heightOfExprList(p->pList, &nHeight);
44369   heightOfSelect(p->pSelect, &nHeight);
44370   p->nHeight = nHeight + 1;
44371 }
44372
44373 /*
44374 ** Return the maximum height of any expression tree referenced
44375 ** by the select statement passed as an argument.
44376 */
44377 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
44378   int nHeight = 0;
44379   heightOfSelect(p, &nHeight);
44380   return nHeight;
44381 }
44382 #endif
44383
44384 /*
44385 ** Delete an entire expression list.
44386 */
44387 SQLITE_PRIVATE void sqlite3ExprListDelete(ExprList *pList){
44388   int i;
44389   struct ExprList_item *pItem;
44390   if( pList==0 ) return;
44391   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
44392   assert( pList->nExpr<=pList->nAlloc );
44393   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
44394     sqlite3ExprDelete(pItem->pExpr);
44395     sqlite3_free(pItem->zName);
44396   }
44397   sqlite3_free(pList->a);
44398   sqlite3_free(pList);
44399 }
44400
44401 /*
44402 ** Walk an expression tree.  Call xFunc for each node visited.
44403 **
44404 ** The return value from xFunc determines whether the tree walk continues.
44405 ** 0 means continue walking the tree.  1 means do not walk children
44406 ** of the current node but continue with siblings.  2 means abandon
44407 ** the tree walk completely.
44408 **
44409 ** The return value from this routine is 1 to abandon the tree walk
44410 ** and 0 to continue.
44411 **
44412 ** NOTICE:  This routine does *not* descend into subqueries.
44413 */
44414 static int walkExprList(ExprList *, int (*)(void *, Expr*), void *);
44415 static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){
44416   int rc;
44417   if( pExpr==0 ) return 0;
44418   rc = (*xFunc)(pArg, pExpr);
44419   if( rc==0 ){
44420     if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1;
44421     if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1;
44422     if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1;
44423   }
44424   return rc>1;
44425 }
44426
44427 /*
44428 ** Call walkExprTree() for every expression in list p.
44429 */
44430 static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){
44431   int i;
44432   struct ExprList_item *pItem;
44433   if( !p ) return 0;
44434   for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
44435     if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1;
44436   }
44437   return 0;
44438 }
44439
44440 /*
44441 ** Call walkExprTree() for every expression in Select p, not including
44442 ** expressions that are part of sub-selects in any FROM clause or the LIMIT
44443 ** or OFFSET expressions..
44444 */
44445 static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){
44446   walkExprList(p->pEList, xFunc, pArg);
44447   walkExprTree(p->pWhere, xFunc, pArg);
44448   walkExprList(p->pGroupBy, xFunc, pArg);
44449   walkExprTree(p->pHaving, xFunc, pArg);
44450   walkExprList(p->pOrderBy, xFunc, pArg);
44451   if( p->pPrior ){
44452     walkSelectExpr(p->pPrior, xFunc, pArg);
44453   }
44454   return 0;
44455 }
44456
44457
44458 /*
44459 ** This routine is designed as an xFunc for walkExprTree().
44460 **
44461 ** pArg is really a pointer to an integer.  If we can tell by looking
44462 ** at pExpr that the expression that contains pExpr is not a constant
44463 ** expression, then set *pArg to 0 and return 2 to abandon the tree walk.
44464 ** If pExpr does does not disqualify the expression from being a constant
44465 ** then do nothing.
44466 **
44467 ** After walking the whole tree, if no nodes are found that disqualify
44468 ** the expression as constant, then we assume the whole expression
44469 ** is constant.  See sqlite3ExprIsConstant() for additional information.
44470 */
44471 static int exprNodeIsConstant(void *pArg, Expr *pExpr){
44472   int *pN = (int*)pArg;
44473
44474   /* If *pArg is 3 then any term of the expression that comes from
44475   ** the ON or USING clauses of a join disqualifies the expression
44476   ** from being considered constant. */
44477   if( (*pN)==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
44478     *pN = 0;
44479     return 2;
44480   }
44481
44482   switch( pExpr->op ){
44483     /* Consider functions to be constant if all their arguments are constant
44484     ** and *pArg==2 */
44485     case TK_FUNCTION:
44486       if( (*pN)==2 ) return 0;
44487       /* Fall through */
44488     case TK_ID:
44489     case TK_COLUMN:
44490     case TK_DOT:
44491     case TK_AGG_FUNCTION:
44492     case TK_AGG_COLUMN:
44493 #ifndef SQLITE_OMIT_SUBQUERY
44494     case TK_SELECT:
44495     case TK_EXISTS:
44496 #endif
44497       *pN = 0;
44498       return 2;
44499     case TK_IN:
44500       if( pExpr->pSelect ){
44501         *pN = 0;
44502         return 2;
44503       }
44504     default:
44505       return 0;
44506   }
44507 }
44508
44509 /*
44510 ** Walk an expression tree.  Return 1 if the expression is constant
44511 ** and 0 if it involves variables or function calls.
44512 **
44513 ** For the purposes of this function, a double-quoted string (ex: "abc")
44514 ** is considered a variable but a single-quoted string (ex: 'abc') is
44515 ** a constant.
44516 */
44517 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
44518   int isConst = 1;
44519   walkExprTree(p, exprNodeIsConstant, &isConst);
44520   return isConst;
44521 }
44522
44523 /*
44524 ** Walk an expression tree.  Return 1 if the expression is constant
44525 ** that does no originate from the ON or USING clauses of a join.
44526 ** Return 0 if it involves variables or function calls or terms from
44527 ** an ON or USING clause.
44528 */
44529 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
44530   int isConst = 3;
44531   walkExprTree(p, exprNodeIsConstant, &isConst);
44532   return isConst!=0;
44533 }
44534
44535 /*
44536 ** Walk an expression tree.  Return 1 if the expression is constant
44537 ** or a function call with constant arguments.  Return and 0 if there
44538 ** are any variables.
44539 **
44540 ** For the purposes of this function, a double-quoted string (ex: "abc")
44541 ** is considered a variable but a single-quoted string (ex: 'abc') is
44542 ** a constant.
44543 */
44544 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
44545   int isConst = 2;
44546   walkExprTree(p, exprNodeIsConstant, &isConst);
44547   return isConst!=0;
44548 }
44549
44550 /*
44551 ** If the expression p codes a constant integer that is small enough
44552 ** to fit in a 32-bit integer, return 1 and put the value of the integer
44553 ** in *pValue.  If the expression is not an integer or if it is too big
44554 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
44555 */
44556 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
44557   switch( p->op ){
44558     case TK_INTEGER: {
44559       if( sqlite3GetInt32((char*)p->token.z, pValue) ){
44560         return 1;
44561       }
44562       break;
44563     }
44564     case TK_UPLUS: {
44565       return sqlite3ExprIsInteger(p->pLeft, pValue);
44566     }
44567     case TK_UMINUS: {
44568       int v;
44569       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
44570         *pValue = -v;
44571         return 1;
44572       }
44573       break;
44574     }
44575     default: break;
44576   }
44577   return 0;
44578 }
44579
44580 /*
44581 ** Return TRUE if the given string is a row-id column name.
44582 */
44583 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
44584   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
44585   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
44586   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
44587   return 0;
44588 }
44589
44590 /*
44591 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
44592 ** that name in the set of source tables in pSrcList and make the pExpr 
44593 ** expression node refer back to that source column.  The following changes
44594 ** are made to pExpr:
44595 **
44596 **    pExpr->iDb           Set the index in db->aDb[] of the database holding
44597 **                         the table.
44598 **    pExpr->iTable        Set to the cursor number for the table obtained
44599 **                         from pSrcList.
44600 **    pExpr->iColumn       Set to the column number within the table.
44601 **    pExpr->op            Set to TK_COLUMN.
44602 **    pExpr->pLeft         Any expression this points to is deleted
44603 **    pExpr->pRight        Any expression this points to is deleted.
44604 **
44605 ** The pDbToken is the name of the database (the "X").  This value may be
44606 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
44607 ** can be used.  The pTableToken is the name of the table (the "Y").  This
44608 ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
44609 ** means that the form of the name is Z and that columns from any table
44610 ** can be used.
44611 **
44612 ** If the name cannot be resolved unambiguously, leave an error message
44613 ** in pParse and return non-zero.  Return zero on success.
44614 */
44615 static int lookupName(
44616   Parse *pParse,       /* The parsing context */
44617   Token *pDbToken,     /* Name of the database containing table, or NULL */
44618   Token *pTableToken,  /* Name of table containing column, or NULL */
44619   Token *pColumnToken, /* Name of the column. */
44620   NameContext *pNC,    /* The name context used to resolve the name */
44621   Expr *pExpr          /* Make this EXPR node point to the selected column */
44622 ){
44623   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
44624   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
44625   char *zCol = 0;      /* Name of the column.  The "Z" */
44626   int i, j;            /* Loop counters */
44627   int cnt = 0;         /* Number of matching column names */
44628   int cntTab = 0;      /* Number of matching table names */
44629   sqlite3 *db = pParse->db;  /* The database */
44630   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
44631   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
44632   NameContext *pTopNC = pNC;        /* First namecontext in the list */
44633   Schema *pSchema = 0;              /* Schema of the expression */
44634
44635   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
44636   zDb = sqlite3NameFromToken(db, pDbToken);
44637   zTab = sqlite3NameFromToken(db, pTableToken);
44638   zCol = sqlite3NameFromToken(db, pColumnToken);
44639   if( db->mallocFailed ){
44640     goto lookupname_end;
44641   }
44642
44643   pExpr->iTable = -1;
44644   while( pNC && cnt==0 ){
44645     ExprList *pEList;
44646     SrcList *pSrcList = pNC->pSrcList;
44647
44648     if( pSrcList ){
44649       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
44650         Table *pTab;
44651         int iDb;
44652         Column *pCol;
44653   
44654         pTab = pItem->pTab;
44655         assert( pTab!=0 );
44656         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
44657         assert( pTab->nCol>0 );
44658         if( zTab ){
44659           if( pItem->zAlias ){
44660             char *zTabName = pItem->zAlias;
44661             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
44662           }else{
44663             char *zTabName = pTab->zName;
44664             if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
44665             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
44666               continue;
44667             }
44668           }
44669         }
44670         if( 0==(cntTab++) ){
44671           pExpr->iTable = pItem->iCursor;
44672           pSchema = pTab->pSchema;
44673           pMatch = pItem;
44674         }
44675         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
44676           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
44677             const char *zColl = pTab->aCol[j].zColl;
44678             IdList *pUsing;
44679             cnt++;
44680             pExpr->iTable = pItem->iCursor;
44681             pMatch = pItem;
44682             pSchema = pTab->pSchema;
44683             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
44684             pExpr->iColumn = j==pTab->iPKey ? -1 : j;
44685             pExpr->affinity = pTab->aCol[j].affinity;
44686             if( (pExpr->flags & EP_ExpCollate)==0 ){
44687               pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
44688             }
44689             if( i<pSrcList->nSrc-1 ){
44690               if( pItem[1].jointype & JT_NATURAL ){
44691                 /* If this match occurred in the left table of a natural join,
44692                 ** then skip the right table to avoid a duplicate match */
44693                 pItem++;
44694                 i++;
44695               }else if( (pUsing = pItem[1].pUsing)!=0 ){
44696                 /* If this match occurs on a column that is in the USING clause
44697                 ** of a join, skip the search of the right table of the join
44698                 ** to avoid a duplicate match there. */
44699                 int k;
44700                 for(k=0; k<pUsing->nId; k++){
44701                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
44702                     pItem++;
44703                     i++;
44704                     break;
44705                   }
44706                 }
44707               }
44708             }
44709             break;
44710           }
44711         }
44712       }
44713     }
44714
44715 #ifndef SQLITE_OMIT_TRIGGER
44716     /* If we have not already resolved the name, then maybe 
44717     ** it is a new.* or old.* trigger argument reference
44718     */
44719     if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
44720       TriggerStack *pTriggerStack = pParse->trigStack;
44721       Table *pTab = 0;
44722       if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
44723         pExpr->iTable = pTriggerStack->newIdx;
44724         assert( pTriggerStack->pTab );
44725         pTab = pTriggerStack->pTab;
44726       }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
44727         pExpr->iTable = pTriggerStack->oldIdx;
44728         assert( pTriggerStack->pTab );
44729         pTab = pTriggerStack->pTab;
44730       }
44731
44732       if( pTab ){ 
44733         int iCol;
44734         Column *pCol = pTab->aCol;
44735
44736         pSchema = pTab->pSchema;
44737         cntTab++;
44738         for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
44739           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
44740             const char *zColl = pTab->aCol[iCol].zColl;
44741             cnt++;
44742             pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
44743             pExpr->affinity = pTab->aCol[iCol].affinity;
44744             if( (pExpr->flags & EP_ExpCollate)==0 ){
44745               pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
44746             }
44747             pExpr->pTab = pTab;
44748             break;
44749           }
44750         }
44751       }
44752     }
44753 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
44754
44755     /*
44756     ** Perhaps the name is a reference to the ROWID
44757     */
44758     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
44759       cnt = 1;
44760       pExpr->iColumn = -1;
44761       pExpr->affinity = SQLITE_AFF_INTEGER;
44762     }
44763
44764     /*
44765     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
44766     ** might refer to an result-set alias.  This happens, for example, when
44767     ** we are resolving names in the WHERE clause of the following command:
44768     **
44769     **     SELECT a+b AS x FROM table WHERE x<10;
44770     **
44771     ** In cases like this, replace pExpr with a copy of the expression that
44772     ** forms the result set entry ("a+b" in the example) and return immediately.
44773     ** Note that the expression in the result set should have already been
44774     ** resolved by the time the WHERE clause is resolved.
44775     */
44776     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
44777       for(j=0; j<pEList->nExpr; j++){
44778         char *zAs = pEList->a[j].zName;
44779         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
44780           Expr *pDup, *pOrig;
44781           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
44782           assert( pExpr->pList==0 );
44783           assert( pExpr->pSelect==0 );
44784           pOrig = pEList->a[j].pExpr;
44785           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
44786             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
44787             sqlite3_free(zCol);
44788             return 2;
44789           }
44790           pDup = sqlite3ExprDup(db, pOrig);
44791           if( pExpr->flags & EP_ExpCollate ){
44792             pDup->pColl = pExpr->pColl;
44793             pDup->flags |= EP_ExpCollate;
44794           }
44795           if( pExpr->span.dyn ) sqlite3_free((char*)pExpr->span.z);
44796           if( pExpr->token.dyn ) sqlite3_free((char*)pExpr->token.z);
44797           memcpy(pExpr, pDup, sizeof(*pExpr));
44798           sqlite3_free(pDup);
44799           cnt = 1;
44800           pMatch = 0;
44801           assert( zTab==0 && zDb==0 );
44802           goto lookupname_end_2;
44803         }
44804       } 
44805     }
44806
44807     /* Advance to the next name context.  The loop will exit when either
44808     ** we have a match (cnt>0) or when we run out of name contexts.
44809     */
44810     if( cnt==0 ){
44811       pNC = pNC->pNext;
44812     }
44813   }
44814
44815   /*
44816   ** If X and Y are NULL (in other words if only the column name Z is
44817   ** supplied) and the value of Z is enclosed in double-quotes, then
44818   ** Z is a string literal if it doesn't match any column names.  In that
44819   ** case, we need to return right away and not make any changes to
44820   ** pExpr.
44821   **
44822   ** Because no reference was made to outer contexts, the pNC->nRef
44823   ** fields are not changed in any context.
44824   */
44825   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
44826     sqlite3_free(zCol);
44827     return 0;
44828   }
44829
44830   /*
44831   ** cnt==0 means there was not match.  cnt>1 means there were two or
44832   ** more matches.  Either way, we have an error.
44833   */
44834   if( cnt!=1 ){
44835     char *z = 0;
44836     char *zErr;
44837     zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
44838     if( zDb ){
44839       sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, (char*)0);
44840     }else if( zTab ){
44841       sqlite3SetString(&z, zTab, ".", zCol, (char*)0);
44842     }else{
44843       z = sqlite3StrDup(zCol);
44844     }
44845     if( z ){
44846       sqlite3ErrorMsg(pParse, zErr, z);
44847       sqlite3_free(z);
44848       pTopNC->nErr++;
44849     }else{
44850       db->mallocFailed = 1;
44851     }
44852   }
44853
44854   /* If a column from a table in pSrcList is referenced, then record
44855   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
44856   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
44857   ** column number is greater than the number of bits in the bitmask
44858   ** then set the high-order bit of the bitmask.
44859   */
44860   if( pExpr->iColumn>=0 && pMatch!=0 ){
44861     int n = pExpr->iColumn;
44862     if( n>=sizeof(Bitmask)*8 ){
44863       n = sizeof(Bitmask)*8-1;
44864     }
44865     assert( pMatch->iCursor==pExpr->iTable );
44866     pMatch->colUsed |= ((Bitmask)1)<<n;
44867   }
44868
44869 lookupname_end:
44870   /* Clean up and return
44871   */
44872   sqlite3_free(zDb);
44873   sqlite3_free(zTab);
44874   sqlite3ExprDelete(pExpr->pLeft);
44875   pExpr->pLeft = 0;
44876   sqlite3ExprDelete(pExpr->pRight);
44877   pExpr->pRight = 0;
44878   pExpr->op = TK_COLUMN;
44879 lookupname_end_2:
44880   sqlite3_free(zCol);
44881   if( cnt==1 ){
44882     assert( pNC!=0 );
44883     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
44884     if( pMatch && !pMatch->pSelect ){
44885       pExpr->pTab = pMatch->pTab;
44886     }
44887     /* Increment the nRef value on all name contexts from TopNC up to
44888     ** the point where the name matched. */
44889     for(;;){
44890       assert( pTopNC!=0 );
44891       pTopNC->nRef++;
44892       if( pTopNC==pNC ) break;
44893       pTopNC = pTopNC->pNext;
44894     }
44895     return 0;
44896   } else {
44897     return 1;
44898   }
44899 }
44900
44901 /*
44902 ** This routine is designed as an xFunc for walkExprTree().
44903 **
44904 ** Resolve symbolic names into TK_COLUMN operators for the current
44905 ** node in the expression tree.  Return 0 to continue the search down
44906 ** the tree or 2 to abort the tree walk.
44907 **
44908 ** This routine also does error checking and name resolution for
44909 ** function names.  The operator for aggregate functions is changed
44910 ** to TK_AGG_FUNCTION.
44911 */
44912 static int nameResolverStep(void *pArg, Expr *pExpr){
44913   NameContext *pNC = (NameContext*)pArg;
44914   Parse *pParse;
44915
44916   if( pExpr==0 ) return 1;
44917   assert( pNC!=0 );
44918   pParse = pNC->pParse;
44919
44920   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
44921   ExprSetProperty(pExpr, EP_Resolved);
44922 #ifndef NDEBUG
44923   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
44924     SrcList *pSrcList = pNC->pSrcList;
44925     int i;
44926     for(i=0; i<pNC->pSrcList->nSrc; i++){
44927       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
44928     }
44929   }
44930 #endif
44931   switch( pExpr->op ){
44932     /* Double-quoted strings (ex: "abc") are used as identifiers if
44933     ** possible.  Otherwise they remain as strings.  Single-quoted
44934     ** strings (ex: 'abc') are always string literals.
44935     */
44936     case TK_STRING: {
44937       if( pExpr->token.z[0]=='\'' ) break;
44938       /* Fall thru into the TK_ID case if this is a double-quoted string */
44939     }
44940     /* A lone identifier is the name of a column.
44941     */
44942     case TK_ID: {
44943       lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
44944       return 1;
44945     }
44946   
44947     /* A table name and column name:     ID.ID
44948     ** Or a database, table and column:  ID.ID.ID
44949     */
44950     case TK_DOT: {
44951       Token *pColumn;
44952       Token *pTable;
44953       Token *pDb;
44954       Expr *pRight;
44955
44956       /* if( pSrcList==0 ) break; */
44957       pRight = pExpr->pRight;
44958       if( pRight->op==TK_ID ){
44959         pDb = 0;
44960         pTable = &pExpr->pLeft->token;
44961         pColumn = &pRight->token;
44962       }else{
44963         assert( pRight->op==TK_DOT );
44964         pDb = &pExpr->pLeft->token;
44965         pTable = &pRight->pLeft->token;
44966         pColumn = &pRight->pRight->token;
44967       }
44968       lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
44969       return 1;
44970     }
44971
44972     /* Resolve function names
44973     */
44974     case TK_CONST_FUNC:
44975     case TK_FUNCTION: {
44976       ExprList *pList = pExpr->pList;    /* The argument list */
44977       int n = pList ? pList->nExpr : 0;  /* Number of arguments */
44978       int no_such_func = 0;       /* True if no such function exists */
44979       int wrong_num_args = 0;     /* True if wrong number of arguments */
44980       int is_agg = 0;             /* True if is an aggregate function */
44981       int i;
44982       int auth;                   /* Authorization to use the function */
44983       int nId;                    /* Number of characters in function name */
44984       const char *zId;            /* The function name. */
44985       FuncDef *pDef;              /* Information about the function */
44986       int enc = ENC(pParse->db);  /* The database encoding */
44987
44988       zId = (char*)pExpr->token.z;
44989       nId = pExpr->token.n;
44990       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
44991       if( pDef==0 ){
44992         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
44993         if( pDef==0 ){
44994           no_such_func = 1;
44995         }else{
44996           wrong_num_args = 1;
44997         }
44998       }else{
44999         is_agg = pDef->xFunc==0;
45000       }
45001 #ifndef SQLITE_OMIT_AUTHORIZATION
45002       if( pDef ){
45003         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
45004         if( auth!=SQLITE_OK ){
45005           if( auth==SQLITE_DENY ){
45006             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
45007                                     pDef->zName);
45008             pNC->nErr++;
45009           }
45010           pExpr->op = TK_NULL;
45011           return 1;
45012         }
45013       }
45014 #endif
45015       if( is_agg && !pNC->allowAgg ){
45016         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
45017         pNC->nErr++;
45018         is_agg = 0;
45019       }else if( no_such_func ){
45020         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
45021         pNC->nErr++;
45022       }else if( wrong_num_args ){
45023         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
45024              nId, zId);
45025         pNC->nErr++;
45026       }
45027       if( is_agg ){
45028         pExpr->op = TK_AGG_FUNCTION;
45029         pNC->hasAgg = 1;
45030       }
45031       if( is_agg ) pNC->allowAgg = 0;
45032       for(i=0; pNC->nErr==0 && i<n; i++){
45033         walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC);
45034       }
45035       if( is_agg ) pNC->allowAgg = 1;
45036       /* FIX ME:  Compute pExpr->affinity based on the expected return
45037       ** type of the function 
45038       */
45039       return is_agg;
45040     }
45041 #ifndef SQLITE_OMIT_SUBQUERY
45042     case TK_SELECT:
45043     case TK_EXISTS:
45044 #endif
45045     case TK_IN: {
45046       if( pExpr->pSelect ){
45047         int nRef = pNC->nRef;
45048 #ifndef SQLITE_OMIT_CHECK
45049         if( pNC->isCheck ){
45050           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
45051         }
45052 #endif
45053         sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
45054         assert( pNC->nRef>=nRef );
45055         if( nRef!=pNC->nRef ){
45056           ExprSetProperty(pExpr, EP_VarSelect);
45057         }
45058       }
45059       break;
45060     }
45061 #ifndef SQLITE_OMIT_CHECK
45062     case TK_VARIABLE: {
45063       if( pNC->isCheck ){
45064         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
45065       }
45066       break;
45067     }
45068 #endif
45069   }
45070   return 0;
45071 }
45072
45073 /*
45074 ** This routine walks an expression tree and resolves references to
45075 ** table columns.  Nodes of the form ID.ID or ID resolve into an
45076 ** index to the table in the table list and a column offset.  The 
45077 ** Expr.opcode for such nodes is changed to TK_COLUMN.  The Expr.iTable
45078 ** value is changed to the index of the referenced table in pTabList
45079 ** plus the "base" value.  The base value will ultimately become the
45080 ** VDBE cursor number for a cursor that is pointing into the referenced
45081 ** table.  The Expr.iColumn value is changed to the index of the column 
45082 ** of the referenced table.  The Expr.iColumn value for the special
45083 ** ROWID column is -1.  Any INTEGER PRIMARY KEY column is tried as an
45084 ** alias for ROWID.
45085 **
45086 ** Also resolve function names and check the functions for proper
45087 ** usage.  Make sure all function names are recognized and all functions
45088 ** have the correct number of arguments.  Leave an error message
45089 ** in pParse->zErrMsg if anything is amiss.  Return the number of errors.
45090 **
45091 ** If the expression contains aggregate functions then set the EP_Agg
45092 ** property on the expression.
45093 */
45094 SQLITE_PRIVATE int sqlite3ExprResolveNames( 
45095   NameContext *pNC,       /* Namespace to resolve expressions in. */
45096   Expr *pExpr             /* The expression to be analyzed. */
45097 ){
45098   int savedHasAgg;
45099   if( pExpr==0 ) return 0;
45100 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
45101   if( (pExpr->nHeight+pNC->pParse->nHeight)>SQLITE_MAX_EXPR_DEPTH ){
45102     sqlite3ErrorMsg(pNC->pParse, 
45103        "Expression tree is too large (maximum depth %d)",
45104        SQLITE_MAX_EXPR_DEPTH
45105     );
45106     return 1;
45107   }
45108   pNC->pParse->nHeight += pExpr->nHeight;
45109 #endif
45110   savedHasAgg = pNC->hasAgg;
45111   pNC->hasAgg = 0;
45112   walkExprTree(pExpr, nameResolverStep, pNC);
45113 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
45114   pNC->pParse->nHeight -= pExpr->nHeight;
45115 #endif
45116   if( pNC->nErr>0 ){
45117     ExprSetProperty(pExpr, EP_Error);
45118   }
45119   if( pNC->hasAgg ){
45120     ExprSetProperty(pExpr, EP_Agg);
45121   }else if( savedHasAgg ){
45122     pNC->hasAgg = 1;
45123   }
45124   return ExprHasProperty(pExpr, EP_Error);
45125 }
45126
45127 /*
45128 ** A pointer instance of this structure is used to pass information
45129 ** through walkExprTree into codeSubqueryStep().
45130 */
45131 typedef struct QueryCoder QueryCoder;
45132 struct QueryCoder {
45133   Parse *pParse;       /* The parsing context */
45134   NameContext *pNC;    /* Namespace of first enclosing query */
45135 };
45136
45137 #ifdef SQLITE_TEST
45138   int sqlite3_enable_in_opt = 1;
45139 #else
45140   #define sqlite3_enable_in_opt 1
45141 #endif
45142
45143 /*
45144 ** This function is used by the implementation of the IN (...) operator.
45145 ** It's job is to find or create a b-tree structure that may be used
45146 ** either to test for membership of the (...) set or to iterate through
45147 ** its members, skipping duplicates.
45148 **
45149 ** The cursor opened on the structure (database table, database index 
45150 ** or ephermal table) is stored in pX->iTable before this function returns.
45151 ** The returned value indicates the structure type, as follows:
45152 **
45153 **   IN_INDEX_ROWID - The cursor was opened on a database table.
45154 **   IN_INDEX_INDEX - The cursor was opened on a database indec.
45155 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
45156 **                    populated epheremal table.
45157 **
45158 ** An existing structure may only be used if the SELECT is of the simple
45159 ** form:
45160 **
45161 **     SELECT <column> FROM <table>
45162 **
45163 ** If the mustBeUnique parameter is false, the structure will be used 
45164 ** for fast set membership tests. In this case an epheremal table must 
45165 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
45166 ** be found with <column> as its left-most column.
45167 **
45168 ** If mustBeUnique is true, then the structure will be used to iterate
45169 ** through the set members, skipping any duplicates. In this case an
45170 ** epheremal table must be used unless the selected <column> is guaranteed
45171 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
45172 ** is unique by virtue of a constraint or implicit index.
45173 */
45174 #ifndef SQLITE_OMIT_SUBQUERY
45175 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int mustBeUnique){
45176   Select *p;
45177   int eType = 0;
45178   int iTab = pParse->nTab++;
45179
45180   /* The follwing if(...) expression is true if the SELECT is of the 
45181   ** simple form:
45182   **
45183   **     SELECT <column> FROM <table>
45184   **
45185   ** If this is the case, it may be possible to use an existing table
45186   ** or index instead of generating an epheremal table.
45187   */
45188   if( sqlite3_enable_in_opt
45189    && (p=pX->pSelect) && !p->pPrior
45190    && !p->isDistinct && !p->isAgg && !p->pGroupBy
45191    && p->pSrc && p->pSrc->nSrc==1 && !p->pSrc->a[0].pSelect
45192    && !p->pSrc->a[0].pTab->pSelect                                  
45193    && p->pEList->nExpr==1 && p->pEList->a[0].pExpr->op==TK_COLUMN
45194    && !p->pLimit && !p->pOffset && !p->pWhere
45195   ){
45196     sqlite3 *db = pParse->db;
45197     Index *pIdx;
45198     Expr *pExpr = p->pEList->a[0].pExpr;
45199     int iCol = pExpr->iColumn;
45200     Vdbe *v = sqlite3GetVdbe(pParse);
45201
45202     /* This function is only called from two places. In both cases the vdbe
45203     ** has already been allocated. So assume sqlite3GetVdbe() is always
45204     ** successful here.
45205     */
45206     assert(v);
45207     if( iCol<0 ){
45208       int iMem = pParse->nMem++;
45209       int iAddr;
45210       Table *pTab = p->pSrc->a[0].pTab;
45211       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
45212       sqlite3VdbeUsesBtree(v, iDb);
45213
45214       sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0);
45215       iAddr = sqlite3VdbeAddOp(v, OP_If, 0, iMem);
45216       sqlite3VdbeAddOp(v, OP_MemInt, 1, iMem);
45217
45218       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
45219       eType = IN_INDEX_ROWID;
45220
45221       sqlite3VdbeJumpHere(v, iAddr);
45222     }else{
45223       /* The collation sequence used by the comparison. If an index is to 
45224       ** be used in place of a temp-table, it must be ordered according
45225       ** to this collation sequence.
45226       */
45227       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
45228
45229       /* Check that the affinity that will be used to perform the 
45230       ** comparison is the same as the affinity of the column. If
45231       ** it is not, it is not possible to use any index.
45232       */
45233       Table *pTab = p->pSrc->a[0].pTab;
45234       char aff = comparisonAffinity(pX);
45235       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
45236
45237       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
45238         if( (pIdx->aiColumn[0]==iCol)
45239          && (pReq==sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], -1, 0))
45240          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
45241         ){
45242           int iDb;
45243           int iMem = pParse->nMem++;
45244           int iAddr;
45245           char *pKey;
45246   
45247           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
45248           iDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
45249           sqlite3VdbeUsesBtree(v, iDb);
45250
45251           sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0);
45252           iAddr = sqlite3VdbeAddOp(v, OP_If, 0, iMem);
45253           sqlite3VdbeAddOp(v, OP_MemInt, 1, iMem);
45254   
45255           sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
45256           VdbeComment((v, "# %s", pIdx->zName));
45257           sqlite3VdbeOp3(v,OP_OpenRead,iTab,pIdx->tnum,pKey,P3_KEYINFO_HANDOFF);
45258           eType = IN_INDEX_INDEX;
45259           sqlite3VdbeAddOp(v, OP_SetNumColumns, iTab, pIdx->nColumn);
45260
45261           sqlite3VdbeJumpHere(v, iAddr);
45262         }
45263       }
45264     }
45265   }
45266
45267   if( eType==0 ){
45268     sqlite3CodeSubselect(pParse, pX);
45269     eType = IN_INDEX_EPH;
45270   }else{
45271     pX->iTable = iTab;
45272   }
45273   return eType;
45274 }
45275 #endif
45276
45277 /*
45278 ** Generate code for scalar subqueries used as an expression
45279 ** and IN operators.  Examples:
45280 **
45281 **     (SELECT a FROM b)          -- subquery
45282 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
45283 **     x IN (4,5,11)              -- IN operator with list on right-hand side
45284 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
45285 **
45286 ** The pExpr parameter describes the expression that contains the IN
45287 ** operator or subquery.
45288 */
45289 #ifndef SQLITE_OMIT_SUBQUERY
45290 SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
45291   int testAddr = 0;                       /* One-time test address */
45292   Vdbe *v = sqlite3GetVdbe(pParse);
45293   if( v==0 ) return;
45294
45295
45296   /* This code must be run in its entirety every time it is encountered
45297   ** if any of the following is true:
45298   **
45299   **    *  The right-hand side is a correlated subquery
45300   **    *  The right-hand side is an expression list containing variables
45301   **    *  We are inside a trigger
45302   **
45303   ** If all of the above are false, then we can run this code just once
45304   ** save the results, and reuse the same result on subsequent invocations.
45305   */
45306   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
45307     int mem = pParse->nMem++;
45308     sqlite3VdbeAddOp(v, OP_MemLoad, mem, 0);
45309     testAddr = sqlite3VdbeAddOp(v, OP_If, 0, 0);
45310     assert( testAddr>0 || pParse->db->mallocFailed );
45311     sqlite3VdbeAddOp(v, OP_MemInt, 1, mem);
45312   }
45313
45314   switch( pExpr->op ){
45315     case TK_IN: {
45316       char affinity;
45317       KeyInfo keyInfo;
45318       int addr;        /* Address of OP_OpenEphemeral instruction */
45319
45320       affinity = sqlite3ExprAffinity(pExpr->pLeft);
45321
45322       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
45323       ** expression it is handled the same way. A virtual table is 
45324       ** filled with single-field index keys representing the results
45325       ** from the SELECT or the <exprlist>.
45326       **
45327       ** If the 'x' expression is a column value, or the SELECT...
45328       ** statement returns a column value, then the affinity of that
45329       ** column is used to build the index keys. If both 'x' and the
45330       ** SELECT... statement are columns, then numeric affinity is used
45331       ** if either column has NUMERIC or INTEGER affinity. If neither
45332       ** 'x' nor the SELECT... statement are columns, then numeric affinity
45333       ** is used.
45334       */
45335       pExpr->iTable = pParse->nTab++;
45336       addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, pExpr->iTable, 0);
45337       memset(&keyInfo, 0, sizeof(keyInfo));
45338       keyInfo.nField = 1;
45339       sqlite3VdbeAddOp(v, OP_SetNumColumns, pExpr->iTable, 1);
45340
45341       if( pExpr->pSelect ){
45342         /* Case 1:     expr IN (SELECT ...)
45343         **
45344         ** Generate code to write the results of the select into the temporary
45345         ** table allocated and opened above.
45346         */
45347         int iParm = pExpr->iTable +  (((int)affinity)<<16);
45348         ExprList *pEList;
45349         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
45350         if( sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0) ){
45351           return;
45352         }
45353         pEList = pExpr->pSelect->pEList;
45354         if( pEList && pEList->nExpr>0 ){ 
45355           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
45356               pEList->a[0].pExpr);
45357         }
45358       }else if( pExpr->pList ){
45359         /* Case 2:     expr IN (exprlist)
45360         **
45361         ** For each expression, build an index key from the evaluation and
45362         ** store it in the temporary table. If <expr> is a column, then use
45363         ** that columns affinity when building index keys. If <expr> is not
45364         ** a column, use numeric affinity.
45365         */
45366         int i;
45367         ExprList *pList = pExpr->pList;
45368         struct ExprList_item *pItem;
45369
45370         if( !affinity ){
45371           affinity = SQLITE_AFF_NONE;
45372         }
45373         keyInfo.aColl[0] = pExpr->pLeft->pColl;
45374
45375         /* Loop through each expression in <exprlist>. */
45376         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
45377           Expr *pE2 = pItem->pExpr;
45378
45379           /* If the expression is not constant then we will need to
45380           ** disable the test that was generated above that makes sure
45381           ** this code only executes once.  Because for a non-constant
45382           ** expression we need to rerun this code each time.
45383           */
45384           if( testAddr>0 && !sqlite3ExprIsConstant(pE2) ){
45385             sqlite3VdbeChangeToNoop(v, testAddr-1, 3);
45386             testAddr = 0;
45387           }
45388
45389           /* Evaluate the expression and insert it into the temp table */
45390           sqlite3ExprCode(pParse, pE2);
45391           sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);
45392           sqlite3VdbeAddOp(v, OP_IdxInsert, pExpr->iTable, 0);
45393         }
45394       }
45395       sqlite3VdbeChangeP3(v, addr, (void *)&keyInfo, P3_KEYINFO);
45396       break;
45397     }
45398
45399     case TK_EXISTS:
45400     case TK_SELECT: {
45401       /* This has to be a scalar SELECT.  Generate code to put the
45402       ** value of this select in a memory cell and record the number
45403       ** of the memory cell in iColumn.
45404       */
45405       static const Token one = { (u8*)"1", 0, 1 };
45406       Select *pSel;
45407       int iMem;
45408       int sop;
45409
45410       pExpr->iColumn = iMem = pParse->nMem++;
45411       pSel = pExpr->pSelect;
45412       if( pExpr->op==TK_SELECT ){
45413         sop = SRT_Mem;
45414         sqlite3VdbeAddOp(v, OP_MemNull, iMem, 0);
45415         VdbeComment((v, "# Init subquery result"));
45416       }else{
45417         sop = SRT_Exists;
45418         sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem);
45419         VdbeComment((v, "# Init EXISTS result"));
45420       }
45421       sqlite3ExprDelete(pSel->pLimit);
45422       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
45423       if( sqlite3Select(pParse, pSel, sop, iMem, 0, 0, 0, 0) ){
45424         return;
45425       }
45426       break;
45427     }
45428   }
45429
45430   if( testAddr ){
45431     sqlite3VdbeJumpHere(v, testAddr);
45432   }
45433
45434   return;
45435 }
45436 #endif /* SQLITE_OMIT_SUBQUERY */
45437
45438 /*
45439 ** Duplicate an 8-byte value
45440 */
45441 static char *dup8bytes(Vdbe *v, const char *in){
45442   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
45443   if( out ){
45444     memcpy(out, in, 8);
45445   }
45446   return out;
45447 }
45448
45449 /*
45450 ** Generate an instruction that will put the floating point
45451 ** value described by z[0..n-1] on the stack.
45452 **
45453 ** The z[] string will probably not be zero-terminated.  But the 
45454 ** z[n] character is guaranteed to be something that does not look
45455 ** like the continuation of the number.
45456 */
45457 static void codeReal(Vdbe *v, const char *z, int n, int negateFlag){
45458   assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
45459   if( z ){
45460     double value;
45461     char *zV;
45462     assert( !isdigit(z[n]) );
45463     sqlite3AtoF(z, &value);
45464     if( negateFlag ) value = -value;
45465     zV = dup8bytes(v, (char*)&value);
45466     sqlite3VdbeOp3(v, OP_Real, 0, 0, zV, P3_REAL);
45467   }
45468 }
45469
45470
45471 /*
45472 ** Generate an instruction that will put the integer describe by
45473 ** text z[0..n-1] on the stack.
45474 **
45475 ** The z[] string will probably not be zero-terminated.  But the 
45476 ** z[n] character is guaranteed to be something that does not look
45477 ** like the continuation of the number.
45478 */
45479 static void codeInteger(Vdbe *v, const char *z, int n, int negateFlag){
45480   assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
45481   if( z ){
45482     int i;
45483     assert( !isdigit(z[n]) );
45484     if( sqlite3GetInt32(z, &i) ){
45485       if( negateFlag ) i = -i;
45486       sqlite3VdbeAddOp(v, OP_Integer, i, 0);
45487     }else if( sqlite3FitsIn64Bits(z, negateFlag) ){
45488       i64 value;
45489       char *zV;
45490       sqlite3Atoi64(z, &value);
45491       if( negateFlag ) value = -value;
45492       zV = dup8bytes(v, (char*)&value);
45493       sqlite3VdbeOp3(v, OP_Int64, 0, 0, zV, P3_INT64);
45494     }else{
45495       codeReal(v, z, n, negateFlag);
45496     }
45497   }
45498 }
45499
45500
45501 /*
45502 ** Generate code that will extract the iColumn-th column from
45503 ** table pTab and push that column value on the stack.  There
45504 ** is an open cursor to pTab in iTable.  If iColumn<0 then
45505 ** code is generated that extracts the rowid.
45506 */
45507 SQLITE_PRIVATE void sqlite3ExprCodeGetColumn(Vdbe *v, Table *pTab, int iColumn, int iTable){
45508   if( iColumn<0 ){
45509     int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
45510     sqlite3VdbeAddOp(v, op, iTable, 0);
45511   }else if( pTab==0 ){
45512     sqlite3VdbeAddOp(v, OP_Column, iTable, iColumn);
45513   }else{
45514     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
45515     sqlite3VdbeAddOp(v, op, iTable, iColumn);
45516     sqlite3ColumnDefault(v, pTab, iColumn);
45517 #ifndef SQLITE_OMIT_FLOATING_POINT
45518     if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
45519       sqlite3VdbeAddOp(v, OP_RealAffinity, 0, 0);
45520     }
45521 #endif
45522   }
45523 }
45524
45525 /*
45526 ** Generate code into the current Vdbe to evaluate the given
45527 ** expression and leave the result on the top of stack.
45528 **
45529 ** This code depends on the fact that certain token values (ex: TK_EQ)
45530 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
45531 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
45532 ** the make process cause these values to align.  Assert()s in the code
45533 ** below verify that the numbers are aligned correctly.
45534 */
45535 SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr){
45536   Vdbe *v = pParse->pVdbe;
45537   int op;
45538   int stackChng = 1;    /* Amount of change to stack depth */
45539
45540   if( v==0 ) return;
45541   if( pExpr==0 ){
45542     sqlite3VdbeAddOp(v, OP_Null, 0, 0);
45543     return;
45544   }
45545   op = pExpr->op;
45546   switch( op ){
45547     case TK_AGG_COLUMN: {
45548       AggInfo *pAggInfo = pExpr->pAggInfo;
45549       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
45550       if( !pAggInfo->directMode ){
45551         sqlite3VdbeAddOp(v, OP_MemLoad, pCol->iMem, 0);
45552         break;
45553       }else if( pAggInfo->useSortingIdx ){
45554         sqlite3VdbeAddOp(v, OP_Column, pAggInfo->sortingIdx,
45555                               pCol->iSorterColumn);
45556         break;
45557       }
45558       /* Otherwise, fall thru into the TK_COLUMN case */
45559     }
45560     case TK_COLUMN: {
45561       if( pExpr->iTable<0 ){
45562         /* This only happens when coding check constraints */
45563         assert( pParse->ckOffset>0 );
45564         sqlite3VdbeAddOp(v, OP_Dup, pParse->ckOffset-pExpr->iColumn-1, 1);
45565       }else{
45566         sqlite3ExprCodeGetColumn(v, pExpr->pTab, pExpr->iColumn, pExpr->iTable);
45567       }
45568       break;
45569     }
45570     case TK_INTEGER: {
45571       codeInteger(v, (char*)pExpr->token.z, pExpr->token.n, 0);
45572       break;
45573     }
45574     case TK_FLOAT: {
45575       codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0);
45576       break;
45577     }
45578     case TK_STRING: {
45579       sqlite3DequoteExpr(pParse->db, pExpr);
45580       sqlite3VdbeOp3(v,OP_String8, 0, 0, (char*)pExpr->token.z, pExpr->token.n);
45581       break;
45582     }
45583     case TK_NULL: {
45584       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
45585       break;
45586     }
45587 #ifndef SQLITE_OMIT_BLOB_LITERAL
45588     case TK_BLOB: {
45589       int n;
45590       const char *z;
45591       assert( TK_BLOB==OP_HexBlob );
45592       n = pExpr->token.n - 3;
45593       z = (char*)pExpr->token.z + 2;
45594       assert( n>=0 );
45595       if( n==0 ){
45596         z = "";
45597       }
45598       sqlite3VdbeOp3(v, op, 0, 0, z, n);
45599       break;
45600     }
45601 #endif
45602     case TK_VARIABLE: {
45603       sqlite3VdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
45604       if( pExpr->token.n>1 ){
45605         sqlite3VdbeChangeP3(v, -1, (char*)pExpr->token.z, pExpr->token.n);
45606       }
45607       break;
45608     }
45609     case TK_REGISTER: {
45610       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iTable, 0);
45611       break;
45612     }
45613 #ifndef SQLITE_OMIT_CAST
45614     case TK_CAST: {
45615       /* Expressions of the form:   CAST(pLeft AS token) */
45616       int aff, to_op;
45617       sqlite3ExprCode(pParse, pExpr->pLeft);
45618       aff = sqlite3AffinityType(&pExpr->token);
45619       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
45620       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
45621       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
45622       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
45623       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
45624       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
45625       sqlite3VdbeAddOp(v, to_op, 0, 0);
45626       stackChng = 0;
45627       break;
45628     }
45629 #endif /* SQLITE_OMIT_CAST */
45630     case TK_LT:
45631     case TK_LE:
45632     case TK_GT:
45633     case TK_GE:
45634     case TK_NE:
45635     case TK_EQ: {
45636       assert( TK_LT==OP_Lt );
45637       assert( TK_LE==OP_Le );
45638       assert( TK_GT==OP_Gt );
45639       assert( TK_GE==OP_Ge );
45640       assert( TK_EQ==OP_Eq );
45641       assert( TK_NE==OP_Ne );
45642       sqlite3ExprCode(pParse, pExpr->pLeft);
45643       sqlite3ExprCode(pParse, pExpr->pRight);
45644       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 0, 0);
45645       stackChng = -1;
45646       break;
45647     }
45648     case TK_AND:
45649     case TK_OR:
45650     case TK_PLUS:
45651     case TK_STAR:
45652     case TK_MINUS:
45653     case TK_REM:
45654     case TK_BITAND:
45655     case TK_BITOR:
45656     case TK_SLASH:
45657     case TK_LSHIFT:
45658     case TK_RSHIFT: 
45659     case TK_CONCAT: {
45660       assert( TK_AND==OP_And );
45661       assert( TK_OR==OP_Or );
45662       assert( TK_PLUS==OP_Add );
45663       assert( TK_MINUS==OP_Subtract );
45664       assert( TK_REM==OP_Remainder );
45665       assert( TK_BITAND==OP_BitAnd );
45666       assert( TK_BITOR==OP_BitOr );
45667       assert( TK_SLASH==OP_Divide );
45668       assert( TK_LSHIFT==OP_ShiftLeft );
45669       assert( TK_RSHIFT==OP_ShiftRight );
45670       assert( TK_CONCAT==OP_Concat );
45671       sqlite3ExprCode(pParse, pExpr->pLeft);
45672       sqlite3ExprCode(pParse, pExpr->pRight);
45673       sqlite3VdbeAddOp(v, op, 0, 0);
45674       stackChng = -1;
45675       break;
45676     }
45677     case TK_UMINUS: {
45678       Expr *pLeft = pExpr->pLeft;
45679       assert( pLeft );
45680       if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
45681         Token *p = &pLeft->token;
45682         if( pLeft->op==TK_FLOAT ){
45683           codeReal(v, (char*)p->z, p->n, 1);
45684         }else{
45685           codeInteger(v, (char*)p->z, p->n, 1);
45686         }
45687         break;
45688       }
45689       /* Fall through into TK_NOT */
45690     }
45691     case TK_BITNOT:
45692     case TK_NOT: {
45693       assert( TK_BITNOT==OP_BitNot );
45694       assert( TK_NOT==OP_Not );
45695       sqlite3ExprCode(pParse, pExpr->pLeft);
45696       sqlite3VdbeAddOp(v, op, 0, 0);
45697       stackChng = 0;
45698       break;
45699     }
45700     case TK_ISNULL:
45701     case TK_NOTNULL: {
45702       int dest;
45703       assert( TK_ISNULL==OP_IsNull );
45704       assert( TK_NOTNULL==OP_NotNull );
45705       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
45706       sqlite3ExprCode(pParse, pExpr->pLeft);
45707       dest = sqlite3VdbeCurrentAddr(v) + 2;
45708       sqlite3VdbeAddOp(v, op, 1, dest);
45709       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
45710       stackChng = 0;
45711       break;
45712     }
45713     case TK_AGG_FUNCTION: {
45714       AggInfo *pInfo = pExpr->pAggInfo;
45715       if( pInfo==0 ){
45716         sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
45717             &pExpr->span);
45718       }else{
45719         sqlite3VdbeAddOp(v, OP_MemLoad, pInfo->aFunc[pExpr->iAgg].iMem, 0);
45720       }
45721       break;
45722     }
45723     case TK_CONST_FUNC:
45724     case TK_FUNCTION: {
45725       ExprList *pList = pExpr->pList;
45726       int nExpr = pList ? pList->nExpr : 0;
45727       FuncDef *pDef;
45728       int nId;
45729       const char *zId;
45730       int constMask = 0;
45731       int i;
45732       sqlite3 *db = pParse->db;
45733       u8 enc = ENC(db);
45734       CollSeq *pColl = 0;
45735
45736       zId = (char*)pExpr->token.z;
45737       nId = pExpr->token.n;
45738       pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
45739       assert( pDef!=0 );
45740       nExpr = sqlite3ExprCodeExprList(pParse, pList);
45741 #ifndef SQLITE_OMIT_VIRTUALTABLE
45742       /* Possibly overload the function if the first argument is
45743       ** a virtual table column.
45744       **
45745       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
45746       ** second argument, not the first, as the argument to test to
45747       ** see if it is a column in a virtual table.  This is done because
45748       ** the left operand of infix functions (the operand we want to
45749       ** control overloading) ends up as the second argument to the
45750       ** function.  The expression "A glob B" is equivalent to 
45751       ** "glob(B,A).  We want to use the A in "A glob B" to test
45752       ** for function overloading.  But we use the B term in "glob(B,A)".
45753       */
45754       if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
45755         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[1].pExpr);
45756       }else if( nExpr>0 ){
45757         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[0].pExpr);
45758       }
45759 #endif
45760       for(i=0; i<nExpr && i<32; i++){
45761         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
45762           constMask |= (1<<i);
45763         }
45764         if( pDef->needCollSeq && !pColl ){
45765           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
45766         }
45767       }
45768       if( pDef->needCollSeq ){
45769         if( !pColl ) pColl = pParse->db->pDfltColl; 
45770         sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
45771       }
45772       sqlite3VdbeOp3(v, OP_Function, constMask, nExpr, (char*)pDef, P3_FUNCDEF);
45773       stackChng = 1-nExpr;
45774       break;
45775     }
45776 #ifndef SQLITE_OMIT_SUBQUERY
45777     case TK_EXISTS:
45778     case TK_SELECT: {
45779       if( pExpr->iColumn==0 ){
45780         sqlite3CodeSubselect(pParse, pExpr);
45781       }
45782       sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
45783       VdbeComment((v, "# load subquery result"));
45784       break;
45785     }
45786     case TK_IN: {
45787       int addr;
45788       char affinity;
45789       int ckOffset = pParse->ckOffset;
45790       int eType;
45791       int iLabel = sqlite3VdbeMakeLabel(v);
45792
45793       eType = sqlite3FindInIndex(pParse, pExpr, 0);
45794
45795       /* Figure out the affinity to use to create a key from the results
45796       ** of the expression. affinityStr stores a static string suitable for
45797       ** P3 of OP_MakeRecord.
45798       */
45799       affinity = comparisonAffinity(pExpr);
45800
45801       sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
45802       pParse->ckOffset = (ckOffset ? (ckOffset+1) : 0);
45803
45804       /* Code the <expr> from "<expr> IN (...)". The temporary table
45805       ** pExpr->iTable contains the values that make up the (...) set.
45806       */
45807       sqlite3ExprCode(pParse, pExpr->pLeft);
45808       addr = sqlite3VdbeCurrentAddr(v);
45809       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+4);            /* addr + 0 */
45810       sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
45811       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
45812       sqlite3VdbeAddOp(v, OP_Goto, 0, iLabel);
45813       if( eType==IN_INDEX_ROWID ){
45814         int iAddr = sqlite3VdbeCurrentAddr(v)+3;
45815         sqlite3VdbeAddOp(v, OP_MustBeInt, 1, iAddr);
45816         sqlite3VdbeAddOp(v, OP_NotExists, pExpr->iTable, iAddr);
45817         sqlite3VdbeAddOp(v, OP_Goto, pExpr->iTable, iLabel);
45818       }else{
45819         sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);   /* addr + 4 */
45820         sqlite3VdbeAddOp(v, OP_Found, pExpr->iTable, iLabel);
45821       }
45822       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);                  /* addr + 6 */
45823       sqlite3VdbeResolveLabel(v, iLabel);
45824
45825       break;
45826     }
45827 #endif
45828     case TK_BETWEEN: {
45829       Expr *pLeft = pExpr->pLeft;
45830       struct ExprList_item *pLItem = pExpr->pList->a;
45831       Expr *pRight = pLItem->pExpr;
45832       sqlite3ExprCode(pParse, pLeft);
45833       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
45834       sqlite3ExprCode(pParse, pRight);
45835       codeCompare(pParse, pLeft, pRight, OP_Ge, 0, 0);
45836       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
45837       pLItem++;
45838       pRight = pLItem->pExpr;
45839       sqlite3ExprCode(pParse, pRight);
45840       codeCompare(pParse, pLeft, pRight, OP_Le, 0, 0);
45841       sqlite3VdbeAddOp(v, OP_And, 0, 0);
45842       break;
45843     }
45844     case TK_UPLUS: {
45845       sqlite3ExprCode(pParse, pExpr->pLeft);
45846       stackChng = 0;
45847       break;
45848     }
45849     case TK_CASE: {
45850       int expr_end_label;
45851       int jumpInst;
45852       int nExpr;
45853       int i;
45854       ExprList *pEList;
45855       struct ExprList_item *aListelem;
45856
45857       assert(pExpr->pList);
45858       assert((pExpr->pList->nExpr % 2) == 0);
45859       assert(pExpr->pList->nExpr > 0);
45860       pEList = pExpr->pList;
45861       aListelem = pEList->a;
45862       nExpr = pEList->nExpr;
45863       expr_end_label = sqlite3VdbeMakeLabel(v);
45864       if( pExpr->pLeft ){
45865         sqlite3ExprCode(pParse, pExpr->pLeft);
45866       }
45867       for(i=0; i<nExpr; i=i+2){
45868         sqlite3ExprCode(pParse, aListelem[i].pExpr);
45869         if( pExpr->pLeft ){
45870           sqlite3VdbeAddOp(v, OP_Dup, 1, 1);
45871           jumpInst = codeCompare(pParse, pExpr->pLeft, aListelem[i].pExpr,
45872                                  OP_Ne, 0, 1);
45873           sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
45874         }else{
45875           jumpInst = sqlite3VdbeAddOp(v, OP_IfNot, 1, 0);
45876         }
45877         sqlite3ExprCode(pParse, aListelem[i+1].pExpr);
45878         sqlite3VdbeAddOp(v, OP_Goto, 0, expr_end_label);
45879         sqlite3VdbeJumpHere(v, jumpInst);
45880       }
45881       if( pExpr->pLeft ){
45882         sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
45883       }
45884       if( pExpr->pRight ){
45885         sqlite3ExprCode(pParse, pExpr->pRight);
45886       }else{
45887         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
45888       }
45889       sqlite3VdbeResolveLabel(v, expr_end_label);
45890       break;
45891     }
45892 #ifndef SQLITE_OMIT_TRIGGER
45893     case TK_RAISE: {
45894       if( !pParse->trigStack ){
45895         sqlite3ErrorMsg(pParse,
45896                        "RAISE() may only be used within a trigger-program");
45897         return;
45898       }
45899       if( pExpr->iColumn!=OE_Ignore ){
45900          assert( pExpr->iColumn==OE_Rollback ||
45901                  pExpr->iColumn == OE_Abort ||
45902                  pExpr->iColumn == OE_Fail );
45903          sqlite3DequoteExpr(pParse->db, pExpr);
45904          sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn,
45905                         (char*)pExpr->token.z, pExpr->token.n);
45906       } else {
45907          assert( pExpr->iColumn == OE_Ignore );
45908          sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
45909          sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
45910          VdbeComment((v, "# raise(IGNORE)"));
45911       }
45912       stackChng = 0;
45913       break;
45914     }
45915 #endif
45916   }
45917
45918   if( pParse->ckOffset ){
45919     pParse->ckOffset += stackChng;
45920     assert( pParse->ckOffset );
45921   }
45922 }
45923
45924 #ifndef SQLITE_OMIT_TRIGGER
45925 /*
45926 ** Generate code that evalutes the given expression and leaves the result
45927 ** on the stack.  See also sqlite3ExprCode().
45928 **
45929 ** This routine might also cache the result and modify the pExpr tree
45930 ** so that it will make use of the cached result on subsequent evaluations
45931 ** rather than evaluate the whole expression again.  Trivial expressions are
45932 ** not cached.  If the expression is cached, its result is stored in a 
45933 ** memory location.
45934 */
45935 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr){
45936   Vdbe *v = pParse->pVdbe;
45937   VdbeOp *pOp;
45938   int iMem;
45939   int addr1, addr2;
45940   if( v==0 ) return;
45941   addr1 = sqlite3VdbeCurrentAddr(v);
45942   sqlite3ExprCode(pParse, pExpr);
45943   addr2 = sqlite3VdbeCurrentAddr(v);
45944   if( addr2>addr1+1
45945    || ((pOp = sqlite3VdbeGetOp(v, addr1))!=0 && pOp->opcode==OP_Function) ){
45946     iMem = pExpr->iTable = pParse->nMem++;
45947     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
45948     pExpr->op = TK_REGISTER;
45949   }
45950 }
45951 #endif
45952
45953 /*
45954 ** Generate code that pushes the value of every element of the given
45955 ** expression list onto the stack.
45956 **
45957 ** Return the number of elements pushed onto the stack.
45958 */
45959 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
45960   Parse *pParse,     /* Parsing context */
45961   ExprList *pList    /* The expression list to be coded */
45962 ){
45963   struct ExprList_item *pItem;
45964   int i, n;
45965   if( pList==0 ) return 0;
45966   n = pList->nExpr;
45967   for(pItem=pList->a, i=n; i>0; i--, pItem++){
45968     sqlite3ExprCode(pParse, pItem->pExpr);
45969   }
45970   return n;
45971 }
45972
45973 /*
45974 ** Generate code for a boolean expression such that a jump is made
45975 ** to the label "dest" if the expression is true but execution
45976 ** continues straight thru if the expression is false.
45977 **
45978 ** If the expression evaluates to NULL (neither true nor false), then
45979 ** take the jump if the jumpIfNull flag is true.
45980 **
45981 ** This code depends on the fact that certain token values (ex: TK_EQ)
45982 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
45983 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
45984 ** the make process cause these values to align.  Assert()s in the code
45985 ** below verify that the numbers are aligned correctly.
45986 */
45987 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
45988   Vdbe *v = pParse->pVdbe;
45989   int op = 0;
45990   int ckOffset = pParse->ckOffset;
45991   if( v==0 || pExpr==0 ) return;
45992   op = pExpr->op;
45993   switch( op ){
45994     case TK_AND: {
45995       int d2 = sqlite3VdbeMakeLabel(v);
45996       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
45997       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
45998       sqlite3VdbeResolveLabel(v, d2);
45999       break;
46000     }
46001     case TK_OR: {
46002       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
46003       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
46004       break;
46005     }
46006     case TK_NOT: {
46007       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
46008       break;
46009     }
46010     case TK_LT:
46011     case TK_LE:
46012     case TK_GT:
46013     case TK_GE:
46014     case TK_NE:
46015     case TK_EQ: {
46016       assert( TK_LT==OP_Lt );
46017       assert( TK_LE==OP_Le );
46018       assert( TK_GT==OP_Gt );
46019       assert( TK_GE==OP_Ge );
46020       assert( TK_EQ==OP_Eq );
46021       assert( TK_NE==OP_Ne );
46022       sqlite3ExprCode(pParse, pExpr->pLeft);
46023       sqlite3ExprCode(pParse, pExpr->pRight);
46024       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
46025       break;
46026     }
46027     case TK_ISNULL:
46028     case TK_NOTNULL: {
46029       assert( TK_ISNULL==OP_IsNull );
46030       assert( TK_NOTNULL==OP_NotNull );
46031       sqlite3ExprCode(pParse, pExpr->pLeft);
46032       sqlite3VdbeAddOp(v, op, 1, dest);
46033       break;
46034     }
46035     case TK_BETWEEN: {
46036       /* The expression "x BETWEEN y AND z" is implemented as:
46037       **
46038       ** 1 IF (x < y) GOTO 3
46039       ** 2 IF (x <= z) GOTO <dest>
46040       ** 3 ...
46041       */
46042       int addr;
46043       Expr *pLeft = pExpr->pLeft;
46044       Expr *pRight = pExpr->pList->a[0].pExpr;
46045       sqlite3ExprCode(pParse, pLeft);
46046       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
46047       sqlite3ExprCode(pParse, pRight);
46048       addr = codeCompare(pParse, pLeft, pRight, OP_Lt, 0, !jumpIfNull);
46049
46050       pRight = pExpr->pList->a[1].pExpr;
46051       sqlite3ExprCode(pParse, pRight);
46052       codeCompare(pParse, pLeft, pRight, OP_Le, dest, jumpIfNull);
46053
46054       sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
46055       sqlite3VdbeJumpHere(v, addr);
46056       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
46057       break;
46058     }
46059     default: {
46060       sqlite3ExprCode(pParse, pExpr);
46061       sqlite3VdbeAddOp(v, OP_If, jumpIfNull, dest);
46062       break;
46063     }
46064   }
46065   pParse->ckOffset = ckOffset;
46066 }
46067
46068 /*
46069 ** Generate code for a boolean expression such that a jump is made
46070 ** to the label "dest" if the expression is false but execution
46071 ** continues straight thru if the expression is true.
46072 **
46073 ** If the expression evaluates to NULL (neither true nor false) then
46074 ** jump if jumpIfNull is true or fall through if jumpIfNull is false.
46075 */
46076 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
46077   Vdbe *v = pParse->pVdbe;
46078   int op = 0;
46079   int ckOffset = pParse->ckOffset;
46080   if( v==0 || pExpr==0 ) return;
46081
46082   /* The value of pExpr->op and op are related as follows:
46083   **
46084   **       pExpr->op            op
46085   **       ---------          ----------
46086   **       TK_ISNULL          OP_NotNull
46087   **       TK_NOTNULL         OP_IsNull
46088   **       TK_NE              OP_Eq
46089   **       TK_EQ              OP_Ne
46090   **       TK_GT              OP_Le
46091   **       TK_LE              OP_Gt
46092   **       TK_GE              OP_Lt
46093   **       TK_LT              OP_Ge
46094   **
46095   ** For other values of pExpr->op, op is undefined and unused.
46096   ** The value of TK_ and OP_ constants are arranged such that we
46097   ** can compute the mapping above using the following expression.
46098   ** Assert()s verify that the computation is correct.
46099   */
46100   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
46101
46102   /* Verify correct alignment of TK_ and OP_ constants
46103   */
46104   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
46105   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
46106   assert( pExpr->op!=TK_NE || op==OP_Eq );
46107   assert( pExpr->op!=TK_EQ || op==OP_Ne );
46108   assert( pExpr->op!=TK_LT || op==OP_Ge );
46109   assert( pExpr->op!=TK_LE || op==OP_Gt );
46110   assert( pExpr->op!=TK_GT || op==OP_Le );
46111   assert( pExpr->op!=TK_GE || op==OP_Lt );
46112
46113   switch( pExpr->op ){
46114     case TK_AND: {
46115       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
46116       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
46117       break;
46118     }
46119     case TK_OR: {
46120       int d2 = sqlite3VdbeMakeLabel(v);
46121       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull);
46122       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
46123       sqlite3VdbeResolveLabel(v, d2);
46124       break;
46125     }
46126     case TK_NOT: {
46127       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
46128       break;
46129     }
46130     case TK_LT:
46131     case TK_LE:
46132     case TK_GT:
46133     case TK_GE:
46134     case TK_NE:
46135     case TK_EQ: {
46136       sqlite3ExprCode(pParse, pExpr->pLeft);
46137       sqlite3ExprCode(pParse, pExpr->pRight);
46138       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
46139       break;
46140     }
46141     case TK_ISNULL:
46142     case TK_NOTNULL: {
46143       sqlite3ExprCode(pParse, pExpr->pLeft);
46144       sqlite3VdbeAddOp(v, op, 1, dest);
46145       break;
46146     }
46147     case TK_BETWEEN: {
46148       /* The expression is "x BETWEEN y AND z". It is implemented as:
46149       **
46150       ** 1 IF (x >= y) GOTO 3
46151       ** 2 GOTO <dest>
46152       ** 3 IF (x > z) GOTO <dest>
46153       */
46154       int addr;
46155       Expr *pLeft = pExpr->pLeft;
46156       Expr *pRight = pExpr->pList->a[0].pExpr;
46157       sqlite3ExprCode(pParse, pLeft);
46158       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
46159       sqlite3ExprCode(pParse, pRight);
46160       addr = sqlite3VdbeCurrentAddr(v);
46161       codeCompare(pParse, pLeft, pRight, OP_Ge, addr+3, !jumpIfNull);
46162
46163       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
46164       sqlite3VdbeAddOp(v, OP_Goto, 0, dest);
46165       pRight = pExpr->pList->a[1].pExpr;
46166       sqlite3ExprCode(pParse, pRight);
46167       codeCompare(pParse, pLeft, pRight, OP_Gt, dest, jumpIfNull);
46168       break;
46169     }
46170     default: {
46171       sqlite3ExprCode(pParse, pExpr);
46172       sqlite3VdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
46173       break;
46174     }
46175   }
46176   pParse->ckOffset = ckOffset;
46177 }
46178
46179 /*
46180 ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
46181 ** if they are identical and return FALSE if they differ in any way.
46182 **
46183 ** Sometimes this routine will return FALSE even if the two expressions
46184 ** really are equivalent.  If we cannot prove that the expressions are
46185 ** identical, we return FALSE just to be safe.  So if this routine
46186 ** returns false, then you do not really know for certain if the two
46187 ** expressions are the same.  But if you get a TRUE return, then you
46188 ** can be sure the expressions are the same.  In the places where
46189 ** this routine is used, it does not hurt to get an extra FALSE - that
46190 ** just might result in some slightly slower code.  But returning
46191 ** an incorrect TRUE could lead to a malfunction.
46192 */
46193 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
46194   int i;
46195   if( pA==0||pB==0 ){
46196     return pB==pA;
46197   }
46198   if( pA->op!=pB->op ) return 0;
46199   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
46200   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
46201   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
46202   if( pA->pList ){
46203     if( pB->pList==0 ) return 0;
46204     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
46205     for(i=0; i<pA->pList->nExpr; i++){
46206       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
46207         return 0;
46208       }
46209     }
46210   }else if( pB->pList ){
46211     return 0;
46212   }
46213   if( pA->pSelect || pB->pSelect ) return 0;
46214   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
46215   if( pA->op!=TK_COLUMN && pA->token.z ){
46216     if( pB->token.z==0 ) return 0;
46217     if( pB->token.n!=pA->token.n ) return 0;
46218     if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
46219       return 0;
46220     }
46221   }
46222   return 1;
46223 }
46224
46225
46226 /*
46227 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
46228 ** the new element.  Return a negative number if malloc fails.
46229 */
46230 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
46231   int i;
46232   pInfo->aCol = sqlite3ArrayAllocate(
46233        db,
46234        pInfo->aCol,
46235        sizeof(pInfo->aCol[0]),
46236        3,
46237        &pInfo->nColumn,
46238        &pInfo->nColumnAlloc,
46239        &i
46240   );
46241   return i;
46242 }    
46243
46244 /*
46245 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
46246 ** the new element.  Return a negative number if malloc fails.
46247 */
46248 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
46249   int i;
46250   pInfo->aFunc = sqlite3ArrayAllocate(
46251        db, 
46252        pInfo->aFunc,
46253        sizeof(pInfo->aFunc[0]),
46254        3,
46255        &pInfo->nFunc,
46256        &pInfo->nFuncAlloc,
46257        &i
46258   );
46259   return i;
46260 }    
46261
46262 /*
46263 ** This is an xFunc for walkExprTree() used to implement 
46264 ** sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
46265 ** for additional information.
46266 **
46267 ** This routine analyzes the aggregate function at pExpr.
46268 */
46269 static int analyzeAggregate(void *pArg, Expr *pExpr){
46270   int i;
46271   NameContext *pNC = (NameContext *)pArg;
46272   Parse *pParse = pNC->pParse;
46273   SrcList *pSrcList = pNC->pSrcList;
46274   AggInfo *pAggInfo = pNC->pAggInfo;
46275
46276   switch( pExpr->op ){
46277     case TK_AGG_COLUMN:
46278     case TK_COLUMN: {
46279       /* Check to see if the column is in one of the tables in the FROM
46280       ** clause of the aggregate query */
46281       if( pSrcList ){
46282         struct SrcList_item *pItem = pSrcList->a;
46283         for(i=0; i<pSrcList->nSrc; i++, pItem++){
46284           struct AggInfo_col *pCol;
46285           if( pExpr->iTable==pItem->iCursor ){
46286             /* If we reach this point, it means that pExpr refers to a table
46287             ** that is in the FROM clause of the aggregate query.  
46288             **
46289             ** Make an entry for the column in pAggInfo->aCol[] if there
46290             ** is not an entry there already.
46291             */
46292             int k;
46293             pCol = pAggInfo->aCol;
46294             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
46295               if( pCol->iTable==pExpr->iTable &&
46296                   pCol->iColumn==pExpr->iColumn ){
46297                 break;
46298               }
46299             }
46300             if( (k>=pAggInfo->nColumn)
46301              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
46302             ){
46303               pCol = &pAggInfo->aCol[k];
46304               pCol->pTab = pExpr->pTab;
46305               pCol->iTable = pExpr->iTable;
46306               pCol->iColumn = pExpr->iColumn;
46307               pCol->iMem = pParse->nMem++;
46308               pCol->iSorterColumn = -1;
46309               pCol->pExpr = pExpr;
46310               if( pAggInfo->pGroupBy ){
46311                 int j, n;
46312                 ExprList *pGB = pAggInfo->pGroupBy;
46313                 struct ExprList_item *pTerm = pGB->a;
46314                 n = pGB->nExpr;
46315                 for(j=0; j<n; j++, pTerm++){
46316                   Expr *pE = pTerm->pExpr;
46317                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
46318                       pE->iColumn==pExpr->iColumn ){
46319                     pCol->iSorterColumn = j;
46320                     break;
46321                   }
46322                 }
46323               }
46324               if( pCol->iSorterColumn<0 ){
46325                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
46326               }
46327             }
46328             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
46329             ** because it was there before or because we just created it).
46330             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
46331             ** pAggInfo->aCol[] entry.
46332             */
46333             pExpr->pAggInfo = pAggInfo;
46334             pExpr->op = TK_AGG_COLUMN;
46335             pExpr->iAgg = k;
46336             break;
46337           } /* endif pExpr->iTable==pItem->iCursor */
46338         } /* end loop over pSrcList */
46339       }
46340       return 1;
46341     }
46342     case TK_AGG_FUNCTION: {
46343       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
46344       ** to be ignored */
46345       if( pNC->nDepth==0 ){
46346         /* Check to see if pExpr is a duplicate of another aggregate 
46347         ** function that is already in the pAggInfo structure
46348         */
46349         struct AggInfo_func *pItem = pAggInfo->aFunc;
46350         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
46351           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
46352             break;
46353           }
46354         }
46355         if( i>=pAggInfo->nFunc ){
46356           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
46357           */
46358           u8 enc = ENC(pParse->db);
46359           i = addAggInfoFunc(pParse->db, pAggInfo);
46360           if( i>=0 ){
46361             pItem = &pAggInfo->aFunc[i];
46362             pItem->pExpr = pExpr;
46363             pItem->iMem = pParse->nMem++;
46364             pItem->pFunc = sqlite3FindFunction(pParse->db,
46365                    (char*)pExpr->token.z, pExpr->token.n,
46366                    pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
46367             if( pExpr->flags & EP_Distinct ){
46368               pItem->iDistinct = pParse->nTab++;
46369             }else{
46370               pItem->iDistinct = -1;
46371             }
46372           }
46373         }
46374         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
46375         */
46376         pExpr->iAgg = i;
46377         pExpr->pAggInfo = pAggInfo;
46378         return 1;
46379       }
46380     }
46381   }
46382
46383   /* Recursively walk subqueries looking for TK_COLUMN nodes that need
46384   ** to be changed to TK_AGG_COLUMN.  But increment nDepth so that
46385   ** TK_AGG_FUNCTION nodes in subqueries will be unchanged.
46386   */
46387   if( pExpr->pSelect ){
46388     pNC->nDepth++;
46389     walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC);
46390     pNC->nDepth--;
46391   }
46392   return 0;
46393 }
46394
46395 /*
46396 ** Analyze the given expression looking for aggregate functions and
46397 ** for variables that need to be added to the pParse->aAgg[] array.
46398 ** Make additional entries to the pParse->aAgg[] array as necessary.
46399 **
46400 ** This routine should only be called after the expression has been
46401 ** analyzed by sqlite3ExprResolveNames().
46402 **
46403 ** If errors are seen, leave an error message in zErrMsg and return
46404 ** the number of errors.
46405 */
46406 SQLITE_PRIVATE int sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
46407   int nErr = pNC->pParse->nErr;
46408   walkExprTree(pExpr, analyzeAggregate, pNC);
46409   return pNC->pParse->nErr - nErr;
46410 }
46411
46412 /*
46413 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
46414 ** expression list.  Return the number of errors.
46415 **
46416 ** If an error is found, the analysis is cut short.
46417 */
46418 SQLITE_PRIVATE int sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
46419   struct ExprList_item *pItem;
46420   int i;
46421   int nErr = 0;
46422   if( pList ){
46423     for(pItem=pList->a, i=0; nErr==0 && i<pList->nExpr; i++, pItem++){
46424       nErr += sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
46425     }
46426   }
46427   return nErr;
46428 }
46429
46430 /************** End of expr.c ************************************************/
46431 /************** Begin file alter.c *******************************************/
46432 /*
46433 ** 2005 February 15
46434 **
46435 ** The author disclaims copyright to this source code.  In place of
46436 ** a legal notice, here is a blessing:
46437 **
46438 **    May you do good and not evil.
46439 **    May you find forgiveness for yourself and forgive others.
46440 **    May you share freely, never taking more than you give.
46441 **
46442 *************************************************************************
46443 ** This file contains C code routines that used to generate VDBE code
46444 ** that implements the ALTER TABLE command.
46445 **
46446 ** $Id: alter.c,v 1.35 2007/12/13 21:54:11 drh Exp $
46447 */
46448
46449 /*
46450 ** The code in this file only exists if we are not omitting the
46451 ** ALTER TABLE logic from the build.
46452 */
46453 #ifndef SQLITE_OMIT_ALTERTABLE
46454
46455
46456 /*
46457 ** This function is used by SQL generated to implement the 
46458 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
46459 ** CREATE INDEX command. The second is a table name. The table name in 
46460 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
46461 ** argument and the result returned. Examples:
46462 **
46463 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
46464 **     -> 'CREATE TABLE def(a, b, c)'
46465 **
46466 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
46467 **     -> 'CREATE INDEX i ON def(a, b, c)'
46468 */
46469 static void renameTableFunc(
46470   sqlite3_context *context,
46471   int argc,
46472   sqlite3_value **argv
46473 ){
46474   unsigned char const *zSql = sqlite3_value_text(argv[0]);
46475   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
46476
46477   int token;
46478   Token tname;
46479   unsigned char const *zCsr = zSql;
46480   int len = 0;
46481   char *zRet;
46482
46483   sqlite3 *db = sqlite3_user_data(context);
46484
46485   /* The principle used to locate the table name in the CREATE TABLE 
46486   ** statement is that the table name is the first token that is immediatedly
46487   ** followed by a left parenthesis - TK_LP - or "USING" TK_USING.
46488   */
46489   if( zSql ){
46490     do {
46491       if( !*zCsr ){
46492         /* Ran out of input before finding an opening bracket. Return NULL. */
46493         return;
46494       }
46495
46496       /* Store the token that zCsr points to in tname. */
46497       tname.z = zCsr;
46498       tname.n = len;
46499
46500       /* Advance zCsr to the next token. Store that token type in 'token',
46501       ** and its length in 'len' (to be used next iteration of this loop).
46502       */
46503       do {
46504         zCsr += len;
46505         len = sqlite3GetToken(zCsr, &token);
46506       } while( token==TK_SPACE );
46507       assert( len>0 );
46508     } while( token!=TK_LP && token!=TK_USING );
46509
46510     zRet = sqlite3MPrintf(db, "%.*s%Q%s", tname.z - zSql, zSql, 
46511        zTableName, tname.z+tname.n);
46512     sqlite3_result_text(context, zRet, -1, sqlite3_free);
46513   }
46514 }
46515
46516 #ifndef SQLITE_OMIT_TRIGGER
46517 /* This function is used by SQL generated to implement the
46518 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
46519 ** statement. The second is a table name. The table name in the CREATE 
46520 ** TRIGGER statement is replaced with the third argument and the result 
46521 ** returned. This is analagous to renameTableFunc() above, except for CREATE
46522 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
46523 */
46524 static void renameTriggerFunc(
46525   sqlite3_context *context,
46526   int argc,
46527   sqlite3_value **argv
46528 ){
46529   unsigned char const *zSql = sqlite3_value_text(argv[0]);
46530   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
46531
46532   int token;
46533   Token tname;
46534   int dist = 3;
46535   unsigned char const *zCsr = zSql;
46536   int len = 0;
46537   char *zRet;
46538
46539   sqlite3 *db = sqlite3_user_data(context);
46540
46541   /* The principle used to locate the table name in the CREATE TRIGGER 
46542   ** statement is that the table name is the first token that is immediatedly
46543   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
46544   ** of TK_WHEN, TK_BEGIN or TK_FOR.
46545   */
46546   if( zSql ){
46547     do {
46548
46549       if( !*zCsr ){
46550         /* Ran out of input before finding the table name. Return NULL. */
46551         return;
46552       }
46553
46554       /* Store the token that zCsr points to in tname. */
46555       tname.z = zCsr;
46556       tname.n = len;
46557
46558       /* Advance zCsr to the next token. Store that token type in 'token',
46559       ** and its length in 'len' (to be used next iteration of this loop).
46560       */
46561       do {
46562         zCsr += len;
46563         len = sqlite3GetToken(zCsr, &token);
46564       }while( token==TK_SPACE );
46565       assert( len>0 );
46566
46567       /* Variable 'dist' stores the number of tokens read since the most
46568       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
46569       ** token is read and 'dist' equals 2, the condition stated above
46570       ** to be met.
46571       **
46572       ** Note that ON cannot be a database, table or column name, so
46573       ** there is no need to worry about syntax like 
46574       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
46575       */
46576       dist++;
46577       if( token==TK_DOT || token==TK_ON ){
46578         dist = 0;
46579       }
46580     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
46581
46582     /* Variable tname now contains the token that is the old table-name
46583     ** in the CREATE TRIGGER statement.
46584     */
46585     zRet = sqlite3MPrintf(db, "%.*s%Q%s", tname.z - zSql, zSql, 
46586        zTableName, tname.z+tname.n);
46587     sqlite3_result_text(context, zRet, -1, sqlite3_free);
46588   }
46589 }
46590 #endif   /* !SQLITE_OMIT_TRIGGER */
46591
46592 /*
46593 ** Register built-in functions used to help implement ALTER TABLE
46594 */
46595 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3 *db){
46596   static const struct {
46597      char *zName;
46598      signed char nArg;
46599      void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
46600   } aFuncs[] = {
46601     { "sqlite_rename_table",    2, renameTableFunc},
46602 #ifndef SQLITE_OMIT_TRIGGER
46603     { "sqlite_rename_trigger",  2, renameTriggerFunc},
46604 #endif
46605   };
46606   int i;
46607
46608   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
46609     sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
46610         SQLITE_UTF8, (void *)db, aFuncs[i].xFunc, 0, 0);
46611   }
46612 }
46613
46614 /*
46615 ** Generate the text of a WHERE expression which can be used to select all
46616 ** temporary triggers on table pTab from the sqlite_temp_master table. If
46617 ** table pTab has no temporary triggers, or is itself stored in the 
46618 ** temporary database, NULL is returned.
46619 */
46620 static char *whereTempTriggers(Parse *pParse, Table *pTab){
46621   Trigger *pTrig;
46622   char *zWhere = 0;
46623   char *tmp = 0;
46624   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
46625
46626   /* If the table is not located in the temp-db (in which case NULL is 
46627   ** returned, loop through the tables list of triggers. For each trigger
46628   ** that is not part of the temp-db schema, add a clause to the WHERE 
46629   ** expression being built up in zWhere.
46630   */
46631   if( pTab->pSchema!=pTempSchema ){
46632     sqlite3 *db = pParse->db;
46633     for( pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext ){
46634       if( pTrig->pSchema==pTempSchema ){
46635         if( !zWhere ){
46636           zWhere = sqlite3MPrintf(db, "name=%Q", pTrig->name);
46637         }else{
46638           tmp = zWhere;
46639           zWhere = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, pTrig->name);
46640           sqlite3_free(tmp);
46641         }
46642       }
46643     }
46644   }
46645   return zWhere;
46646 }
46647
46648 /*
46649 ** Generate code to drop and reload the internal representation of table
46650 ** pTab from the database, including triggers and temporary triggers.
46651 ** Argument zName is the name of the table in the database schema at
46652 ** the time the generated code is executed. This can be different from
46653 ** pTab->zName if this function is being called to code part of an 
46654 ** "ALTER TABLE RENAME TO" statement.
46655 */
46656 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
46657   Vdbe *v;
46658   char *zWhere;
46659   int iDb;                   /* Index of database containing pTab */
46660 #ifndef SQLITE_OMIT_TRIGGER
46661   Trigger *pTrig;
46662 #endif
46663
46664   v = sqlite3GetVdbe(pParse);
46665   if( !v ) return;
46666   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
46667   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
46668   assert( iDb>=0 );
46669
46670 #ifndef SQLITE_OMIT_TRIGGER
46671   /* Drop any table triggers from the internal schema. */
46672   for(pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext){
46673     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
46674     assert( iTrigDb==iDb || iTrigDb==1 );
46675     sqlite3VdbeOp3(v, OP_DropTrigger, iTrigDb, 0, pTrig->name, 0);
46676   }
46677 #endif
46678
46679   /* Drop the table and index from the internal schema */
46680   sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
46681
46682   /* Reload the table, index and permanent trigger schemas. */
46683   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
46684   if( !zWhere ) return;
46685   sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, zWhere, P3_DYNAMIC);
46686
46687 #ifndef SQLITE_OMIT_TRIGGER
46688   /* Now, if the table is not stored in the temp database, reload any temp 
46689   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
46690   */
46691   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
46692     sqlite3VdbeOp3(v, OP_ParseSchema, 1, 0, zWhere, P3_DYNAMIC);
46693   }
46694 #endif
46695 }
46696
46697 /*
46698 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
46699 ** command. 
46700 */
46701 SQLITE_PRIVATE void sqlite3AlterRenameTable(
46702   Parse *pParse,            /* Parser context. */
46703   SrcList *pSrc,            /* The table to rename. */
46704   Token *pName              /* The new table name. */
46705 ){
46706   int iDb;                  /* Database that contains the table */
46707   char *zDb;                /* Name of database iDb */
46708   Table *pTab;              /* Table being renamed */
46709   char *zName = 0;          /* NULL-terminated version of pName */ 
46710   sqlite3 *db = pParse->db; /* Database connection */
46711   int nTabName;             /* Number of UTF-8 characters in zTabName */
46712   const char *zTabName;     /* Original name of the table */
46713   Vdbe *v;
46714 #ifndef SQLITE_OMIT_TRIGGER
46715   char *zWhere = 0;         /* Where clause to locate temp triggers */
46716 #endif
46717   int isVirtualRename = 0;  /* True if this is a v-table with an xRename() */
46718   
46719   if( db->mallocFailed ) goto exit_rename_table;
46720   assert( pSrc->nSrc==1 );
46721   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
46722
46723   pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase);
46724   if( !pTab ) goto exit_rename_table;
46725   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
46726   zDb = db->aDb[iDb].zName;
46727
46728   /* Get a NULL terminated version of the new table name. */
46729   zName = sqlite3NameFromToken(db, pName);
46730   if( !zName ) goto exit_rename_table;
46731
46732   /* Check that a table or index named 'zName' does not already exist
46733   ** in database iDb. If so, this is an error.
46734   */
46735   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
46736     sqlite3ErrorMsg(pParse, 
46737         "there is already another table or index with this name: %s", zName);
46738     goto exit_rename_table;
46739   }
46740
46741   /* Make sure it is not a system table being altered, or a reserved name
46742   ** that the table is being renamed to.
46743   */
46744   if( strlen(pTab->zName)>6 && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7) ){
46745     sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
46746     goto exit_rename_table;
46747   }
46748   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
46749     goto exit_rename_table;
46750   }
46751
46752 #ifndef SQLITE_OMIT_VIEW
46753   if( pTab->pSelect ){
46754     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
46755     goto exit_rename_table;
46756   }
46757 #endif
46758
46759 #ifndef SQLITE_OMIT_AUTHORIZATION
46760   /* Invoke the authorization callback. */
46761   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
46762     goto exit_rename_table;
46763   }
46764 #endif
46765
46766 #ifndef SQLITE_OMIT_VIRTUALTABLE
46767   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
46768     goto exit_rename_table;
46769   }
46770   if( IsVirtual(pTab) && pTab->pMod->pModule->xRename ){
46771     isVirtualRename = 1;
46772   }
46773 #endif
46774
46775   /* Begin a transaction and code the VerifyCookie for database iDb. 
46776   ** Then modify the schema cookie (since the ALTER TABLE modifies the
46777   ** schema). Open a statement transaction if the table is a virtual
46778   ** table.
46779   */
46780   v = sqlite3GetVdbe(pParse);
46781   if( v==0 ){
46782     goto exit_rename_table;
46783   }
46784   sqlite3BeginWriteOperation(pParse, isVirtualRename, iDb);
46785   sqlite3ChangeCookie(db, v, iDb);
46786
46787   /* If this is a virtual table, invoke the xRename() function if
46788   ** one is defined. The xRename() callback will modify the names
46789   ** of any resources used by the v-table implementation (including other
46790   ** SQLite tables) that are identified by the name of the virtual table.
46791   */
46792 #ifndef SQLITE_OMIT_VIRTUALTABLE
46793   if( isVirtualRename ){
46794     sqlite3VdbeOp3(v, OP_String8, 0, 0, zName, 0);
46795     sqlite3VdbeOp3(v, OP_VRename, 0, 0, (const char*)pTab->pVtab, P3_VTAB);
46796   }
46797 #endif
46798
46799   /* figure out how many UTF-8 characters are in zName */
46800   zTabName = pTab->zName;
46801   nTabName = sqlite3Utf8CharLen(zTabName, -1);
46802
46803   /* Modify the sqlite_master table to use the new table name. */
46804   sqlite3NestedParse(pParse,
46805       "UPDATE %Q.%s SET "
46806 #ifdef SQLITE_OMIT_TRIGGER
46807           "sql = sqlite_rename_table(sql, %Q), "
46808 #else
46809           "sql = CASE "
46810             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
46811             "ELSE sqlite_rename_table(sql, %Q) END, "
46812 #endif
46813           "tbl_name = %Q, "
46814           "name = CASE "
46815             "WHEN type='table' THEN %Q "
46816             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
46817              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
46818             "ELSE name END "
46819       "WHERE tbl_name=%Q AND "
46820           "(type='table' OR type='index' OR type='trigger');", 
46821       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
46822 #ifndef SQLITE_OMIT_TRIGGER
46823       zName,
46824 #endif
46825       zName, nTabName, zTabName
46826   );
46827
46828 #ifndef SQLITE_OMIT_AUTOINCREMENT
46829   /* If the sqlite_sequence table exists in this database, then update 
46830   ** it with the new table name.
46831   */
46832   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
46833     sqlite3NestedParse(pParse,
46834         "UPDATE %Q.sqlite_sequence set name = %Q WHERE name = %Q",
46835         zDb, zName, pTab->zName);
46836   }
46837 #endif
46838
46839 #ifndef SQLITE_OMIT_TRIGGER
46840   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
46841   ** table. Don't do this if the table being ALTERed is itself located in
46842   ** the temp database.
46843   */
46844   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
46845     sqlite3NestedParse(pParse, 
46846         "UPDATE sqlite_temp_master SET "
46847             "sql = sqlite_rename_trigger(sql, %Q), "
46848             "tbl_name = %Q "
46849             "WHERE %s;", zName, zName, zWhere);
46850     sqlite3_free(zWhere);
46851   }
46852 #endif
46853
46854   /* Drop and reload the internal table schema. */
46855   reloadTableSchema(pParse, pTab, zName);
46856
46857 exit_rename_table:
46858   sqlite3SrcListDelete(pSrc);
46859   sqlite3_free(zName);
46860 }
46861
46862
46863 /*
46864 ** This function is called after an "ALTER TABLE ... ADD" statement
46865 ** has been parsed. Argument pColDef contains the text of the new
46866 ** column definition.
46867 **
46868 ** The Table structure pParse->pNewTable was extended to include
46869 ** the new column during parsing.
46870 */
46871 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
46872   Table *pNew;              /* Copy of pParse->pNewTable */
46873   Table *pTab;              /* Table being altered */
46874   int iDb;                  /* Database number */
46875   const char *zDb;          /* Database name */
46876   const char *zTab;         /* Table name */
46877   char *zCol;               /* Null-terminated column definition */
46878   Column *pCol;             /* The new column */
46879   Expr *pDflt;              /* Default value for the new column */
46880   sqlite3 *db;              /* The database connection; */
46881
46882   if( pParse->nErr ) return;
46883   pNew = pParse->pNewTable;
46884   assert( pNew );
46885
46886   db = pParse->db;
46887   assert( sqlite3BtreeHoldsAllMutexes(db) );
46888   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
46889   zDb = db->aDb[iDb].zName;
46890   zTab = pNew->zName;
46891   pCol = &pNew->aCol[pNew->nCol-1];
46892   pDflt = pCol->pDflt;
46893   pTab = sqlite3FindTable(db, zTab, zDb);
46894   assert( pTab );
46895
46896 #ifndef SQLITE_OMIT_AUTHORIZATION
46897   /* Invoke the authorization callback. */
46898   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
46899     return;
46900   }
46901 #endif
46902
46903   /* If the default value for the new column was specified with a 
46904   ** literal NULL, then set pDflt to 0. This simplifies checking
46905   ** for an SQL NULL default below.
46906   */
46907   if( pDflt && pDflt->op==TK_NULL ){
46908     pDflt = 0;
46909   }
46910
46911   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
46912   ** If there is a NOT NULL constraint, then the default value for the
46913   ** column must not be NULL.
46914   */
46915   if( pCol->isPrimKey ){
46916     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
46917     return;
46918   }
46919   if( pNew->pIndex ){
46920     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
46921     return;
46922   }
46923   if( pCol->notNull && !pDflt ){
46924     sqlite3ErrorMsg(pParse, 
46925         "Cannot add a NOT NULL column with default value NULL");
46926     return;
46927   }
46928
46929   /* Ensure the default expression is something that sqlite3ValueFromExpr()
46930   ** can handle (i.e. not CURRENT_TIME etc.)
46931   */
46932   if( pDflt ){
46933     sqlite3_value *pVal;
46934     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
46935       db->mallocFailed = 1;
46936       return;
46937     }
46938     if( !pVal ){
46939       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
46940       return;
46941     }
46942     sqlite3ValueFree(pVal);
46943   }
46944
46945   /* Modify the CREATE TABLE statement. */
46946   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
46947   if( zCol ){
46948     char *zEnd = &zCol[pColDef->n-1];
46949     while( (zEnd>zCol && *zEnd==';') || isspace(*(unsigned char *)zEnd) ){
46950       *zEnd-- = '\0';
46951     }
46952     sqlite3NestedParse(pParse, 
46953         "UPDATE %Q.%s SET "
46954           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
46955         "WHERE type = 'table' AND name = %Q", 
46956       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
46957       zTab
46958     );
46959     sqlite3_free(zCol);
46960   }
46961
46962   /* If the default value of the new column is NULL, then set the file
46963   ** format to 2. If the default value of the new column is not NULL,
46964   ** the file format becomes 3.
46965   */
46966   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
46967
46968   /* Reload the schema of the modified table. */
46969   reloadTableSchema(pParse, pTab, pTab->zName);
46970 }
46971
46972 /*
46973 ** This function is called by the parser after the table-name in
46974 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
46975 ** pSrc is the full-name of the table being altered.
46976 **
46977 ** This routine makes a (partial) copy of the Table structure
46978 ** for the table being altered and sets Parse.pNewTable to point
46979 ** to it. Routines called by the parser as the column definition
46980 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
46981 ** the copy. The copy of the Table structure is deleted by tokenize.c 
46982 ** after parsing is finished.
46983 **
46984 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
46985 ** coding the "ALTER TABLE ... ADD" statement.
46986 */
46987 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
46988   Table *pNew;
46989   Table *pTab;
46990   Vdbe *v;
46991   int iDb;
46992   int i;
46993   int nAlloc;
46994   sqlite3 *db = pParse->db;
46995
46996   /* Look up the table being altered. */
46997   assert( pParse->pNewTable==0 );
46998   assert( sqlite3BtreeHoldsAllMutexes(db) );
46999   if( db->mallocFailed ) goto exit_begin_add_column;
47000   pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase);
47001   if( !pTab ) goto exit_begin_add_column;
47002
47003 #ifndef SQLITE_OMIT_VIRTUALTABLE
47004   if( IsVirtual(pTab) ){
47005     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
47006     goto exit_begin_add_column;
47007   }
47008 #endif
47009
47010   /* Make sure this is not an attempt to ALTER a view. */
47011   if( pTab->pSelect ){
47012     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
47013     goto exit_begin_add_column;
47014   }
47015
47016   assert( pTab->addColOffset>0 );
47017   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
47018
47019   /* Put a copy of the Table struct in Parse.pNewTable for the
47020   ** sqlite3AddColumn() function and friends to modify.
47021   */
47022   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
47023   if( !pNew ) goto exit_begin_add_column;
47024   pParse->pNewTable = pNew;
47025   pNew->nRef = 1;
47026   pNew->nCol = pTab->nCol;
47027   assert( pNew->nCol>0 );
47028   nAlloc = (((pNew->nCol-1)/8)*8)+8;
47029   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
47030   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
47031   pNew->zName = sqlite3DbStrDup(db, pTab->zName);
47032   if( !pNew->aCol || !pNew->zName ){
47033     db->mallocFailed = 1;
47034     goto exit_begin_add_column;
47035   }
47036   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
47037   for(i=0; i<pNew->nCol; i++){
47038     Column *pCol = &pNew->aCol[i];
47039     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
47040     pCol->zColl = 0;
47041     pCol->zType = 0;
47042     pCol->pDflt = 0;
47043   }
47044   pNew->pSchema = db->aDb[iDb].pSchema;
47045   pNew->addColOffset = pTab->addColOffset;
47046   pNew->nRef = 1;
47047
47048   /* Begin a transaction and increment the schema cookie.  */
47049   sqlite3BeginWriteOperation(pParse, 0, iDb);
47050   v = sqlite3GetVdbe(pParse);
47051   if( !v ) goto exit_begin_add_column;
47052   sqlite3ChangeCookie(db, v, iDb);
47053
47054 exit_begin_add_column:
47055   sqlite3SrcListDelete(pSrc);
47056   return;
47057 }
47058 #endif  /* SQLITE_ALTER_TABLE */
47059
47060 /************** End of alter.c ***********************************************/
47061 /************** Begin file analyze.c *****************************************/
47062 /*
47063 ** 2005 July 8
47064 **
47065 ** The author disclaims copyright to this source code.  In place of
47066 ** a legal notice, here is a blessing:
47067 **
47068 **    May you do good and not evil.
47069 **    May you find forgiveness for yourself and forgive others.
47070 **    May you share freely, never taking more than you give.
47071 **
47072 *************************************************************************
47073 ** This file contains code associated with the ANALYZE command.
47074 **
47075 ** @(#) $Id: analyze.c,v 1.24 2007/11/15 13:10:23 danielk1977 Exp $
47076 */
47077 #ifndef SQLITE_OMIT_ANALYZE
47078
47079 /*
47080 ** This routine generates code that opens the sqlite_stat1 table on cursor
47081 ** iStatCur.
47082 **
47083 ** If the sqlite_stat1 tables does not previously exist, it is created.
47084 ** If it does previously exist, all entires associated with table zWhere
47085 ** are removed.  If zWhere==0 then all entries are removed.
47086 */
47087 static void openStatTable(
47088   Parse *pParse,          /* Parsing context */
47089   int iDb,                /* The database we are looking in */
47090   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
47091   const char *zWhere      /* Delete entries associated with this table */
47092 ){
47093   sqlite3 *db = pParse->db;
47094   Db *pDb;
47095   int iRootPage;
47096   Table *pStat;
47097   Vdbe *v = sqlite3GetVdbe(pParse);
47098
47099   if( v==0 ) return;
47100   assert( sqlite3BtreeHoldsAllMutexes(db) );
47101   assert( sqlite3VdbeDb(v)==db );
47102   pDb = &db->aDb[iDb];
47103   if( (pStat = sqlite3FindTable(db, "sqlite_stat1", pDb->zName))==0 ){
47104     /* The sqlite_stat1 tables does not exist.  Create it.  
47105     ** Note that a side-effect of the CREATE TABLE statement is to leave
47106     ** the rootpage of the new table on the top of the stack.  This is
47107     ** important because the OpenWrite opcode below will be needing it. */
47108     sqlite3NestedParse(pParse,
47109       "CREATE TABLE %Q.sqlite_stat1(tbl,idx,stat)",
47110       pDb->zName
47111     );
47112     iRootPage = 0;  /* Cause rootpage to be taken from top of stack */
47113   }else if( zWhere ){
47114     /* The sqlite_stat1 table exists.  Delete all entries associated with
47115     ** the table zWhere. */
47116     sqlite3NestedParse(pParse,
47117        "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q",
47118        pDb->zName, zWhere
47119     );
47120     iRootPage = pStat->tnum;
47121   }else{
47122     /* The sqlite_stat1 table already exists.  Delete all rows. */
47123     iRootPage = pStat->tnum;
47124     sqlite3VdbeAddOp(v, OP_Clear, pStat->tnum, iDb);
47125   }
47126
47127   /* Open the sqlite_stat1 table for writing. Unless it was created
47128   ** by this vdbe program, lock it for writing at the shared-cache level. 
47129   ** If this vdbe did create the sqlite_stat1 table, then it must have 
47130   ** already obtained a schema-lock, making the write-lock redundant.
47131   */
47132   if( iRootPage>0 ){
47133     sqlite3TableLock(pParse, iDb, iRootPage, 1, "sqlite_stat1");
47134   }
47135   sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
47136   sqlite3VdbeAddOp(v, OP_OpenWrite, iStatCur, iRootPage);
47137   sqlite3VdbeAddOp(v, OP_SetNumColumns, iStatCur, 3);
47138 }
47139
47140 /*
47141 ** Generate code to do an analysis of all indices associated with
47142 ** a single table.
47143 */
47144 static void analyzeOneTable(
47145   Parse *pParse,   /* Parser context */
47146   Table *pTab,     /* Table whose indices are to be analyzed */
47147   int iStatCur,    /* Cursor that writes to the sqlite_stat1 table */
47148   int iMem         /* Available memory locations begin here */
47149 ){
47150   Index *pIdx;     /* An index to being analyzed */
47151   int iIdxCur;     /* Cursor number for index being analyzed */
47152   int nCol;        /* Number of columns in the index */
47153   Vdbe *v;         /* The virtual machine being built up */
47154   int i;           /* Loop counter */
47155   int topOfLoop;   /* The top of the loop */
47156   int endOfLoop;   /* The end of the loop */
47157   int addr;        /* The address of an instruction */
47158   int iDb;         /* Index of database containing pTab */
47159
47160   v = sqlite3GetVdbe(pParse);
47161   if( v==0 || pTab==0 || pTab->pIndex==0 ){
47162     /* Do no analysis for tables that have no indices */
47163     return;
47164   }
47165   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
47166   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
47167   assert( iDb>=0 );
47168 #ifndef SQLITE_OMIT_AUTHORIZATION
47169   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
47170       pParse->db->aDb[iDb].zName ) ){
47171     return;
47172   }
47173 #endif
47174
47175   /* Establish a read-lock on the table at the shared-cache level. */
47176   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
47177
47178   iIdxCur = pParse->nTab;
47179   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
47180     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
47181
47182     /* Open a cursor to the index to be analyzed
47183     */
47184     assert( iDb==sqlite3SchemaToIndex(pParse->db, pIdx->pSchema) );
47185     sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
47186     VdbeComment((v, "# %s", pIdx->zName));
47187     sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum,
47188         (char *)pKey, P3_KEYINFO_HANDOFF);
47189     nCol = pIdx->nColumn;
47190     if( iMem+nCol*2>=pParse->nMem ){
47191       pParse->nMem = iMem+nCol*2+1;
47192     }
47193     sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, nCol+1);
47194
47195     /* Memory cells are used as follows:
47196     **
47197     **    mem[iMem]:             The total number of rows in the table.
47198     **    mem[iMem+1]:           Number of distinct values in column 1
47199     **    ...
47200     **    mem[iMem+nCol]:        Number of distinct values in column N
47201     **    mem[iMem+nCol+1]       Last observed value of column 1
47202     **    ...
47203     **    mem[iMem+nCol+nCol]:   Last observed value of column N
47204     **
47205     ** Cells iMem through iMem+nCol are initialized to 0.  The others
47206     ** are initialized to NULL.
47207     */
47208     for(i=0; i<=nCol; i++){
47209       sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem+i);
47210     }
47211     for(i=0; i<nCol; i++){
47212       sqlite3VdbeAddOp(v, OP_MemNull, iMem+nCol+i+1, 0);
47213     }
47214
47215     /* Do the analysis.
47216     */
47217     endOfLoop = sqlite3VdbeMakeLabel(v);
47218     sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, endOfLoop);
47219     topOfLoop = sqlite3VdbeCurrentAddr(v);
47220     sqlite3VdbeAddOp(v, OP_MemIncr, 1, iMem);
47221     for(i=0; i<nCol; i++){
47222       sqlite3VdbeAddOp(v, OP_Column, iIdxCur, i);
47223       sqlite3VdbeAddOp(v, OP_MemLoad, iMem+nCol+i+1, 0);
47224       sqlite3VdbeAddOp(v, OP_Ne, 0x100, 0);
47225     }
47226     sqlite3VdbeAddOp(v, OP_Goto, 0, endOfLoop);
47227     for(i=0; i<nCol; i++){
47228       addr = sqlite3VdbeAddOp(v, OP_MemIncr, 1, iMem+i+1);
47229       sqlite3VdbeChangeP2(v, topOfLoop + 3*i + 3, addr);
47230       sqlite3VdbeAddOp(v, OP_Column, iIdxCur, i);
47231       sqlite3VdbeAddOp(v, OP_MemStore, iMem+nCol+i+1, 1);
47232     }
47233     sqlite3VdbeResolveLabel(v, endOfLoop);
47234     sqlite3VdbeAddOp(v, OP_Next, iIdxCur, topOfLoop);
47235     sqlite3VdbeAddOp(v, OP_Close, iIdxCur, 0);
47236
47237     /* Store the results.  
47238     **
47239     ** The result is a single row of the sqlite_stat1 table.  The first
47240     ** two columns are the names of the table and index.  The third column
47241     ** is a string composed of a list of integer statistics about the
47242     ** index.  The first integer in the list is the total number of entires
47243     ** in the index.  There is one additional integer in the list for each
47244     ** column of the table.  This additional integer is a guess of how many
47245     ** rows of the table the index will select.  If D is the count of distinct
47246     ** values and K is the total number of rows, then the integer is computed
47247     ** as:
47248     **
47249     **        I = (K+D-1)/D
47250     **
47251     ** If K==0 then no entry is made into the sqlite_stat1 table.  
47252     ** If K>0 then it is always the case the D>0 so division by zero
47253     ** is never possible.
47254     */
47255     sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0);
47256     addr = sqlite3VdbeAddOp(v, OP_IfNot, 0, 0);
47257     sqlite3VdbeAddOp(v, OP_NewRowid, iStatCur, 0);
47258     sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
47259     sqlite3VdbeOp3(v, OP_String8, 0, 0, pIdx->zName, 0);
47260     sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0);
47261     sqlite3VdbeOp3(v, OP_String8, 0, 0, " ", 0);
47262     for(i=0; i<nCol; i++){
47263       sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0);
47264       sqlite3VdbeAddOp(v, OP_MemLoad, iMem+i+1, 0);
47265       sqlite3VdbeAddOp(v, OP_Add, 0, 0);
47266       sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
47267       sqlite3VdbeAddOp(v, OP_MemLoad, iMem+i+1, 0);
47268       sqlite3VdbeAddOp(v, OP_Divide, 0, 0);
47269       sqlite3VdbeAddOp(v, OP_ToInt, 0, 0);
47270       if( i==nCol-1 ){
47271         sqlite3VdbeAddOp(v, OP_Concat, nCol*2-1, 0);
47272       }else{
47273         sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
47274       }
47275     }
47276     sqlite3VdbeOp3(v, OP_MakeRecord, 3, 0, "aaa", 0);
47277     sqlite3VdbeAddOp(v, OP_Insert, iStatCur, OPFLAG_APPEND);
47278     sqlite3VdbeJumpHere(v, addr);
47279   }
47280 }
47281
47282 /*
47283 ** Generate code that will cause the most recent index analysis to
47284 ** be laoded into internal hash tables where is can be used.
47285 */
47286 static void loadAnalysis(Parse *pParse, int iDb){
47287   Vdbe *v = sqlite3GetVdbe(pParse);
47288   if( v ){
47289     sqlite3VdbeAddOp(v, OP_LoadAnalysis, iDb, 0);
47290   }
47291 }
47292
47293 /*
47294 ** Generate code that will do an analysis of an entire database
47295 */
47296 static void analyzeDatabase(Parse *pParse, int iDb){
47297   sqlite3 *db = pParse->db;
47298   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
47299   HashElem *k;
47300   int iStatCur;
47301   int iMem;
47302
47303   sqlite3BeginWriteOperation(pParse, 0, iDb);
47304   iStatCur = pParse->nTab++;
47305   openStatTable(pParse, iDb, iStatCur, 0);
47306   iMem = pParse->nMem;
47307   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
47308     Table *pTab = (Table*)sqliteHashData(k);
47309     analyzeOneTable(pParse, pTab, iStatCur, iMem);
47310   }
47311   loadAnalysis(pParse, iDb);
47312 }
47313
47314 /*
47315 ** Generate code that will do an analysis of a single table in
47316 ** a database.
47317 */
47318 static void analyzeTable(Parse *pParse, Table *pTab){
47319   int iDb;
47320   int iStatCur;
47321
47322   assert( pTab!=0 );
47323   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
47324   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
47325   sqlite3BeginWriteOperation(pParse, 0, iDb);
47326   iStatCur = pParse->nTab++;
47327   openStatTable(pParse, iDb, iStatCur, pTab->zName);
47328   analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem);
47329   loadAnalysis(pParse, iDb);
47330 }
47331
47332 /*
47333 ** Generate code for the ANALYZE command.  The parser calls this routine
47334 ** when it recognizes an ANALYZE command.
47335 **
47336 **        ANALYZE                            -- 1
47337 **        ANALYZE  <database>                -- 2
47338 **        ANALYZE  ?<database>.?<tablename>  -- 3
47339 **
47340 ** Form 1 causes all indices in all attached databases to be analyzed.
47341 ** Form 2 analyzes all indices the single database named.
47342 ** Form 3 analyzes all indices associated with the named table.
47343 */
47344 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
47345   sqlite3 *db = pParse->db;
47346   int iDb;
47347   int i;
47348   char *z, *zDb;
47349   Table *pTab;
47350   Token *pTableName;
47351
47352   /* Read the database schema. If an error occurs, leave an error message
47353   ** and code in pParse and return NULL. */
47354   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
47355   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
47356     return;
47357   }
47358
47359   if( pName1==0 ){
47360     /* Form 1:  Analyze everything */
47361     for(i=0; i<db->nDb; i++){
47362       if( i==1 ) continue;  /* Do not analyze the TEMP database */
47363       analyzeDatabase(pParse, i);
47364     }
47365   }else if( pName2==0 || pName2->n==0 ){
47366     /* Form 2:  Analyze the database or table named */
47367     iDb = sqlite3FindDb(db, pName1);
47368     if( iDb>=0 ){
47369       analyzeDatabase(pParse, iDb);
47370     }else{
47371       z = sqlite3NameFromToken(db, pName1);
47372       if( z ){
47373         pTab = sqlite3LocateTable(pParse, z, 0);
47374         sqlite3_free(z);
47375         if( pTab ){
47376           analyzeTable(pParse, pTab);
47377         }
47378       }
47379     }
47380   }else{
47381     /* Form 3: Analyze the fully qualified table name */
47382     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
47383     if( iDb>=0 ){
47384       zDb = db->aDb[iDb].zName;
47385       z = sqlite3NameFromToken(db, pTableName);
47386       if( z ){
47387         pTab = sqlite3LocateTable(pParse, z, zDb);
47388         sqlite3_free(z);
47389         if( pTab ){
47390           analyzeTable(pParse, pTab);
47391         }
47392       }
47393     }   
47394   }
47395 }
47396
47397 /*
47398 ** Used to pass information from the analyzer reader through to the
47399 ** callback routine.
47400 */
47401 typedef struct analysisInfo analysisInfo;
47402 struct analysisInfo {
47403   sqlite3 *db;
47404   const char *zDatabase;
47405 };
47406
47407 /*
47408 ** This callback is invoked once for each index when reading the
47409 ** sqlite_stat1 table.  
47410 **
47411 **     argv[0] = name of the index
47412 **     argv[1] = results of analysis - on integer for each column
47413 */
47414 static int analysisLoader(void *pData, int argc, char **argv, char **azNotUsed){
47415   analysisInfo *pInfo = (analysisInfo*)pData;
47416   Index *pIndex;
47417   int i, c;
47418   unsigned int v;
47419   const char *z;
47420
47421   assert( argc==2 );
47422   if( argv==0 || argv[0]==0 || argv[1]==0 ){
47423     return 0;
47424   }
47425   pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
47426   if( pIndex==0 ){
47427     return 0;
47428   }
47429   z = argv[1];
47430   for(i=0; *z && i<=pIndex->nColumn; i++){
47431     v = 0;
47432     while( (c=z[0])>='0' && c<='9' ){
47433       v = v*10 + c - '0';
47434       z++;
47435     }
47436     pIndex->aiRowEst[i] = v;
47437     if( *z==' ' ) z++;
47438   }
47439   return 0;
47440 }
47441
47442 /*
47443 ** Load the content of the sqlite_stat1 table into the index hash tables.
47444 */
47445 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
47446   analysisInfo sInfo;
47447   HashElem *i;
47448   char *zSql;
47449   int rc;
47450
47451   assert( iDb>=0 && iDb<db->nDb );
47452   assert( db->aDb[iDb].pBt!=0 );
47453   assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
47454
47455   /* Clear any prior statistics */
47456   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
47457     Index *pIdx = sqliteHashData(i);
47458     sqlite3DefaultRowEst(pIdx);
47459   }
47460
47461   /* Check to make sure the sqlite_stat1 table existss */
47462   sInfo.db = db;
47463   sInfo.zDatabase = db->aDb[iDb].zName;
47464   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
47465      return SQLITE_ERROR;
47466   }
47467
47468
47469   /* Load new statistics out of the sqlite_stat1 table */
47470   zSql = sqlite3MPrintf(db, "SELECT idx, stat FROM %Q.sqlite_stat1",
47471                         sInfo.zDatabase);
47472   sqlite3SafetyOff(db);
47473   rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
47474   sqlite3SafetyOn(db);
47475   sqlite3_free(zSql);
47476   return rc;
47477 }
47478
47479
47480 #endif /* SQLITE_OMIT_ANALYZE */
47481
47482 /************** End of analyze.c *********************************************/
47483 /************** Begin file attach.c ******************************************/
47484 /*
47485 ** 2003 April 6
47486 **
47487 ** The author disclaims copyright to this source code.  In place of
47488 ** a legal notice, here is a blessing:
47489 **
47490 **    May you do good and not evil.
47491 **    May you find forgiveness for yourself and forgive others.
47492 **    May you share freely, never taking more than you give.
47493 **
47494 *************************************************************************
47495 ** This file contains code used to implement the ATTACH and DETACH commands.
47496 **
47497 ** $Id: attach.c,v 1.63 2007/10/03 08:46:44 danielk1977 Exp $
47498 */
47499
47500 #ifndef SQLITE_OMIT_ATTACH
47501 /*
47502 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
47503 ** is slightly different from resolving a normal SQL expression, because simple
47504 ** identifiers are treated as strings, not possible column names or aliases.
47505 **
47506 ** i.e. if the parser sees:
47507 **
47508 **     ATTACH DATABASE abc AS def
47509 **
47510 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
47511 ** looking for columns of the same name.
47512 **
47513 ** This only applies to the root node of pExpr, so the statement:
47514 **
47515 **     ATTACH DATABASE abc||def AS 'db2'
47516 **
47517 ** will fail because neither abc or def can be resolved.
47518 */
47519 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
47520 {
47521   int rc = SQLITE_OK;
47522   if( pExpr ){
47523     if( pExpr->op!=TK_ID ){
47524       rc = sqlite3ExprResolveNames(pName, pExpr);
47525       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
47526         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%T\"", &pExpr->span);
47527         return SQLITE_ERROR;
47528       }
47529     }else{
47530       pExpr->op = TK_STRING;
47531     }
47532   }
47533   return rc;
47534 }
47535
47536 /*
47537 ** An SQL user-function registered to do the work of an ATTACH statement. The
47538 ** three arguments to the function come directly from an attach statement:
47539 **
47540 **     ATTACH DATABASE x AS y KEY z
47541 **
47542 **     SELECT sqlite_attach(x, y, z)
47543 **
47544 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
47545 ** third argument.
47546 */
47547 static void attachFunc(
47548   sqlite3_context *context,
47549   int argc,
47550   sqlite3_value **argv
47551 ){
47552   int i;
47553   int rc = 0;
47554   sqlite3 *db = sqlite3_user_data(context);
47555   const char *zName;
47556   const char *zFile;
47557   Db *aNew;
47558   char *zErrDyn = 0;
47559   char zErr[128];
47560
47561   zFile = (const char *)sqlite3_value_text(argv[0]);
47562   zName = (const char *)sqlite3_value_text(argv[1]);
47563   if( zFile==0 ) zFile = "";
47564   if( zName==0 ) zName = "";
47565
47566   /* Check for the following errors:
47567   **
47568   **     * Too many attached databases,
47569   **     * Transaction currently open
47570   **     * Specified database name already being used.
47571   */
47572   if( db->nDb>=SQLITE_MAX_ATTACHED+2 ){
47573     sqlite3_snprintf(
47574       sizeof(zErr), zErr, "too many attached databases - max %d", 
47575       SQLITE_MAX_ATTACHED
47576     );
47577     goto attach_error;
47578   }
47579   if( !db->autoCommit ){
47580     sqlite3_snprintf(sizeof(zErr), zErr,
47581                      "cannot ATTACH database within transaction");
47582     goto attach_error;
47583   }
47584   for(i=0; i<db->nDb; i++){
47585     char *z = db->aDb[i].zName;
47586     if( z && zName && sqlite3StrICmp(z, zName)==0 ){
47587       sqlite3_snprintf(sizeof(zErr), zErr, 
47588                        "database %s is already in use", zName);
47589       goto attach_error;
47590     }
47591   }
47592
47593   /* Allocate the new entry in the db->aDb[] array and initialise the schema
47594   ** hash tables.
47595   */
47596   if( db->aDb==db->aDbStatic ){
47597     aNew = sqlite3_malloc( sizeof(db->aDb[0])*3 );
47598     if( aNew==0 ){
47599       db->mallocFailed = 1;
47600       return;
47601     }
47602     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
47603   }else{
47604     aNew = sqlite3_realloc(db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
47605     if( aNew==0 ){
47606       db->mallocFailed = 1;
47607       return;
47608     } 
47609   }
47610   db->aDb = aNew;
47611   aNew = &db->aDb[db->nDb++];
47612   memset(aNew, 0, sizeof(*aNew));
47613
47614   /* Open the database file. If the btree is successfully opened, use
47615   ** it to obtain the database schema. At this point the schema may
47616   ** or may not be initialised.
47617   */
47618   rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
47619                            db->openFlags | SQLITE_OPEN_MAIN_DB,
47620                            &aNew->pBt);
47621   if( rc==SQLITE_OK ){
47622     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
47623     if( !aNew->pSchema ){
47624       rc = SQLITE_NOMEM;
47625     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
47626       sqlite3_snprintf(sizeof(zErr), zErr, 
47627         "attached databases must use the same text encoding as main database");
47628       goto attach_error;
47629     }
47630     sqlite3PagerLockingMode(sqlite3BtreePager(aNew->pBt), db->dfltLockMode);
47631   }
47632   aNew->zName = sqlite3DbStrDup(db, zName);
47633   aNew->safety_level = 3;
47634
47635 #if SQLITE_HAS_CODEC
47636   {
47637     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
47638     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
47639     int nKey;
47640     char *zKey;
47641     int t = sqlite3_value_type(argv[2]);
47642     switch( t ){
47643       case SQLITE_INTEGER:
47644       case SQLITE_FLOAT:
47645         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
47646         rc = SQLITE_ERROR;
47647         break;
47648         
47649       case SQLITE_TEXT:
47650       case SQLITE_BLOB:
47651         nKey = sqlite3_value_bytes(argv[2]);
47652         zKey = (char *)sqlite3_value_blob(argv[2]);
47653         sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
47654         break;
47655
47656       case SQLITE_NULL:
47657         /* No key specified.  Use the key from the main database */
47658         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
47659         sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
47660         break;
47661     }
47662   }
47663 #endif
47664
47665   /* If the file was opened successfully, read the schema for the new database.
47666   ** If this fails, or if opening the file failed, then close the file and 
47667   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
47668   ** we found it.
47669   */
47670   if( rc==SQLITE_OK ){
47671     sqlite3SafetyOn(db);
47672     rc = sqlite3Init(db, &zErrDyn);
47673     sqlite3SafetyOff(db);
47674   }
47675   if( rc ){
47676     int iDb = db->nDb - 1;
47677     assert( iDb>=2 );
47678     if( db->aDb[iDb].pBt ){
47679       sqlite3BtreeClose(db->aDb[iDb].pBt);
47680       db->aDb[iDb].pBt = 0;
47681       db->aDb[iDb].pSchema = 0;
47682     }
47683     sqlite3ResetInternalSchema(db, 0);
47684     db->nDb = iDb;
47685     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
47686       db->mallocFailed = 1;
47687       sqlite3_snprintf(sizeof(zErr),zErr, "out of memory");
47688     }else{
47689       sqlite3_snprintf(sizeof(zErr),zErr, "unable to open database: %s", zFile);
47690     }
47691     goto attach_error;
47692   }
47693   
47694   return;
47695
47696 attach_error:
47697   /* Return an error if we get here */
47698   if( zErrDyn ){
47699     sqlite3_result_error(context, zErrDyn, -1);
47700     sqlite3_free(zErrDyn);
47701   }else{
47702     zErr[sizeof(zErr)-1] = 0;
47703     sqlite3_result_error(context, zErr, -1);
47704   }
47705 }
47706
47707 /*
47708 ** An SQL user-function registered to do the work of an DETACH statement. The
47709 ** three arguments to the function come directly from a detach statement:
47710 **
47711 **     DETACH DATABASE x
47712 **
47713 **     SELECT sqlite_detach(x)
47714 */
47715 static void detachFunc(
47716   sqlite3_context *context,
47717   int argc,
47718   sqlite3_value **argv
47719 ){
47720   const char *zName = (const char *)sqlite3_value_text(argv[0]);
47721   sqlite3 *db = sqlite3_user_data(context);
47722   int i;
47723   Db *pDb = 0;
47724   char zErr[128];
47725
47726   if( zName==0 ) zName = "";
47727   for(i=0; i<db->nDb; i++){
47728     pDb = &db->aDb[i];
47729     if( pDb->pBt==0 ) continue;
47730     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
47731   }
47732
47733   if( i>=db->nDb ){
47734     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
47735     goto detach_error;
47736   }
47737   if( i<2 ){
47738     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
47739     goto detach_error;
47740   }
47741   if( !db->autoCommit ){
47742     sqlite3_snprintf(sizeof(zErr), zErr,
47743                      "cannot DETACH database within transaction");
47744     goto detach_error;
47745   }
47746   if( sqlite3BtreeIsInReadTrans(pDb->pBt) ){
47747     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
47748     goto detach_error;
47749   }
47750
47751   sqlite3BtreeClose(pDb->pBt);
47752   pDb->pBt = 0;
47753   pDb->pSchema = 0;
47754   sqlite3ResetInternalSchema(db, 0);
47755   return;
47756
47757 detach_error:
47758   sqlite3_result_error(context, zErr, -1);
47759 }
47760
47761 /*
47762 ** This procedure generates VDBE code for a single invocation of either the
47763 ** sqlite_detach() or sqlite_attach() SQL user functions.
47764 */
47765 static void codeAttach(
47766   Parse *pParse,       /* The parser context */
47767   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
47768   const char *zFunc,   /* Either "sqlite_attach" or "sqlite_detach */
47769   int nFunc,           /* Number of args to pass to zFunc */
47770   Expr *pAuthArg,      /* Expression to pass to authorization callback */
47771   Expr *pFilename,     /* Name of database file */
47772   Expr *pDbname,       /* Name of the database to use internally */
47773   Expr *pKey           /* Database key for encryption extension */
47774 ){
47775   int rc;
47776   NameContext sName;
47777   Vdbe *v;
47778   FuncDef *pFunc;
47779   sqlite3* db = pParse->db;
47780
47781 #ifndef SQLITE_OMIT_AUTHORIZATION
47782   assert( db->mallocFailed || pAuthArg );
47783   if( pAuthArg ){
47784     char *zAuthArg = sqlite3NameFromToken(db, &pAuthArg->span);
47785     if( !zAuthArg ){
47786       goto attach_end;
47787     }
47788     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
47789     sqlite3_free(zAuthArg);
47790     if(rc!=SQLITE_OK ){
47791       goto attach_end;
47792     }
47793   }
47794 #endif /* SQLITE_OMIT_AUTHORIZATION */
47795
47796   memset(&sName, 0, sizeof(NameContext));
47797   sName.pParse = pParse;
47798
47799   if( 
47800       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
47801       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
47802       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
47803   ){
47804     pParse->nErr++;
47805     goto attach_end;
47806   }
47807
47808   v = sqlite3GetVdbe(pParse);
47809   sqlite3ExprCode(pParse, pFilename);
47810   sqlite3ExprCode(pParse, pDbname);
47811   sqlite3ExprCode(pParse, pKey);
47812
47813   assert( v || db->mallocFailed );
47814   if( v ){
47815     sqlite3VdbeAddOp(v, OP_Function, 0, nFunc);
47816     pFunc = sqlite3FindFunction(db, zFunc, strlen(zFunc), nFunc, SQLITE_UTF8,0);
47817     sqlite3VdbeChangeP3(v, -1, (char *)pFunc, P3_FUNCDEF);
47818
47819     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
47820     ** statement only). For DETACH, set it to false (expire all existing
47821     ** statements).
47822     */
47823     sqlite3VdbeAddOp(v, OP_Expire, (type==SQLITE_ATTACH), 0);
47824   }
47825   
47826 attach_end:
47827   sqlite3ExprDelete(pFilename);
47828   sqlite3ExprDelete(pDbname);
47829   sqlite3ExprDelete(pKey);
47830 }
47831
47832 /*
47833 ** Called by the parser to compile a DETACH statement.
47834 **
47835 **     DETACH pDbname
47836 */
47837 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
47838   codeAttach(pParse, SQLITE_DETACH, "sqlite_detach", 1, pDbname, 0, 0, pDbname);
47839 }
47840
47841 /*
47842 ** Called by the parser to compile an ATTACH statement.
47843 **
47844 **     ATTACH p AS pDbname KEY pKey
47845 */
47846 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
47847   codeAttach(pParse, SQLITE_ATTACH, "sqlite_attach", 3, p, p, pDbname, pKey);
47848 }
47849 #endif /* SQLITE_OMIT_ATTACH */
47850
47851 /*
47852 ** Register the functions sqlite_attach and sqlite_detach.
47853 */
47854 SQLITE_PRIVATE void sqlite3AttachFunctions(sqlite3 *db){
47855 #ifndef SQLITE_OMIT_ATTACH
47856   static const int enc = SQLITE_UTF8;
47857   sqlite3CreateFunc(db, "sqlite_attach", 3, enc, db, attachFunc, 0, 0);
47858   sqlite3CreateFunc(db, "sqlite_detach", 1, enc, db, detachFunc, 0, 0);
47859 #endif
47860 }
47861
47862 /*
47863 ** Initialize a DbFixer structure.  This routine must be called prior
47864 ** to passing the structure to one of the sqliteFixAAAA() routines below.
47865 **
47866 ** The return value indicates whether or not fixation is required.  TRUE
47867 ** means we do need to fix the database references, FALSE means we do not.
47868 */
47869 SQLITE_PRIVATE int sqlite3FixInit(
47870   DbFixer *pFix,      /* The fixer to be initialized */
47871   Parse *pParse,      /* Error messages will be written here */
47872   int iDb,            /* This is the database that must be used */
47873   const char *zType,  /* "view", "trigger", or "index" */
47874   const Token *pName  /* Name of the view, trigger, or index */
47875 ){
47876   sqlite3 *db;
47877
47878   if( iDb<0 || iDb==1 ) return 0;
47879   db = pParse->db;
47880   assert( db->nDb>iDb );
47881   pFix->pParse = pParse;
47882   pFix->zDb = db->aDb[iDb].zName;
47883   pFix->zType = zType;
47884   pFix->pName = pName;
47885   return 1;
47886 }
47887
47888 /*
47889 ** The following set of routines walk through the parse tree and assign
47890 ** a specific database to all table references where the database name
47891 ** was left unspecified in the original SQL statement.  The pFix structure
47892 ** must have been initialized by a prior call to sqlite3FixInit().
47893 **
47894 ** These routines are used to make sure that an index, trigger, or
47895 ** view in one database does not refer to objects in a different database.
47896 ** (Exception: indices, triggers, and views in the TEMP database are
47897 ** allowed to refer to anything.)  If a reference is explicitly made
47898 ** to an object in a different database, an error message is added to
47899 ** pParse->zErrMsg and these routines return non-zero.  If everything
47900 ** checks out, these routines return 0.
47901 */
47902 SQLITE_PRIVATE int sqlite3FixSrcList(
47903   DbFixer *pFix,       /* Context of the fixation */
47904   SrcList *pList       /* The Source list to check and modify */
47905 ){
47906   int i;
47907   const char *zDb;
47908   struct SrcList_item *pItem;
47909
47910   if( pList==0 ) return 0;
47911   zDb = pFix->zDb;
47912   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
47913     if( pItem->zDatabase==0 ){
47914       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
47915     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
47916       sqlite3ErrorMsg(pFix->pParse,
47917          "%s %T cannot reference objects in database %s",
47918          pFix->zType, pFix->pName, pItem->zDatabase);
47919       return 1;
47920     }
47921 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
47922     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
47923     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
47924 #endif
47925   }
47926   return 0;
47927 }
47928 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
47929 SQLITE_PRIVATE int sqlite3FixSelect(
47930   DbFixer *pFix,       /* Context of the fixation */
47931   Select *pSelect      /* The SELECT statement to be fixed to one database */
47932 ){
47933   while( pSelect ){
47934     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
47935       return 1;
47936     }
47937     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
47938       return 1;
47939     }
47940     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
47941       return 1;
47942     }
47943     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
47944       return 1;
47945     }
47946     pSelect = pSelect->pPrior;
47947   }
47948   return 0;
47949 }
47950 SQLITE_PRIVATE int sqlite3FixExpr(
47951   DbFixer *pFix,     /* Context of the fixation */
47952   Expr *pExpr        /* The expression to be fixed to one database */
47953 ){
47954   while( pExpr ){
47955     if( sqlite3FixSelect(pFix, pExpr->pSelect) ){
47956       return 1;
47957     }
47958     if( sqlite3FixExprList(pFix, pExpr->pList) ){
47959       return 1;
47960     }
47961     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
47962       return 1;
47963     }
47964     pExpr = pExpr->pLeft;
47965   }
47966   return 0;
47967 }
47968 SQLITE_PRIVATE int sqlite3FixExprList(
47969   DbFixer *pFix,     /* Context of the fixation */
47970   ExprList *pList    /* The expression to be fixed to one database */
47971 ){
47972   int i;
47973   struct ExprList_item *pItem;
47974   if( pList==0 ) return 0;
47975   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
47976     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
47977       return 1;
47978     }
47979   }
47980   return 0;
47981 }
47982 #endif
47983
47984 #ifndef SQLITE_OMIT_TRIGGER
47985 SQLITE_PRIVATE int sqlite3FixTriggerStep(
47986   DbFixer *pFix,     /* Context of the fixation */
47987   TriggerStep *pStep /* The trigger step be fixed to one database */
47988 ){
47989   while( pStep ){
47990     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
47991       return 1;
47992     }
47993     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
47994       return 1;
47995     }
47996     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
47997       return 1;
47998     }
47999     pStep = pStep->pNext;
48000   }
48001   return 0;
48002 }
48003 #endif
48004
48005 /************** End of attach.c **********************************************/
48006 /************** Begin file auth.c ********************************************/
48007 /*
48008 ** 2003 January 11
48009 **
48010 ** The author disclaims copyright to this source code.  In place of
48011 ** a legal notice, here is a blessing:
48012 **
48013 **    May you do good and not evil.
48014 **    May you find forgiveness for yourself and forgive others.
48015 **    May you share freely, never taking more than you give.
48016 **
48017 *************************************************************************
48018 ** This file contains code used to implement the sqlite3_set_authorizer()
48019 ** API.  This facility is an optional feature of the library.  Embedded
48020 ** systems that do not need this facility may omit it by recompiling
48021 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
48022 **
48023 ** $Id: auth.c,v 1.29 2007/09/18 15:55:07 drh Exp $
48024 */
48025
48026 /*
48027 ** All of the code in this file may be omitted by defining a single
48028 ** macro.
48029 */
48030 #ifndef SQLITE_OMIT_AUTHORIZATION
48031
48032 /*
48033 ** Set or clear the access authorization function.
48034 **
48035 ** The access authorization function is be called during the compilation
48036 ** phase to verify that the user has read and/or write access permission on
48037 ** various fields of the database.  The first argument to the auth function
48038 ** is a copy of the 3rd argument to this routine.  The second argument
48039 ** to the auth function is one of these constants:
48040 **
48041 **       SQLITE_CREATE_INDEX
48042 **       SQLITE_CREATE_TABLE
48043 **       SQLITE_CREATE_TEMP_INDEX
48044 **       SQLITE_CREATE_TEMP_TABLE
48045 **       SQLITE_CREATE_TEMP_TRIGGER
48046 **       SQLITE_CREATE_TEMP_VIEW
48047 **       SQLITE_CREATE_TRIGGER
48048 **       SQLITE_CREATE_VIEW
48049 **       SQLITE_DELETE
48050 **       SQLITE_DROP_INDEX
48051 **       SQLITE_DROP_TABLE
48052 **       SQLITE_DROP_TEMP_INDEX
48053 **       SQLITE_DROP_TEMP_TABLE
48054 **       SQLITE_DROP_TEMP_TRIGGER
48055 **       SQLITE_DROP_TEMP_VIEW
48056 **       SQLITE_DROP_TRIGGER
48057 **       SQLITE_DROP_VIEW
48058 **       SQLITE_INSERT
48059 **       SQLITE_PRAGMA
48060 **       SQLITE_READ
48061 **       SQLITE_SELECT
48062 **       SQLITE_TRANSACTION
48063 **       SQLITE_UPDATE
48064 **
48065 ** The third and fourth arguments to the auth function are the name of
48066 ** the table and the column that are being accessed.  The auth function
48067 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
48068 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
48069 ** means that the SQL statement will never-run - the sqlite3_exec() call
48070 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
48071 ** should run but attempts to read the specified column will return NULL
48072 ** and attempts to write the column will be ignored.
48073 **
48074 ** Setting the auth function to NULL disables this hook.  The default
48075 ** setting of the auth function is NULL.
48076 */
48077 SQLITE_API int sqlite3_set_authorizer(
48078   sqlite3 *db,
48079   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
48080   void *pArg
48081 ){
48082   sqlite3_mutex_enter(db->mutex);
48083   db->xAuth = xAuth;
48084   db->pAuthArg = pArg;
48085   sqlite3ExpirePreparedStatements(db);
48086   sqlite3_mutex_leave(db->mutex);
48087   return SQLITE_OK;
48088 }
48089
48090 /*
48091 ** Write an error message into pParse->zErrMsg that explains that the
48092 ** user-supplied authorization function returned an illegal value.
48093 */
48094 static void sqliteAuthBadReturnCode(Parse *pParse, int rc){
48095   sqlite3ErrorMsg(pParse, "illegal return value (%d) from the "
48096     "authorization function - should be SQLITE_OK, SQLITE_IGNORE, "
48097     "or SQLITE_DENY", rc);
48098   pParse->rc = SQLITE_ERROR;
48099 }
48100
48101 /*
48102 ** The pExpr should be a TK_COLUMN expression.  The table referred to
48103 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
48104 ** Check to see if it is OK to read this particular column.
48105 **
48106 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
48107 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
48108 ** then generate an error.
48109 */
48110 SQLITE_PRIVATE void sqlite3AuthRead(
48111   Parse *pParse,        /* The parser context */
48112   Expr *pExpr,          /* The expression to check authorization on */
48113   Schema *pSchema,      /* The schema of the expression */
48114   SrcList *pTabList     /* All table that pExpr might refer to */
48115 ){
48116   sqlite3 *db = pParse->db;
48117   int rc;
48118   Table *pTab = 0;      /* The table being read */
48119   const char *zCol;     /* Name of the column of the table */
48120   int iSrc;             /* Index in pTabList->a[] of table being read */
48121   const char *zDBase;   /* Name of database being accessed */
48122   TriggerStack *pStack; /* The stack of current triggers */
48123   int iDb;              /* The index of the database the expression refers to */
48124
48125   if( db->xAuth==0 ) return;
48126   if( pExpr->op!=TK_COLUMN ) return;
48127   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
48128   if( iDb<0 ){
48129     /* An attempt to read a column out of a subquery or other
48130     ** temporary table. */
48131     return;
48132   }
48133   for(iSrc=0; pTabList && iSrc<pTabList->nSrc; iSrc++){
48134     if( pExpr->iTable==pTabList->a[iSrc].iCursor ) break;
48135   }
48136   if( iSrc>=0 && pTabList && iSrc<pTabList->nSrc ){
48137     pTab = pTabList->a[iSrc].pTab;
48138   }else if( (pStack = pParse->trigStack)!=0 ){
48139     /* This must be an attempt to read the NEW or OLD pseudo-tables
48140     ** of a trigger.
48141     */
48142     assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx );
48143     pTab = pStack->pTab;
48144   }
48145   if( pTab==0 ) return;
48146   if( pExpr->iColumn>=0 ){
48147     assert( pExpr->iColumn<pTab->nCol );
48148     zCol = pTab->aCol[pExpr->iColumn].zName;
48149   }else if( pTab->iPKey>=0 ){
48150     assert( pTab->iPKey<pTab->nCol );
48151     zCol = pTab->aCol[pTab->iPKey].zName;
48152   }else{
48153     zCol = "ROWID";
48154   }
48155   assert( iDb>=0 && iDb<db->nDb );
48156   zDBase = db->aDb[iDb].zName;
48157   rc = db->xAuth(db->pAuthArg, SQLITE_READ, pTab->zName, zCol, zDBase, 
48158                  pParse->zAuthContext);
48159   if( rc==SQLITE_IGNORE ){
48160     pExpr->op = TK_NULL;
48161   }else if( rc==SQLITE_DENY ){
48162     if( db->nDb>2 || iDb!=0 ){
48163       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited", 
48164          zDBase, pTab->zName, zCol);
48165     }else{
48166       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited",pTab->zName,zCol);
48167     }
48168     pParse->rc = SQLITE_AUTH;
48169   }else if( rc!=SQLITE_OK ){
48170     sqliteAuthBadReturnCode(pParse, rc);
48171   }
48172 }
48173
48174 /*
48175 ** Do an authorization check using the code and arguments given.  Return
48176 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
48177 ** is returned, then the error count and error message in pParse are
48178 ** modified appropriately.
48179 */
48180 SQLITE_PRIVATE int sqlite3AuthCheck(
48181   Parse *pParse,
48182   int code,
48183   const char *zArg1,
48184   const char *zArg2,
48185   const char *zArg3
48186 ){
48187   sqlite3 *db = pParse->db;
48188   int rc;
48189
48190   /* Don't do any authorization checks if the database is initialising
48191   ** or if the parser is being invoked from within sqlite3_declare_vtab.
48192   */
48193   if( db->init.busy || IN_DECLARE_VTAB ){
48194     return SQLITE_OK;
48195   }
48196
48197   if( db->xAuth==0 ){
48198     return SQLITE_OK;
48199   }
48200   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
48201   if( rc==SQLITE_DENY ){
48202     sqlite3ErrorMsg(pParse, "not authorized");
48203     pParse->rc = SQLITE_AUTH;
48204   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
48205     rc = SQLITE_DENY;
48206     sqliteAuthBadReturnCode(pParse, rc);
48207   }
48208   return rc;
48209 }
48210
48211 /*
48212 ** Push an authorization context.  After this routine is called, the
48213 ** zArg3 argument to authorization callbacks will be zContext until
48214 ** popped.  Or if pParse==0, this routine is a no-op.
48215 */
48216 SQLITE_PRIVATE void sqlite3AuthContextPush(
48217   Parse *pParse,
48218   AuthContext *pContext, 
48219   const char *zContext
48220 ){
48221   pContext->pParse = pParse;
48222   if( pParse ){
48223     pContext->zAuthContext = pParse->zAuthContext;
48224     pParse->zAuthContext = zContext;
48225   }
48226 }
48227
48228 /*
48229 ** Pop an authorization context that was previously pushed
48230 ** by sqlite3AuthContextPush
48231 */
48232 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
48233   if( pContext->pParse ){
48234     pContext->pParse->zAuthContext = pContext->zAuthContext;
48235     pContext->pParse = 0;
48236   }
48237 }
48238
48239 #endif /* SQLITE_OMIT_AUTHORIZATION */
48240
48241 /************** End of auth.c ************************************************/
48242 /************** Begin file build.c *******************************************/
48243 /*
48244 ** 2001 September 15
48245 **
48246 ** The author disclaims copyright to this source code.  In place of
48247 ** a legal notice, here is a blessing:
48248 **
48249 **    May you do good and not evil.
48250 **    May you find forgiveness for yourself and forgive others.
48251 **    May you share freely, never taking more than you give.
48252 **
48253 *************************************************************************
48254 ** This file contains C code routines that are called by the SQLite parser
48255 ** when syntax rules are reduced.  The routines in this file handle the
48256 ** following kinds of SQL syntax:
48257 **
48258 **     CREATE TABLE
48259 **     DROP TABLE
48260 **     CREATE INDEX
48261 **     DROP INDEX
48262 **     creating ID lists
48263 **     BEGIN TRANSACTION
48264 **     COMMIT
48265 **     ROLLBACK
48266 **
48267 ** $Id: build.c,v 1.450 2007/12/04 16:54:53 drh Exp $
48268 */
48269
48270 /*
48271 ** This routine is called when a new SQL statement is beginning to
48272 ** be parsed.  Initialize the pParse structure as needed.
48273 */
48274 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
48275   pParse->explain = explainFlag;
48276   pParse->nVar = 0;
48277 }
48278
48279 #ifndef SQLITE_OMIT_SHARED_CACHE
48280 /*
48281 ** The TableLock structure is only used by the sqlite3TableLock() and
48282 ** codeTableLocks() functions.
48283 */
48284 struct TableLock {
48285   int iDb;             /* The database containing the table to be locked */
48286   int iTab;            /* The root page of the table to be locked */
48287   u8 isWriteLock;      /* True for write lock.  False for a read lock */
48288   const char *zName;   /* Name of the table */
48289 };
48290
48291 /*
48292 ** Record the fact that we want to lock a table at run-time.  
48293 **
48294 ** The table to be locked has root page iTab and is found in database iDb.
48295 ** A read or a write lock can be taken depending on isWritelock.
48296 **
48297 ** This routine just records the fact that the lock is desired.  The
48298 ** code to make the lock occur is generated by a later call to
48299 ** codeTableLocks() which occurs during sqlite3FinishCoding().
48300 */
48301 SQLITE_PRIVATE void sqlite3TableLock(
48302   Parse *pParse,     /* Parsing context */
48303   int iDb,           /* Index of the database containing the table to lock */
48304   int iTab,          /* Root page number of the table to be locked */
48305   u8 isWriteLock,    /* True for a write lock */
48306   const char *zName  /* Name of the table to be locked */
48307 ){
48308   int i;
48309   int nBytes;
48310   TableLock *p;
48311
48312   if( iDb<0 ){
48313     return;
48314   }
48315
48316   for(i=0; i<pParse->nTableLock; i++){
48317     p = &pParse->aTableLock[i];
48318     if( p->iDb==iDb && p->iTab==iTab ){
48319       p->isWriteLock = (p->isWriteLock || isWriteLock);
48320       return;
48321     }
48322   }
48323
48324   nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
48325   pParse->aTableLock = 
48326       sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes);
48327   if( pParse->aTableLock ){
48328     p = &pParse->aTableLock[pParse->nTableLock++];
48329     p->iDb = iDb;
48330     p->iTab = iTab;
48331     p->isWriteLock = isWriteLock;
48332     p->zName = zName;
48333   }else{
48334     pParse->nTableLock = 0;
48335     pParse->db->mallocFailed = 1;
48336   }
48337 }
48338
48339 /*
48340 ** Code an OP_TableLock instruction for each table locked by the
48341 ** statement (configured by calls to sqlite3TableLock()).
48342 */
48343 static void codeTableLocks(Parse *pParse){
48344   int i;
48345   Vdbe *pVdbe; 
48346
48347   if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
48348     return;
48349   }
48350
48351   for(i=0; i<pParse->nTableLock; i++){
48352     TableLock *p = &pParse->aTableLock[i];
48353     int p1 = p->iDb;
48354     if( p->isWriteLock ){
48355       p1 = -1*(p1+1);
48356     }
48357     sqlite3VdbeOp3(pVdbe, OP_TableLock, p1, p->iTab, p->zName, P3_STATIC);
48358   }
48359 }
48360 #else
48361   #define codeTableLocks(x)
48362 #endif
48363
48364 /*
48365 ** This routine is called after a single SQL statement has been
48366 ** parsed and a VDBE program to execute that statement has been
48367 ** prepared.  This routine puts the finishing touches on the
48368 ** VDBE program and resets the pParse structure for the next
48369 ** parse.
48370 **
48371 ** Note that if an error occurred, it might be the case that
48372 ** no VDBE code was generated.
48373 */
48374 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
48375   sqlite3 *db;
48376   Vdbe *v;
48377
48378   db = pParse->db;
48379   if( db->mallocFailed ) return;
48380   if( pParse->nested ) return;
48381   if( !pParse->pVdbe ){
48382     if( pParse->rc==SQLITE_OK && pParse->nErr ){
48383       pParse->rc = SQLITE_ERROR;
48384       return;
48385     }
48386   }
48387
48388   /* Begin by generating some termination code at the end of the
48389   ** vdbe program
48390   */
48391   v = sqlite3GetVdbe(pParse);
48392   if( v ){
48393     sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
48394
48395     /* The cookie mask contains one bit for each database file open.
48396     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
48397     ** set for each database that is used.  Generate code to start a
48398     ** transaction on each used database and to verify the schema cookie
48399     ** on each used database.
48400     */
48401     if( pParse->cookieGoto>0 ){
48402       u32 mask;
48403       int iDb;
48404       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
48405       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
48406         if( (mask & pParse->cookieMask)==0 ) continue;
48407         sqlite3VdbeUsesBtree(v, iDb);
48408         sqlite3VdbeAddOp(v, OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
48409         sqlite3VdbeAddOp(v, OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
48410       }
48411 #ifndef SQLITE_OMIT_VIRTUALTABLE
48412       if( pParse->pVirtualLock ){
48413         char *vtab = (char *)pParse->pVirtualLock->pVtab;
48414         sqlite3VdbeOp3(v, OP_VBegin, 0, 0, vtab, P3_VTAB);
48415       }
48416 #endif
48417
48418       /* Once all the cookies have been verified and transactions opened, 
48419       ** obtain the required table-locks. This is a no-op unless the 
48420       ** shared-cache feature is enabled.
48421       */
48422       codeTableLocks(pParse);
48423       sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->cookieGoto);
48424     }
48425
48426 #ifndef SQLITE_OMIT_TRACE
48427     /* Add a No-op that contains the complete text of the compiled SQL
48428     ** statement as its P3 argument.  This does not change the functionality
48429     ** of the program. 
48430     **
48431     ** This is used to implement sqlite3_trace().
48432     */
48433     sqlite3VdbeOp3(v, OP_Noop, 0, 0, pParse->zSql, pParse->zTail-pParse->zSql);
48434 #endif /* SQLITE_OMIT_TRACE */
48435   }
48436
48437
48438   /* Get the VDBE program ready for execution
48439   */
48440   if( v && pParse->nErr==0 && !db->mallocFailed ){
48441 #ifdef SQLITE_DEBUG
48442     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
48443     sqlite3VdbeTrace(v, trace);
48444 #endif
48445     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
48446                          pParse->nTab+3, pParse->explain);
48447     pParse->rc = SQLITE_DONE;
48448     pParse->colNamesSet = 0;
48449   }else if( pParse->rc==SQLITE_OK ){
48450     pParse->rc = SQLITE_ERROR;
48451   }
48452   pParse->nTab = 0;
48453   pParse->nMem = 0;
48454   pParse->nSet = 0;
48455   pParse->nVar = 0;
48456   pParse->cookieMask = 0;
48457   pParse->cookieGoto = 0;
48458 }
48459
48460 /*
48461 ** Run the parser and code generator recursively in order to generate
48462 ** code for the SQL statement given onto the end of the pParse context
48463 ** currently under construction.  When the parser is run recursively
48464 ** this way, the final OP_Halt is not appended and other initialization
48465 ** and finalization steps are omitted because those are handling by the
48466 ** outermost parser.
48467 **
48468 ** Not everything is nestable.  This facility is designed to permit
48469 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
48470 ** care if you decide to try to use this routine for some other purposes.
48471 */
48472 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
48473   va_list ap;
48474   char *zSql;
48475 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
48476   char saveBuf[SAVE_SZ];
48477
48478   if( pParse->nErr ) return;
48479   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
48480   va_start(ap, zFormat);
48481   zSql = sqlite3VMPrintf(pParse->db, zFormat, ap);
48482   va_end(ap);
48483   if( zSql==0 ){
48484     pParse->db->mallocFailed = 1;
48485     return;   /* A malloc must have failed */
48486   }
48487   pParse->nested++;
48488   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
48489   memset(&pParse->nVar, 0, SAVE_SZ);
48490   sqlite3RunParser(pParse, zSql, 0);
48491   sqlite3_free(zSql);
48492   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
48493   pParse->nested--;
48494 }
48495
48496 /*
48497 ** Locate the in-memory structure that describes a particular database
48498 ** table given the name of that table and (optionally) the name of the
48499 ** database containing the table.  Return NULL if not found.
48500 **
48501 ** If zDatabase is 0, all databases are searched for the table and the
48502 ** first matching table is returned.  (No checking for duplicate table
48503 ** names is done.)  The search order is TEMP first, then MAIN, then any
48504 ** auxiliary databases added using the ATTACH command.
48505 **
48506 ** See also sqlite3LocateTable().
48507 */
48508 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
48509   Table *p = 0;
48510   int i;
48511   assert( zName!=0 );
48512   for(i=OMIT_TEMPDB; i<db->nDb; i++){
48513     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
48514     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
48515     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, strlen(zName)+1);
48516     if( p ) break;
48517   }
48518   return p;
48519 }
48520
48521 /*
48522 ** Locate the in-memory structure that describes a particular database
48523 ** table given the name of that table and (optionally) the name of the
48524 ** database containing the table.  Return NULL if not found.  Also leave an
48525 ** error message in pParse->zErrMsg.
48526 **
48527 ** The difference between this routine and sqlite3FindTable() is that this
48528 ** routine leaves an error message in pParse->zErrMsg where
48529 ** sqlite3FindTable() does not.
48530 */
48531 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse *pParse, const char *zName, const char *zDbase){
48532   Table *p;
48533
48534   /* Read the database schema. If an error occurs, leave an error message
48535   ** and code in pParse and return NULL. */
48536   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
48537     return 0;
48538   }
48539
48540   p = sqlite3FindTable(pParse->db, zName, zDbase);
48541   if( p==0 ){
48542     if( zDbase ){
48543       sqlite3ErrorMsg(pParse, "no such table: %s.%s", zDbase, zName);
48544     }else{
48545       sqlite3ErrorMsg(pParse, "no such table: %s", zName);
48546     }
48547     pParse->checkSchema = 1;
48548   }
48549   return p;
48550 }
48551
48552 /*
48553 ** Locate the in-memory structure that describes 
48554 ** a particular index given the name of that index
48555 ** and the name of the database that contains the index.
48556 ** Return NULL if not found.
48557 **
48558 ** If zDatabase is 0, all databases are searched for the
48559 ** table and the first matching index is returned.  (No checking
48560 ** for duplicate index names is done.)  The search order is
48561 ** TEMP first, then MAIN, then any auxiliary databases added
48562 ** using the ATTACH command.
48563 */
48564 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
48565   Index *p = 0;
48566   int i;
48567   for(i=OMIT_TEMPDB; i<db->nDb; i++){
48568     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
48569     Schema *pSchema = db->aDb[j].pSchema;
48570     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
48571     assert( pSchema || (j==1 && !db->aDb[1].pBt) );
48572     if( pSchema ){
48573       p = sqlite3HashFind(&pSchema->idxHash, zName, strlen(zName)+1);
48574     }
48575     if( p ) break;
48576   }
48577   return p;
48578 }
48579
48580 /*
48581 ** Reclaim the memory used by an index
48582 */
48583 static void freeIndex(Index *p){
48584   sqlite3_free(p->zColAff);
48585   sqlite3_free(p);
48586 }
48587
48588 /*
48589 ** Remove the given index from the index hash table, and free
48590 ** its memory structures.
48591 **
48592 ** The index is removed from the database hash tables but
48593 ** it is not unlinked from the Table that it indexes.
48594 ** Unlinking from the Table must be done by the calling function.
48595 */
48596 static void sqliteDeleteIndex(Index *p){
48597   Index *pOld;
48598   const char *zName = p->zName;
48599
48600   pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen( zName)+1, 0);
48601   assert( pOld==0 || pOld==p );
48602   freeIndex(p);
48603 }
48604
48605 /*
48606 ** For the index called zIdxName which is found in the database iDb,
48607 ** unlike that index from its Table then remove the index from
48608 ** the index hash table and free all memory structures associated
48609 ** with the index.
48610 */
48611 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
48612   Index *pIndex;
48613   int len;
48614   Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
48615
48616   len = strlen(zIdxName);
48617   pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
48618   if( pIndex ){
48619     if( pIndex->pTable->pIndex==pIndex ){
48620       pIndex->pTable->pIndex = pIndex->pNext;
48621     }else{
48622       Index *p;
48623       for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
48624       if( p && p->pNext==pIndex ){
48625         p->pNext = pIndex->pNext;
48626       }
48627     }
48628     freeIndex(pIndex);
48629   }
48630   db->flags |= SQLITE_InternChanges;
48631 }
48632
48633 /*
48634 ** Erase all schema information from the in-memory hash tables of
48635 ** a single database.  This routine is called to reclaim memory
48636 ** before the database closes.  It is also called during a rollback
48637 ** if there were schema changes during the transaction or if a
48638 ** schema-cookie mismatch occurs.
48639 **
48640 ** If iDb<=0 then reset the internal schema tables for all database
48641 ** files.  If iDb>=2 then reset the internal schema for only the
48642 ** single file indicated.
48643 */
48644 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
48645   int i, j;
48646
48647   assert( iDb>=0 && iDb<db->nDb );
48648   for(i=iDb; i<db->nDb; i++){
48649     Db *pDb = &db->aDb[i];
48650     if( pDb->pSchema ){
48651       sqlite3SchemaFree(pDb->pSchema);
48652     }
48653     if( iDb>0 ) return;
48654   }
48655   assert( iDb==0 );
48656   db->flags &= ~SQLITE_InternChanges;
48657
48658   /* If one or more of the auxiliary database files has been closed,
48659   ** then remove them from the auxiliary database list.  We take the
48660   ** opportunity to do this here since we have just deleted all of the
48661   ** schema hash tables and therefore do not have to make any changes
48662   ** to any of those tables.
48663   */
48664   for(i=0; i<db->nDb; i++){
48665     struct Db *pDb = &db->aDb[i];
48666     if( pDb->pBt==0 ){
48667       if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
48668       pDb->pAux = 0;
48669     }
48670   }
48671   for(i=j=2; i<db->nDb; i++){
48672     struct Db *pDb = &db->aDb[i];
48673     if( pDb->pBt==0 ){
48674       sqlite3_free(pDb->zName);
48675       pDb->zName = 0;
48676       continue;
48677     }
48678     if( j<i ){
48679       db->aDb[j] = db->aDb[i];
48680     }
48681     j++;
48682   }
48683   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
48684   db->nDb = j;
48685   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
48686     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
48687     sqlite3_free(db->aDb);
48688     db->aDb = db->aDbStatic;
48689   }
48690 }
48691
48692 /*
48693 ** This routine is called when a commit occurs.
48694 */
48695 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
48696   db->flags &= ~SQLITE_InternChanges;
48697 }
48698
48699 /*
48700 ** Clear the column names from a table or view.
48701 */
48702 static void sqliteResetColumnNames(Table *pTable){
48703   int i;
48704   Column *pCol;
48705   assert( pTable!=0 );
48706   if( (pCol = pTable->aCol)!=0 ){
48707     for(i=0; i<pTable->nCol; i++, pCol++){
48708       sqlite3_free(pCol->zName);
48709       sqlite3ExprDelete(pCol->pDflt);
48710       sqlite3_free(pCol->zType);
48711       sqlite3_free(pCol->zColl);
48712     }
48713     sqlite3_free(pTable->aCol);
48714   }
48715   pTable->aCol = 0;
48716   pTable->nCol = 0;
48717 }
48718
48719 /*
48720 ** Remove the memory data structures associated with the given
48721 ** Table.  No changes are made to disk by this routine.
48722 **
48723 ** This routine just deletes the data structure.  It does not unlink
48724 ** the table data structure from the hash table.  Nor does it remove
48725 ** foreign keys from the sqlite.aFKey hash table.  But it does destroy
48726 ** memory structures of the indices and foreign keys associated with 
48727 ** the table.
48728 */
48729 SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
48730   Index *pIndex, *pNext;
48731   FKey *pFKey, *pNextFKey;
48732
48733   if( pTable==0 ) return;
48734
48735   /* Do not delete the table until the reference count reaches zero. */
48736   pTable->nRef--;
48737   if( pTable->nRef>0 ){
48738     return;
48739   }
48740   assert( pTable->nRef==0 );
48741
48742   /* Delete all indices associated with this table
48743   */
48744   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
48745     pNext = pIndex->pNext;
48746     assert( pIndex->pSchema==pTable->pSchema );
48747     sqliteDeleteIndex(pIndex);
48748   }
48749
48750 #ifndef SQLITE_OMIT_FOREIGN_KEY
48751   /* Delete all foreign keys associated with this table.  The keys
48752   ** should have already been unlinked from the pSchema->aFKey hash table 
48753   */
48754   for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
48755     pNextFKey = pFKey->pNextFrom;
48756     assert( sqlite3HashFind(&pTable->pSchema->aFKey,
48757                            pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
48758     sqlite3_free(pFKey);
48759   }
48760 #endif
48761
48762   /* Delete the Table structure itself.
48763   */
48764   sqliteResetColumnNames(pTable);
48765   sqlite3_free(pTable->zName);
48766   sqlite3_free(pTable->zColAff);
48767   sqlite3SelectDelete(pTable->pSelect);
48768 #ifndef SQLITE_OMIT_CHECK
48769   sqlite3ExprDelete(pTable->pCheck);
48770 #endif
48771   sqlite3VtabClear(pTable);
48772   sqlite3_free(pTable);
48773 }
48774
48775 /*
48776 ** Unlink the given table from the hash tables and the delete the
48777 ** table structure with all its indices and foreign keys.
48778 */
48779 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
48780   Table *p;
48781   FKey *pF1, *pF2;
48782   Db *pDb;
48783
48784   assert( db!=0 );
48785   assert( iDb>=0 && iDb<db->nDb );
48786   assert( zTabName && zTabName[0] );
48787   pDb = &db->aDb[iDb];
48788   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0);
48789   if( p ){
48790 #ifndef SQLITE_OMIT_FOREIGN_KEY
48791     for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
48792       int nTo = strlen(pF1->zTo) + 1;
48793       pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
48794       if( pF2==pF1 ){
48795         sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
48796       }else{
48797         while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
48798         if( pF2 ){
48799           pF2->pNextTo = pF1->pNextTo;
48800         }
48801       }
48802     }
48803 #endif
48804     sqlite3DeleteTable(p);
48805   }
48806   db->flags |= SQLITE_InternChanges;
48807 }
48808
48809 /*
48810 ** Given a token, return a string that consists of the text of that
48811 ** token with any quotations removed.  Space to hold the returned string
48812 ** is obtained from sqliteMalloc() and must be freed by the calling
48813 ** function.
48814 **
48815 ** Tokens are often just pointers into the original SQL text and so
48816 ** are not \000 terminated and are not persistent.  The returned string
48817 ** is \000 terminated and is persistent.
48818 */
48819 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
48820   char *zName;
48821   if( pName ){
48822     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
48823     sqlite3Dequote(zName);
48824   }else{
48825     zName = 0;
48826   }
48827   return zName;
48828 }
48829
48830 /*
48831 ** Open the sqlite_master table stored in database number iDb for
48832 ** writing. The table is opened using cursor 0.
48833 */
48834 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
48835   Vdbe *v = sqlite3GetVdbe(p);
48836   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
48837   sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
48838   sqlite3VdbeAddOp(v, OP_OpenWrite, 0, MASTER_ROOT);
48839   sqlite3VdbeAddOp(v, OP_SetNumColumns, 0, 5); /* sqlite_master has 5 columns */
48840 }
48841
48842 /*
48843 ** The token *pName contains the name of a database (either "main" or
48844 ** "temp" or the name of an attached db). This routine returns the
48845 ** index of the named database in db->aDb[], or -1 if the named db 
48846 ** does not exist.
48847 */
48848 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
48849   int i = -1;    /* Database number */
48850   int n;         /* Number of characters in the name */
48851   Db *pDb;       /* A database whose name space is being searched */
48852   char *zName;   /* Name we are searching for */
48853
48854   zName = sqlite3NameFromToken(db, pName);
48855   if( zName ){
48856     n = strlen(zName);
48857     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
48858       if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) && 
48859           0==sqlite3StrICmp(pDb->zName, zName) ){
48860         break;
48861       }
48862     }
48863     sqlite3_free(zName);
48864   }
48865   return i;
48866 }
48867
48868 /* The table or view or trigger name is passed to this routine via tokens
48869 ** pName1 and pName2. If the table name was fully qualified, for example:
48870 **
48871 ** CREATE TABLE xxx.yyy (...);
48872 ** 
48873 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
48874 ** the table name is not fully qualified, i.e.:
48875 **
48876 ** CREATE TABLE yyy(...);
48877 **
48878 ** Then pName1 is set to "yyy" and pName2 is "".
48879 **
48880 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
48881 ** pName2) that stores the unqualified table name.  The index of the
48882 ** database "xxx" is returned.
48883 */
48884 SQLITE_PRIVATE int sqlite3TwoPartName(
48885   Parse *pParse,      /* Parsing and code generating context */
48886   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
48887   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
48888   Token **pUnqual     /* Write the unqualified object name here */
48889 ){
48890   int iDb;                    /* Database holding the object */
48891   sqlite3 *db = pParse->db;
48892
48893   if( pName2 && pName2->n>0 ){
48894     assert( !db->init.busy );
48895     *pUnqual = pName2;
48896     iDb = sqlite3FindDb(db, pName1);
48897     if( iDb<0 ){
48898       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
48899       pParse->nErr++;
48900       return -1;
48901     }
48902   }else{
48903     assert( db->init.iDb==0 || db->init.busy );
48904     iDb = db->init.iDb;
48905     *pUnqual = pName1;
48906   }
48907   return iDb;
48908 }
48909
48910 /*
48911 ** This routine is used to check if the UTF-8 string zName is a legal
48912 ** unqualified name for a new schema object (table, index, view or
48913 ** trigger). All names are legal except those that begin with the string
48914 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
48915 ** is reserved for internal use.
48916 */
48917 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
48918   if( !pParse->db->init.busy && pParse->nested==0 
48919           && (pParse->db->flags & SQLITE_WriteSchema)==0
48920           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
48921     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
48922     return SQLITE_ERROR;
48923   }
48924   return SQLITE_OK;
48925 }
48926
48927 /*
48928 ** Begin constructing a new table representation in memory.  This is
48929 ** the first of several action routines that get called in response
48930 ** to a CREATE TABLE statement.  In particular, this routine is called
48931 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
48932 ** flag is true if the table should be stored in the auxiliary database
48933 ** file instead of in the main database file.  This is normally the case
48934 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
48935 ** CREATE and TABLE.
48936 **
48937 ** The new table record is initialized and put in pParse->pNewTable.
48938 ** As more of the CREATE TABLE statement is parsed, additional action
48939 ** routines will be called to add more information to this record.
48940 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
48941 ** is called to complete the construction of the new table record.
48942 */
48943 SQLITE_PRIVATE void sqlite3StartTable(
48944   Parse *pParse,   /* Parser context */
48945   Token *pName1,   /* First part of the name of the table or view */
48946   Token *pName2,   /* Second part of the name of the table or view */
48947   int isTemp,      /* True if this is a TEMP table */
48948   int isView,      /* True if this is a VIEW */
48949   int isVirtual,   /* True if this is a VIRTUAL table */
48950   int noErr        /* Do nothing if table already exists */
48951 ){
48952   Table *pTable;
48953   char *zName = 0; /* The name of the new table */
48954   sqlite3 *db = pParse->db;
48955   Vdbe *v;
48956   int iDb;         /* Database number to create the table in */
48957   Token *pName;    /* Unqualified name of the table to create */
48958
48959   /* The table or view name to create is passed to this routine via tokens
48960   ** pName1 and pName2. If the table name was fully qualified, for example:
48961   **
48962   ** CREATE TABLE xxx.yyy (...);
48963   ** 
48964   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
48965   ** the table name is not fully qualified, i.e.:
48966   **
48967   ** CREATE TABLE yyy(...);
48968   **
48969   ** Then pName1 is set to "yyy" and pName2 is "".
48970   **
48971   ** The call below sets the pName pointer to point at the token (pName1 or
48972   ** pName2) that stores the unqualified table name. The variable iDb is
48973   ** set to the index of the database that the table or view is to be
48974   ** created in.
48975   */
48976   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
48977   if( iDb<0 ) return;
48978   if( !OMIT_TEMPDB && isTemp && iDb>1 ){
48979     /* If creating a temp table, the name may not be qualified */
48980     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
48981     return;
48982   }
48983   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
48984
48985   pParse->sNameToken = *pName;
48986   zName = sqlite3NameFromToken(db, pName);
48987   if( zName==0 ) return;
48988   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
48989     goto begin_table_error;
48990   }
48991   if( db->init.iDb==1 ) isTemp = 1;
48992 #ifndef SQLITE_OMIT_AUTHORIZATION
48993   assert( (isTemp & 1)==isTemp );
48994   {
48995     int code;
48996     char *zDb = db->aDb[iDb].zName;
48997     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
48998       goto begin_table_error;
48999     }
49000     if( isView ){
49001       if( !OMIT_TEMPDB && isTemp ){
49002         code = SQLITE_CREATE_TEMP_VIEW;
49003       }else{
49004         code = SQLITE_CREATE_VIEW;
49005       }
49006     }else{
49007       if( !OMIT_TEMPDB && isTemp ){
49008         code = SQLITE_CREATE_TEMP_TABLE;
49009       }else{
49010         code = SQLITE_CREATE_TABLE;
49011       }
49012     }
49013     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
49014       goto begin_table_error;
49015     }
49016   }
49017 #endif
49018
49019   /* Make sure the new table name does not collide with an existing
49020   ** index or table name in the same database.  Issue an error message if
49021   ** it does. The exception is if the statement being parsed was passed
49022   ** to an sqlite3_declare_vtab() call. In that case only the column names
49023   ** and types will be used, so there is no need to test for namespace
49024   ** collisions.
49025   */
49026   if( !IN_DECLARE_VTAB ){
49027     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
49028       goto begin_table_error;
49029     }
49030     pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
49031     if( pTable ){
49032       if( !noErr ){
49033         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
49034       }
49035       goto begin_table_error;
49036     }
49037     if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
49038       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
49039       goto begin_table_error;
49040     }
49041   }
49042
49043   pTable = sqlite3DbMallocZero(db, sizeof(Table));
49044   if( pTable==0 ){
49045     db->mallocFailed = 1;
49046     pParse->rc = SQLITE_NOMEM;
49047     pParse->nErr++;
49048     goto begin_table_error;
49049   }
49050   pTable->zName = zName;
49051   pTable->iPKey = -1;
49052   pTable->pSchema = db->aDb[iDb].pSchema;
49053   pTable->nRef = 1;
49054   if( pParse->pNewTable ) sqlite3DeleteTable(pParse->pNewTable);
49055   pParse->pNewTable = pTable;
49056
49057   /* If this is the magic sqlite_sequence table used by autoincrement,
49058   ** then record a pointer to this table in the main database structure
49059   ** so that INSERT can find the table easily.
49060   */
49061 #ifndef SQLITE_OMIT_AUTOINCREMENT
49062   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
49063     pTable->pSchema->pSeqTab = pTable;
49064   }
49065 #endif
49066
49067   /* Begin generating the code that will insert the table record into
49068   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
49069   ** and allocate the record number for the table entry now.  Before any
49070   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
49071   ** indices to be created and the table record must come before the 
49072   ** indices.  Hence, the record number for the table must be allocated
49073   ** now.
49074   */
49075   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
49076     int lbl;
49077     int fileFormat;
49078     sqlite3BeginWriteOperation(pParse, 0, iDb);
49079
49080 #ifndef SQLITE_OMIT_VIRTUALTABLE
49081     if( isVirtual ){
49082       sqlite3VdbeAddOp(v, OP_VBegin, 0, 0);
49083     }
49084 #endif
49085
49086     /* If the file format and encoding in the database have not been set, 
49087     ** set them now.
49088     */
49089     sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1);   /* file_format */
49090     sqlite3VdbeUsesBtree(v, iDb);
49091     lbl = sqlite3VdbeMakeLabel(v);
49092     sqlite3VdbeAddOp(v, OP_If, 0, lbl);
49093     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
49094                   1 : SQLITE_MAX_FILE_FORMAT;
49095     sqlite3VdbeAddOp(v, OP_Integer, fileFormat, 0);
49096     sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
49097     sqlite3VdbeAddOp(v, OP_Integer, ENC(db), 0);
49098     sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 4);
49099     sqlite3VdbeResolveLabel(v, lbl);
49100
49101     /* This just creates a place-holder record in the sqlite_master table.
49102     ** The record created does not contain anything yet.  It will be replaced
49103     ** by the real entry in code generated at sqlite3EndTable().
49104     **
49105     ** The rowid for the new entry is left on the top of the stack.
49106     ** The rowid value is needed by the code that sqlite3EndTable will
49107     ** generate.
49108     */
49109 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
49110     if( isView || isVirtual ){
49111       sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
49112     }else
49113 #endif
49114     {
49115       sqlite3VdbeAddOp(v, OP_CreateTable, iDb, 0);
49116     }
49117     sqlite3OpenMasterTable(pParse, iDb);
49118     sqlite3VdbeAddOp(v, OP_NewRowid, 0, 0);
49119     sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
49120     sqlite3VdbeAddOp(v, OP_Null, 0, 0);
49121     sqlite3VdbeAddOp(v, OP_Insert, 0, OPFLAG_APPEND);
49122     sqlite3VdbeAddOp(v, OP_Close, 0, 0);
49123     sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
49124   }
49125
49126   /* Normal (non-error) return. */
49127   return;
49128
49129   /* If an error occurs, we jump here */
49130 begin_table_error:
49131   sqlite3_free(zName);
49132   return;
49133 }
49134
49135 /*
49136 ** This macro is used to compare two strings in a case-insensitive manner.
49137 ** It is slightly faster than calling sqlite3StrICmp() directly, but
49138 ** produces larger code.
49139 **
49140 ** WARNING: This macro is not compatible with the strcmp() family. It
49141 ** returns true if the two strings are equal, otherwise false.
49142 */
49143 #define STRICMP(x, y) (\
49144 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
49145 sqlite3UpperToLower[*(unsigned char *)(y)]     \
49146 && sqlite3StrICmp((x)+1,(y)+1)==0 )
49147
49148 /*
49149 ** Add a new column to the table currently being constructed.
49150 **
49151 ** The parser calls this routine once for each column declaration
49152 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
49153 ** first to get things going.  Then this routine is called for each
49154 ** column.
49155 */
49156 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
49157   Table *p;
49158   int i;
49159   char *z;
49160   Column *pCol;
49161   if( (p = pParse->pNewTable)==0 ) return;
49162   if( p->nCol+1>SQLITE_MAX_COLUMN ){
49163     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
49164     return;
49165   }
49166   z = sqlite3NameFromToken(pParse->db, pName);
49167   if( z==0 ) return;
49168   for(i=0; i<p->nCol; i++){
49169     if( STRICMP(z, p->aCol[i].zName) ){
49170       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
49171       sqlite3_free(z);
49172       return;
49173     }
49174   }
49175   if( (p->nCol & 0x7)==0 ){
49176     Column *aNew;
49177     aNew = sqlite3DbRealloc(pParse->db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
49178     if( aNew==0 ){
49179       sqlite3_free(z);
49180       return;
49181     }
49182     p->aCol = aNew;
49183   }
49184   pCol = &p->aCol[p->nCol];
49185   memset(pCol, 0, sizeof(p->aCol[0]));
49186   pCol->zName = z;
49187  
49188   /* If there is no type specified, columns have the default affinity
49189   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
49190   ** be called next to set pCol->affinity correctly.
49191   */
49192   pCol->affinity = SQLITE_AFF_NONE;
49193   p->nCol++;
49194 }
49195
49196 /*
49197 ** This routine is called by the parser while in the middle of
49198 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
49199 ** been seen on a column.  This routine sets the notNull flag on
49200 ** the column currently under construction.
49201 */
49202 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
49203   Table *p;
49204   int i;
49205   if( (p = pParse->pNewTable)==0 ) return;
49206   i = p->nCol-1;
49207   if( i>=0 ) p->aCol[i].notNull = onError;
49208 }
49209
49210 /*
49211 ** Scan the column type name zType (length nType) and return the
49212 ** associated affinity type.
49213 **
49214 ** This routine does a case-independent search of zType for the 
49215 ** substrings in the following table. If one of the substrings is
49216 ** found, the corresponding affinity is returned. If zType contains
49217 ** more than one of the substrings, entries toward the top of 
49218 ** the table take priority. For example, if zType is 'BLOBINT', 
49219 ** SQLITE_AFF_INTEGER is returned.
49220 **
49221 ** Substring     | Affinity
49222 ** --------------------------------
49223 ** 'INT'         | SQLITE_AFF_INTEGER
49224 ** 'CHAR'        | SQLITE_AFF_TEXT
49225 ** 'CLOB'        | SQLITE_AFF_TEXT
49226 ** 'TEXT'        | SQLITE_AFF_TEXT
49227 ** 'BLOB'        | SQLITE_AFF_NONE
49228 ** 'REAL'        | SQLITE_AFF_REAL
49229 ** 'FLOA'        | SQLITE_AFF_REAL
49230 ** 'DOUB'        | SQLITE_AFF_REAL
49231 **
49232 ** If none of the substrings in the above table are found,
49233 ** SQLITE_AFF_NUMERIC is returned.
49234 */
49235 SQLITE_PRIVATE char sqlite3AffinityType(const Token *pType){
49236   u32 h = 0;
49237   char aff = SQLITE_AFF_NUMERIC;
49238   const unsigned char *zIn = pType->z;
49239   const unsigned char *zEnd = &pType->z[pType->n];
49240
49241   while( zIn!=zEnd ){
49242     h = (h<<8) + sqlite3UpperToLower[*zIn];
49243     zIn++;
49244     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
49245       aff = SQLITE_AFF_TEXT; 
49246     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
49247       aff = SQLITE_AFF_TEXT;
49248     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
49249       aff = SQLITE_AFF_TEXT;
49250     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
49251         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
49252       aff = SQLITE_AFF_NONE;
49253 #ifndef SQLITE_OMIT_FLOATING_POINT
49254     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
49255         && aff==SQLITE_AFF_NUMERIC ){
49256       aff = SQLITE_AFF_REAL;
49257     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
49258         && aff==SQLITE_AFF_NUMERIC ){
49259       aff = SQLITE_AFF_REAL;
49260     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
49261         && aff==SQLITE_AFF_NUMERIC ){
49262       aff = SQLITE_AFF_REAL;
49263 #endif
49264     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
49265       aff = SQLITE_AFF_INTEGER;
49266       break;
49267     }
49268   }
49269
49270   return aff;
49271 }
49272
49273 /*
49274 ** This routine is called by the parser while in the middle of
49275 ** parsing a CREATE TABLE statement.  The pFirst token is the first
49276 ** token in the sequence of tokens that describe the type of the
49277 ** column currently under construction.   pLast is the last token
49278 ** in the sequence.  Use this information to construct a string
49279 ** that contains the typename of the column and store that string
49280 ** in zType.
49281 */ 
49282 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
49283   Table *p;
49284   int i;
49285   Column *pCol;
49286
49287   if( (p = pParse->pNewTable)==0 ) return;
49288   i = p->nCol-1;
49289   if( i<0 ) return;
49290   pCol = &p->aCol[i];
49291   sqlite3_free(pCol->zType);
49292   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
49293   pCol->affinity = sqlite3AffinityType(pType);
49294 }
49295
49296 /*
49297 ** The expression is the default value for the most recently added column
49298 ** of the table currently under construction.
49299 **
49300 ** Default value expressions must be constant.  Raise an exception if this
49301 ** is not the case.
49302 **
49303 ** This routine is called by the parser while in the middle of
49304 ** parsing a CREATE TABLE statement.
49305 */
49306 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
49307   Table *p;
49308   Column *pCol;
49309   if( (p = pParse->pNewTable)!=0 ){
49310     pCol = &(p->aCol[p->nCol-1]);
49311     if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
49312       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
49313           pCol->zName);
49314     }else{
49315       Expr *pCopy;
49316       sqlite3 *db = pParse->db;
49317       sqlite3ExprDelete(pCol->pDflt);
49318       pCol->pDflt = pCopy = sqlite3ExprDup(db, pExpr);
49319       if( pCopy ){
49320         sqlite3TokenCopy(db, &pCopy->span, &pExpr->span);
49321       }
49322     }
49323   }
49324   sqlite3ExprDelete(pExpr);
49325 }
49326
49327 /*
49328 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
49329 ** of columns that form the primary key.  If pList is NULL, then the
49330 ** most recently added column of the table is the primary key.
49331 **
49332 ** A table can have at most one primary key.  If the table already has
49333 ** a primary key (and this is the second primary key) then create an
49334 ** error.
49335 **
49336 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
49337 ** then we will try to use that column as the rowid.  Set the Table.iPKey
49338 ** field of the table under construction to be the index of the
49339 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
49340 ** no INTEGER PRIMARY KEY.
49341 **
49342 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
49343 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
49344 */
49345 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
49346   Parse *pParse,    /* Parsing context */
49347   ExprList *pList,  /* List of field names to be indexed */
49348   int onError,      /* What to do with a uniqueness conflict */
49349   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
49350   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
49351 ){
49352   Table *pTab = pParse->pNewTable;
49353   char *zType = 0;
49354   int iCol = -1, i;
49355   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
49356   if( pTab->hasPrimKey ){
49357     sqlite3ErrorMsg(pParse, 
49358       "table \"%s\" has more than one primary key", pTab->zName);
49359     goto primary_key_exit;
49360   }
49361   pTab->hasPrimKey = 1;
49362   if( pList==0 ){
49363     iCol = pTab->nCol - 1;
49364     pTab->aCol[iCol].isPrimKey = 1;
49365   }else{
49366     for(i=0; i<pList->nExpr; i++){
49367       for(iCol=0; iCol<pTab->nCol; iCol++){
49368         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
49369           break;
49370         }
49371       }
49372       if( iCol<pTab->nCol ){
49373         pTab->aCol[iCol].isPrimKey = 1;
49374       }
49375     }
49376     if( pList->nExpr>1 ) iCol = -1;
49377   }
49378   if( iCol>=0 && iCol<pTab->nCol ){
49379     zType = pTab->aCol[iCol].zType;
49380   }
49381   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
49382         && sortOrder==SQLITE_SO_ASC ){
49383     pTab->iPKey = iCol;
49384     pTab->keyConf = onError;
49385     pTab->autoInc = autoInc;
49386   }else if( autoInc ){
49387 #ifndef SQLITE_OMIT_AUTOINCREMENT
49388     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
49389        "INTEGER PRIMARY KEY");
49390 #endif
49391   }else{
49392     sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
49393     pList = 0;
49394   }
49395
49396 primary_key_exit:
49397   sqlite3ExprListDelete(pList);
49398   return;
49399 }
49400
49401 /*
49402 ** Add a new CHECK constraint to the table currently under construction.
49403 */
49404 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
49405   Parse *pParse,    /* Parsing context */
49406   Expr *pCheckExpr  /* The check expression */
49407 ){
49408 #ifndef SQLITE_OMIT_CHECK
49409   Table *pTab = pParse->pNewTable;
49410   sqlite3 *db = pParse->db;
49411   if( pTab && !IN_DECLARE_VTAB ){
49412     /* The CHECK expression must be duplicated so that tokens refer
49413     ** to malloced space and not the (ephemeral) text of the CREATE TABLE
49414     ** statement */
49415     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, 
49416                                   sqlite3ExprDup(db, pCheckExpr));
49417   }
49418 #endif
49419   sqlite3ExprDelete(pCheckExpr);
49420 }
49421
49422 /*
49423 ** Set the collation function of the most recently parsed table column
49424 ** to the CollSeq given.
49425 */
49426 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
49427   Table *p;
49428   int i;
49429   char *zColl;              /* Dequoted name of collation sequence */
49430
49431   if( (p = pParse->pNewTable)==0 ) return;
49432   i = p->nCol-1;
49433
49434   zColl = sqlite3NameFromToken(pParse->db, pToken);
49435   if( !zColl ) return;
49436
49437   if( sqlite3LocateCollSeq(pParse, zColl, -1) ){
49438     Index *pIdx;
49439     p->aCol[i].zColl = zColl;
49440   
49441     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
49442     ** then an index may have been created on this column before the
49443     ** collation type was added. Correct this if it is the case.
49444     */
49445     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
49446       assert( pIdx->nColumn==1 );
49447       if( pIdx->aiColumn[0]==i ){
49448         pIdx->azColl[0] = p->aCol[i].zColl;
49449       }
49450     }
49451   }else{
49452     sqlite3_free(zColl);
49453   }
49454 }
49455
49456 /*
49457 ** This function returns the collation sequence for database native text
49458 ** encoding identified by the string zName, length nName.
49459 **
49460 ** If the requested collation sequence is not available, or not available
49461 ** in the database native encoding, the collation factory is invoked to
49462 ** request it. If the collation factory does not supply such a sequence,
49463 ** and the sequence is available in another text encoding, then that is
49464 ** returned instead.
49465 **
49466 ** If no versions of the requested collations sequence are available, or
49467 ** another error occurs, NULL is returned and an error message written into
49468 ** pParse.
49469 **
49470 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
49471 ** invokes the collation factory if the named collation cannot be found
49472 ** and generates an error message.
49473 */
49474 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
49475   sqlite3 *db = pParse->db;
49476   u8 enc = ENC(db);
49477   u8 initbusy = db->init.busy;
49478   CollSeq *pColl;
49479
49480   pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
49481   if( !initbusy && (!pColl || !pColl->xCmp) ){
49482     pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
49483     if( !pColl ){
49484       if( nName<0 ){
49485         nName = strlen(zName);
49486       }
49487       sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
49488       pColl = 0;
49489     }
49490   }
49491
49492   return pColl;
49493 }
49494
49495
49496 /*
49497 ** Generate code that will increment the schema cookie.
49498 **
49499 ** The schema cookie is used to determine when the schema for the
49500 ** database changes.  After each schema change, the cookie value
49501 ** changes.  When a process first reads the schema it records the
49502 ** cookie.  Thereafter, whenever it goes to access the database,
49503 ** it checks the cookie to make sure the schema has not changed
49504 ** since it was last read.
49505 **
49506 ** This plan is not completely bullet-proof.  It is possible for
49507 ** the schema to change multiple times and for the cookie to be
49508 ** set back to prior value.  But schema changes are infrequent
49509 ** and the probability of hitting the same cookie value is only
49510 ** 1 chance in 2^32.  So we're safe enough.
49511 */
49512 SQLITE_PRIVATE void sqlite3ChangeCookie(sqlite3 *db, Vdbe *v, int iDb){
49513   sqlite3VdbeAddOp(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, 0);
49514   sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 0);
49515 }
49516
49517 /*
49518 ** Measure the number of characters needed to output the given
49519 ** identifier.  The number returned includes any quotes used
49520 ** but does not include the null terminator.
49521 **
49522 ** The estimate is conservative.  It might be larger that what is
49523 ** really needed.
49524 */
49525 static int identLength(const char *z){
49526   int n;
49527   for(n=0; *z; n++, z++){
49528     if( *z=='"' ){ n++; }
49529   }
49530   return n + 2;
49531 }
49532
49533 /*
49534 ** Write an identifier onto the end of the given string.  Add
49535 ** quote characters as needed.
49536 */
49537 static void identPut(char *z, int *pIdx, char *zSignedIdent){
49538   unsigned char *zIdent = (unsigned char*)zSignedIdent;
49539   int i, j, needQuote;
49540   i = *pIdx;
49541   for(j=0; zIdent[j]; j++){
49542     if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
49543   }
49544   needQuote =  zIdent[j]!=0 || isdigit(zIdent[0])
49545                   || sqlite3KeywordCode(zIdent, j)!=TK_ID;
49546   if( needQuote ) z[i++] = '"';
49547   for(j=0; zIdent[j]; j++){
49548     z[i++] = zIdent[j];
49549     if( zIdent[j]=='"' ) z[i++] = '"';
49550   }
49551   if( needQuote ) z[i++] = '"';
49552   z[i] = 0;
49553   *pIdx = i;
49554 }
49555
49556 /*
49557 ** Generate a CREATE TABLE statement appropriate for the given
49558 ** table.  Memory to hold the text of the statement is obtained
49559 ** from sqliteMalloc() and must be freed by the calling function.
49560 */
49561 static char *createTableStmt(Table *p, int isTemp){
49562   int i, k, n;
49563   char *zStmt;
49564   char *zSep, *zSep2, *zEnd, *z;
49565   Column *pCol;
49566   n = 0;
49567   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
49568     n += identLength(pCol->zName);
49569     z = pCol->zType;
49570     if( z ){
49571       n += (strlen(z) + 1);
49572     }
49573   }
49574   n += identLength(p->zName);
49575   if( n<50 ){
49576     zSep = "";
49577     zSep2 = ",";
49578     zEnd = ")";
49579   }else{
49580     zSep = "\n  ";
49581     zSep2 = ",\n  ";
49582     zEnd = "\n)";
49583   }
49584   n += 35 + 6*p->nCol;
49585   zStmt = sqlite3_malloc( n );
49586   if( zStmt==0 ) return 0;
49587   sqlite3_snprintf(n, zStmt,
49588                   !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
49589   k = strlen(zStmt);
49590   identPut(zStmt, &k, p->zName);
49591   zStmt[k++] = '(';
49592   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
49593     sqlite3_snprintf(n-k, &zStmt[k], zSep);
49594     k += strlen(&zStmt[k]);
49595     zSep = zSep2;
49596     identPut(zStmt, &k, pCol->zName);
49597     if( (z = pCol->zType)!=0 ){
49598       zStmt[k++] = ' ';
49599       assert( strlen(z)+k+1<=n );
49600       sqlite3_snprintf(n-k, &zStmt[k], "%s", z);
49601       k += strlen(z);
49602     }
49603   }
49604   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
49605   return zStmt;
49606 }
49607
49608 /*
49609 ** This routine is called to report the final ")" that terminates
49610 ** a CREATE TABLE statement.
49611 **
49612 ** The table structure that other action routines have been building
49613 ** is added to the internal hash tables, assuming no errors have
49614 ** occurred.
49615 **
49616 ** An entry for the table is made in the master table on disk, unless
49617 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
49618 ** it means we are reading the sqlite_master table because we just
49619 ** connected to the database or because the sqlite_master table has
49620 ** recently changed, so the entry for this table already exists in
49621 ** the sqlite_master table.  We do not want to create it again.
49622 **
49623 ** If the pSelect argument is not NULL, it means that this routine
49624 ** was called to create a table generated from a 
49625 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
49626 ** the new table will match the result set of the SELECT.
49627 */
49628 SQLITE_PRIVATE void sqlite3EndTable(
49629   Parse *pParse,          /* Parse context */
49630   Token *pCons,           /* The ',' token after the last column defn. */
49631   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
49632   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
49633 ){
49634   Table *p;
49635   sqlite3 *db = pParse->db;
49636   int iDb;
49637
49638   if( (pEnd==0 && pSelect==0) || pParse->nErr || db->mallocFailed ) {
49639     return;
49640   }
49641   p = pParse->pNewTable;
49642   if( p==0 ) return;
49643
49644   assert( !db->init.busy || !pSelect );
49645
49646   iDb = sqlite3SchemaToIndex(db, p->pSchema);
49647
49648 #ifndef SQLITE_OMIT_CHECK
49649   /* Resolve names in all CHECK constraint expressions.
49650   */
49651   if( p->pCheck ){
49652     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
49653     NameContext sNC;                /* Name context for pParse->pNewTable */
49654
49655     memset(&sNC, 0, sizeof(sNC));
49656     memset(&sSrc, 0, sizeof(sSrc));
49657     sSrc.nSrc = 1;
49658     sSrc.a[0].zName = p->zName;
49659     sSrc.a[0].pTab = p;
49660     sSrc.a[0].iCursor = -1;
49661     sNC.pParse = pParse;
49662     sNC.pSrcList = &sSrc;
49663     sNC.isCheck = 1;
49664     if( sqlite3ExprResolveNames(&sNC, p->pCheck) ){
49665       return;
49666     }
49667   }
49668 #endif /* !defined(SQLITE_OMIT_CHECK) */
49669
49670   /* If the db->init.busy is 1 it means we are reading the SQL off the
49671   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
49672   ** So do not write to the disk again.  Extract the root page number
49673   ** for the table from the db->init.newTnum field.  (The page number
49674   ** should have been put there by the sqliteOpenCb routine.)
49675   */
49676   if( db->init.busy ){
49677     p->tnum = db->init.newTnum;
49678   }
49679
49680   /* If not initializing, then create a record for the new table
49681   ** in the SQLITE_MASTER table of the database.  The record number
49682   ** for the new table entry should already be on the stack.
49683   **
49684   ** If this is a TEMPORARY table, write the entry into the auxiliary
49685   ** file instead of into the main database file.
49686   */
49687   if( !db->init.busy ){
49688     int n;
49689     Vdbe *v;
49690     char *zType;    /* "view" or "table" */
49691     char *zType2;   /* "VIEW" or "TABLE" */
49692     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
49693
49694     v = sqlite3GetVdbe(pParse);
49695     if( v==0 ) return;
49696
49697     sqlite3VdbeAddOp(v, OP_Close, 0, 0);
49698
49699     /* Create the rootpage for the new table and push it onto the stack.
49700     ** A view has no rootpage, so just push a zero onto the stack for
49701     ** views.  Initialize zType at the same time.
49702     */
49703     if( p->pSelect==0 ){
49704       /* A regular table */
49705       zType = "table";
49706       zType2 = "TABLE";
49707 #ifndef SQLITE_OMIT_VIEW
49708     }else{
49709       /* A view */
49710       zType = "view";
49711       zType2 = "VIEW";
49712 #endif
49713     }
49714
49715     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
49716     ** statement to populate the new table. The root-page number for the
49717     ** new table is on the top of the vdbe stack.
49718     **
49719     ** Once the SELECT has been coded by sqlite3Select(), it is in a
49720     ** suitable state to query for the column names and types to be used
49721     ** by the new table.
49722     **
49723     ** A shared-cache write-lock is not required to write to the new table,
49724     ** as a schema-lock must have already been obtained to create it. Since
49725     ** a schema-lock excludes all other database users, the write-lock would
49726     ** be redundant.
49727     */
49728     if( pSelect ){
49729       Table *pSelTab;
49730       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
49731       sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
49732       sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0);
49733       pParse->nTab = 2;
49734       sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0);
49735       sqlite3VdbeAddOp(v, OP_Close, 1, 0);
49736       if( pParse->nErr==0 ){
49737         pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect);
49738         if( pSelTab==0 ) return;
49739         assert( p->aCol==0 );
49740         p->nCol = pSelTab->nCol;
49741         p->aCol = pSelTab->aCol;
49742         pSelTab->nCol = 0;
49743         pSelTab->aCol = 0;
49744         sqlite3DeleteTable(pSelTab);
49745       }
49746     }
49747
49748     /* Compute the complete text of the CREATE statement */
49749     if( pSelect ){
49750       zStmt = createTableStmt(p, p->pSchema==db->aDb[1].pSchema);
49751     }else{
49752       n = pEnd->z - pParse->sNameToken.z + 1;
49753       zStmt = sqlite3MPrintf(db, 
49754           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
49755       );
49756     }
49757
49758     /* A slot for the record has already been allocated in the 
49759     ** SQLITE_MASTER table.  We just need to update that slot with all
49760     ** the information we've collected.  The rowid for the preallocated
49761     ** slot is the 2nd item on the stack.  The top of the stack is the
49762     ** root page for the new table (or a 0 if this is a view).
49763     */
49764     sqlite3NestedParse(pParse,
49765       "UPDATE %Q.%s "
49766          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#0, sql=%Q "
49767        "WHERE rowid=#1",
49768       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
49769       zType,
49770       p->zName,
49771       p->zName,
49772       zStmt
49773     );
49774     sqlite3_free(zStmt);
49775     sqlite3ChangeCookie(db, v, iDb);
49776
49777 #ifndef SQLITE_OMIT_AUTOINCREMENT
49778     /* Check to see if we need to create an sqlite_sequence table for
49779     ** keeping track of autoincrement keys.
49780     */
49781     if( p->autoInc ){
49782       Db *pDb = &db->aDb[iDb];
49783       if( pDb->pSchema->pSeqTab==0 ){
49784         sqlite3NestedParse(pParse,
49785           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
49786           pDb->zName
49787         );
49788       }
49789     }
49790 #endif
49791
49792     /* Reparse everything to update our internal data structures */
49793     sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
49794         sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P3_DYNAMIC);
49795   }
49796
49797
49798   /* Add the table to the in-memory representation of the database.
49799   */
49800   if( db->init.busy && pParse->nErr==0 ){
49801     Table *pOld;
49802     FKey *pFKey; 
49803     Schema *pSchema = p->pSchema;
49804     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p);
49805     if( pOld ){
49806       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
49807       db->mallocFailed = 1;
49808       return;
49809     }
49810 #ifndef SQLITE_OMIT_FOREIGN_KEY
49811     for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
49812       void *data;
49813       int nTo = strlen(pFKey->zTo) + 1;
49814       pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
49815       data = sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
49816       if( data==(void *)pFKey ){
49817         db->mallocFailed = 1;
49818       }
49819     }
49820 #endif
49821     pParse->pNewTable = 0;
49822     db->nTable++;
49823     db->flags |= SQLITE_InternChanges;
49824
49825 #ifndef SQLITE_OMIT_ALTERTABLE
49826     if( !p->pSelect ){
49827       const char *zName = (const char *)pParse->sNameToken.z;
49828       int nName;
49829       assert( !pSelect && pCons && pEnd );
49830       if( pCons->z==0 ){
49831         pCons = pEnd;
49832       }
49833       nName = (const char *)pCons->z - zName;
49834       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
49835     }
49836 #endif
49837   }
49838 }
49839
49840 #ifndef SQLITE_OMIT_VIEW
49841 /*
49842 ** The parser calls this routine in order to create a new VIEW
49843 */
49844 SQLITE_PRIVATE void sqlite3CreateView(
49845   Parse *pParse,     /* The parsing context */
49846   Token *pBegin,     /* The CREATE token that begins the statement */
49847   Token *pName1,     /* The token that holds the name of the view */
49848   Token *pName2,     /* The token that holds the name of the view */
49849   Select *pSelect,   /* A SELECT statement that will become the new view */
49850   int isTemp,        /* TRUE for a TEMPORARY view */
49851   int noErr          /* Suppress error messages if VIEW already exists */
49852 ){
49853   Table *p;
49854   int n;
49855   const unsigned char *z;
49856   Token sEnd;
49857   DbFixer sFix;
49858   Token *pName;
49859   int iDb;
49860   sqlite3 *db = pParse->db;
49861
49862   if( pParse->nVar>0 ){
49863     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
49864     sqlite3SelectDelete(pSelect);
49865     return;
49866   }
49867   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
49868   p = pParse->pNewTable;
49869   if( p==0 || pParse->nErr ){
49870     sqlite3SelectDelete(pSelect);
49871     return;
49872   }
49873   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
49874   iDb = sqlite3SchemaToIndex(db, p->pSchema);
49875   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
49876     && sqlite3FixSelect(&sFix, pSelect)
49877   ){
49878     sqlite3SelectDelete(pSelect);
49879     return;
49880   }
49881
49882   /* Make a copy of the entire SELECT statement that defines the view.
49883   ** This will force all the Expr.token.z values to be dynamically
49884   ** allocated rather than point to the input string - which means that
49885   ** they will persist after the current sqlite3_exec() call returns.
49886   */
49887   p->pSelect = sqlite3SelectDup(db, pSelect);
49888   sqlite3SelectDelete(pSelect);
49889   if( db->mallocFailed ){
49890     return;
49891   }
49892   if( !db->init.busy ){
49893     sqlite3ViewGetColumnNames(pParse, p);
49894   }
49895
49896   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
49897   ** the end.
49898   */
49899   sEnd = pParse->sLastToken;
49900   if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
49901     sEnd.z += sEnd.n;
49902   }
49903   sEnd.n = 0;
49904   n = sEnd.z - pBegin->z;
49905   z = (const unsigned char*)pBegin->z;
49906   while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
49907   sEnd.z = &z[n-1];
49908   sEnd.n = 1;
49909
49910   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
49911   sqlite3EndTable(pParse, 0, &sEnd, 0);
49912   return;
49913 }
49914 #endif /* SQLITE_OMIT_VIEW */
49915
49916 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
49917 /*
49918 ** The Table structure pTable is really a VIEW.  Fill in the names of
49919 ** the columns of the view in the pTable structure.  Return the number
49920 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
49921 */
49922 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
49923   Table *pSelTab;   /* A fake table from which we get the result set */
49924   Select *pSel;     /* Copy of the SELECT that implements the view */
49925   int nErr = 0;     /* Number of errors encountered */
49926   int n;            /* Temporarily holds the number of cursors assigned */
49927   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
49928   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
49929
49930   assert( pTable );
49931
49932 #ifndef SQLITE_OMIT_VIRTUALTABLE
49933   if( sqlite3VtabCallConnect(pParse, pTable) ){
49934     return SQLITE_ERROR;
49935   }
49936   if( IsVirtual(pTable) ) return 0;
49937 #endif
49938
49939 #ifndef SQLITE_OMIT_VIEW
49940   /* A positive nCol means the columns names for this view are
49941   ** already known.
49942   */
49943   if( pTable->nCol>0 ) return 0;
49944
49945   /* A negative nCol is a special marker meaning that we are currently
49946   ** trying to compute the column names.  If we enter this routine with
49947   ** a negative nCol, it means two or more views form a loop, like this:
49948   **
49949   **     CREATE VIEW one AS SELECT * FROM two;
49950   **     CREATE VIEW two AS SELECT * FROM one;
49951   **
49952   ** Actually, this error is caught previously and so the following test
49953   ** should always fail.  But we will leave it in place just to be safe.
49954   */
49955   if( pTable->nCol<0 ){
49956     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
49957     return 1;
49958   }
49959   assert( pTable->nCol>=0 );
49960
49961   /* If we get this far, it means we need to compute the table names.
49962   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
49963   ** "*" elements in the results set of the view and will assign cursors
49964   ** to the elements of the FROM clause.  But we do not want these changes
49965   ** to be permanent.  So the computation is done on a copy of the SELECT
49966   ** statement that defines the view.
49967   */
49968   assert( pTable->pSelect );
49969   pSel = sqlite3SelectDup(db, pTable->pSelect);
49970   if( pSel ){
49971     n = pParse->nTab;
49972     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
49973     pTable->nCol = -1;
49974 #ifndef SQLITE_OMIT_AUTHORIZATION
49975     xAuth = db->xAuth;
49976     db->xAuth = 0;
49977     pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
49978     db->xAuth = xAuth;
49979 #else
49980     pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
49981 #endif
49982     pParse->nTab = n;
49983     if( pSelTab ){
49984       assert( pTable->aCol==0 );
49985       pTable->nCol = pSelTab->nCol;
49986       pTable->aCol = pSelTab->aCol;
49987       pSelTab->nCol = 0;
49988       pSelTab->aCol = 0;
49989       sqlite3DeleteTable(pSelTab);
49990       pTable->pSchema->flags |= DB_UnresetViews;
49991     }else{
49992       pTable->nCol = 0;
49993       nErr++;
49994     }
49995     sqlite3SelectDelete(pSel);
49996   } else {
49997     nErr++;
49998   }
49999 #endif /* SQLITE_OMIT_VIEW */
50000   return nErr;  
50001 }
50002 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
50003
50004 #ifndef SQLITE_OMIT_VIEW
50005 /*
50006 ** Clear the column names from every VIEW in database idx.
50007 */
50008 static void sqliteViewResetAll(sqlite3 *db, int idx){
50009   HashElem *i;
50010   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
50011   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
50012     Table *pTab = sqliteHashData(i);
50013     if( pTab->pSelect ){
50014       sqliteResetColumnNames(pTab);
50015     }
50016   }
50017   DbClearProperty(db, idx, DB_UnresetViews);
50018 }
50019 #else
50020 # define sqliteViewResetAll(A,B)
50021 #endif /* SQLITE_OMIT_VIEW */
50022
50023 /*
50024 ** This function is called by the VDBE to adjust the internal schema
50025 ** used by SQLite when the btree layer moves a table root page. The
50026 ** root-page of a table or index in database iDb has changed from iFrom
50027 ** to iTo.
50028 **
50029 ** Ticket #1728:  The symbol table might still contain information
50030 ** on tables and/or indices that are the process of being deleted.
50031 ** If you are unlucky, one of those deleted indices or tables might
50032 ** have the same rootpage number as the real table or index that is
50033 ** being moved.  So we cannot stop searching after the first match 
50034 ** because the first match might be for one of the deleted indices
50035 ** or tables and not the table/index that is actually being moved.
50036 ** We must continue looping until all tables and indices with
50037 ** rootpage==iFrom have been converted to have a rootpage of iTo
50038 ** in order to be certain that we got the right one.
50039 */
50040 #ifndef SQLITE_OMIT_AUTOVACUUM
50041 SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
50042   HashElem *pElem;
50043   Hash *pHash;
50044
50045   pHash = &pDb->pSchema->tblHash;
50046   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
50047     Table *pTab = sqliteHashData(pElem);
50048     if( pTab->tnum==iFrom ){
50049       pTab->tnum = iTo;
50050     }
50051   }
50052   pHash = &pDb->pSchema->idxHash;
50053   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
50054     Index *pIdx = sqliteHashData(pElem);
50055     if( pIdx->tnum==iFrom ){
50056       pIdx->tnum = iTo;
50057     }
50058   }
50059 }
50060 #endif
50061
50062 /*
50063 ** Write code to erase the table with root-page iTable from database iDb.
50064 ** Also write code to modify the sqlite_master table and internal schema
50065 ** if a root-page of another table is moved by the btree-layer whilst
50066 ** erasing iTable (this can happen with an auto-vacuum database).
50067 */ 
50068 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
50069   Vdbe *v = sqlite3GetVdbe(pParse);
50070   sqlite3VdbeAddOp(v, OP_Destroy, iTable, iDb);
50071 #ifndef SQLITE_OMIT_AUTOVACUUM
50072   /* OP_Destroy pushes an integer onto the stack. If this integer
50073   ** is non-zero, then it is the root page number of a table moved to
50074   ** location iTable. The following code modifies the sqlite_master table to
50075   ** reflect this.
50076   **
50077   ** The "#0" in the SQL is a special constant that means whatever value
50078   ** is on the top of the stack.  See sqlite3RegisterExpr().
50079   */
50080   sqlite3NestedParse(pParse, 
50081      "UPDATE %Q.%s SET rootpage=%d WHERE #0 AND rootpage=#0",
50082      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable);
50083 #endif
50084 }
50085
50086 /*
50087 ** Write VDBE code to erase table pTab and all associated indices on disk.
50088 ** Code to update the sqlite_master tables and internal schema definitions
50089 ** in case a root-page belonging to another table is moved by the btree layer
50090 ** is also added (this can happen with an auto-vacuum database).
50091 */
50092 static void destroyTable(Parse *pParse, Table *pTab){
50093 #ifdef SQLITE_OMIT_AUTOVACUUM
50094   Index *pIdx;
50095   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
50096   destroyRootPage(pParse, pTab->tnum, iDb);
50097   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
50098     destroyRootPage(pParse, pIdx->tnum, iDb);
50099   }
50100 #else
50101   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
50102   ** is not defined), then it is important to call OP_Destroy on the
50103   ** table and index root-pages in order, starting with the numerically 
50104   ** largest root-page number. This guarantees that none of the root-pages
50105   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
50106   ** following were coded:
50107   **
50108   ** OP_Destroy 4 0
50109   ** ...
50110   ** OP_Destroy 5 0
50111   **
50112   ** and root page 5 happened to be the largest root-page number in the
50113   ** database, then root page 5 would be moved to page 4 by the 
50114   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
50115   ** a free-list page.
50116   */
50117   int iTab = pTab->tnum;
50118   int iDestroyed = 0;
50119
50120   while( 1 ){
50121     Index *pIdx;
50122     int iLargest = 0;
50123
50124     if( iDestroyed==0 || iTab<iDestroyed ){
50125       iLargest = iTab;
50126     }
50127     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
50128       int iIdx = pIdx->tnum;
50129       assert( pIdx->pSchema==pTab->pSchema );
50130       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
50131         iLargest = iIdx;
50132       }
50133     }
50134     if( iLargest==0 ){
50135       return;
50136     }else{
50137       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
50138       destroyRootPage(pParse, iLargest, iDb);
50139       iDestroyed = iLargest;
50140     }
50141   }
50142 #endif
50143 }
50144
50145 /*
50146 ** This routine is called to do the work of a DROP TABLE statement.
50147 ** pName is the name of the table to be dropped.
50148 */
50149 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
50150   Table *pTab;
50151   Vdbe *v;
50152   sqlite3 *db = pParse->db;
50153   int iDb;
50154
50155   if( pParse->nErr || db->mallocFailed ){
50156     goto exit_drop_table;
50157   }
50158   assert( pName->nSrc==1 );
50159   pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase);
50160
50161   if( pTab==0 ){
50162     if( noErr ){
50163       sqlite3ErrorClear(pParse);
50164     }
50165     goto exit_drop_table;
50166   }
50167   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
50168   assert( iDb>=0 && iDb<db->nDb );
50169
50170   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
50171   ** it is initialized.
50172   */
50173   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
50174     goto exit_drop_table;
50175   }
50176 #ifndef SQLITE_OMIT_AUTHORIZATION
50177   {
50178     int code;
50179     const char *zTab = SCHEMA_TABLE(iDb);
50180     const char *zDb = db->aDb[iDb].zName;
50181     const char *zArg2 = 0;
50182     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
50183       goto exit_drop_table;
50184     }
50185     if( isView ){
50186       if( !OMIT_TEMPDB && iDb==1 ){
50187         code = SQLITE_DROP_TEMP_VIEW;
50188       }else{
50189         code = SQLITE_DROP_VIEW;
50190       }
50191 #ifndef SQLITE_OMIT_VIRTUALTABLE
50192     }else if( IsVirtual(pTab) ){
50193       code = SQLITE_DROP_VTABLE;
50194       zArg2 = pTab->pMod->zName;
50195 #endif
50196     }else{
50197       if( !OMIT_TEMPDB && iDb==1 ){
50198         code = SQLITE_DROP_TEMP_TABLE;
50199       }else{
50200         code = SQLITE_DROP_TABLE;
50201       }
50202     }
50203     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
50204       goto exit_drop_table;
50205     }
50206     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
50207       goto exit_drop_table;
50208     }
50209   }
50210 #endif
50211   if( pTab->readOnly || pTab==db->aDb[iDb].pSchema->pSeqTab ){
50212     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
50213     goto exit_drop_table;
50214   }
50215
50216 #ifndef SQLITE_OMIT_VIEW
50217   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
50218   ** on a table.
50219   */
50220   if( isView && pTab->pSelect==0 ){
50221     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
50222     goto exit_drop_table;
50223   }
50224   if( !isView && pTab->pSelect ){
50225     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
50226     goto exit_drop_table;
50227   }
50228 #endif
50229
50230   /* Generate code to remove the table from the master table
50231   ** on disk.
50232   */
50233   v = sqlite3GetVdbe(pParse);
50234   if( v ){
50235     Trigger *pTrigger;
50236     Db *pDb = &db->aDb[iDb];
50237     sqlite3BeginWriteOperation(pParse, 1, iDb);
50238
50239 #ifndef SQLITE_OMIT_VIRTUALTABLE
50240     if( IsVirtual(pTab) ){
50241       Vdbe *v = sqlite3GetVdbe(pParse);
50242       if( v ){
50243         sqlite3VdbeAddOp(v, OP_VBegin, 0, 0);
50244       }
50245     }
50246 #endif
50247
50248     /* Drop all triggers associated with the table being dropped. Code
50249     ** is generated to remove entries from sqlite_master and/or
50250     ** sqlite_temp_master if required.
50251     */
50252     pTrigger = pTab->pTrigger;
50253     while( pTrigger ){
50254       assert( pTrigger->pSchema==pTab->pSchema || 
50255           pTrigger->pSchema==db->aDb[1].pSchema );
50256       sqlite3DropTriggerPtr(pParse, pTrigger);
50257       pTrigger = pTrigger->pNext;
50258     }
50259
50260 #ifndef SQLITE_OMIT_AUTOINCREMENT
50261     /* Remove any entries of the sqlite_sequence table associated with
50262     ** the table being dropped. This is done before the table is dropped
50263     ** at the btree level, in case the sqlite_sequence table needs to
50264     ** move as a result of the drop (can happen in auto-vacuum mode).
50265     */
50266     if( pTab->autoInc ){
50267       sqlite3NestedParse(pParse,
50268         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
50269         pDb->zName, pTab->zName
50270       );
50271     }
50272 #endif
50273
50274     /* Drop all SQLITE_MASTER table and index entries that refer to the
50275     ** table. The program name loops through the master table and deletes
50276     ** every row that refers to a table of the same name as the one being
50277     ** dropped. Triggers are handled seperately because a trigger can be
50278     ** created in the temp database that refers to a table in another
50279     ** database.
50280     */
50281     sqlite3NestedParse(pParse, 
50282         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
50283         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
50284     if( !isView && !IsVirtual(pTab) ){
50285       destroyTable(pParse, pTab);
50286     }
50287
50288     /* Remove the table entry from SQLite's internal schema and modify
50289     ** the schema cookie.
50290     */
50291     if( IsVirtual(pTab) ){
50292       sqlite3VdbeOp3(v, OP_VDestroy, iDb, 0, pTab->zName, 0);
50293     }
50294     sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
50295     sqlite3ChangeCookie(db, v, iDb);
50296   }
50297   sqliteViewResetAll(db, iDb);
50298
50299 exit_drop_table:
50300   sqlite3SrcListDelete(pName);
50301 }
50302
50303 /*
50304 ** This routine is called to create a new foreign key on the table
50305 ** currently under construction.  pFromCol determines which columns
50306 ** in the current table point to the foreign key.  If pFromCol==0 then
50307 ** connect the key to the last column inserted.  pTo is the name of
50308 ** the table referred to.  pToCol is a list of tables in the other
50309 ** pTo table that the foreign key points to.  flags contains all
50310 ** information about the conflict resolution algorithms specified
50311 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
50312 **
50313 ** An FKey structure is created and added to the table currently
50314 ** under construction in the pParse->pNewTable field.  The new FKey
50315 ** is not linked into db->aFKey at this point - that does not happen
50316 ** until sqlite3EndTable().
50317 **
50318 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
50319 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
50320 */
50321 SQLITE_PRIVATE void sqlite3CreateForeignKey(
50322   Parse *pParse,       /* Parsing context */
50323   ExprList *pFromCol,  /* Columns in this table that point to other table */
50324   Token *pTo,          /* Name of the other table */
50325   ExprList *pToCol,    /* Columns in the other table */
50326   int flags            /* Conflict resolution algorithms. */
50327 ){
50328 #ifndef SQLITE_OMIT_FOREIGN_KEY
50329   FKey *pFKey = 0;
50330   Table *p = pParse->pNewTable;
50331   int nByte;
50332   int i;
50333   int nCol;
50334   char *z;
50335
50336   assert( pTo!=0 );
50337   if( p==0 || pParse->nErr || IN_DECLARE_VTAB ) goto fk_end;
50338   if( pFromCol==0 ){
50339     int iCol = p->nCol-1;
50340     if( iCol<0 ) goto fk_end;
50341     if( pToCol && pToCol->nExpr!=1 ){
50342       sqlite3ErrorMsg(pParse, "foreign key on %s"
50343          " should reference only one column of table %T",
50344          p->aCol[iCol].zName, pTo);
50345       goto fk_end;
50346     }
50347     nCol = 1;
50348   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
50349     sqlite3ErrorMsg(pParse,
50350         "number of columns in foreign key does not match the number of "
50351         "columns in the referenced table");
50352     goto fk_end;
50353   }else{
50354     nCol = pFromCol->nExpr;
50355   }
50356   nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
50357   if( pToCol ){
50358     for(i=0; i<pToCol->nExpr; i++){
50359       nByte += strlen(pToCol->a[i].zName) + 1;
50360     }
50361   }
50362   pFKey = sqlite3DbMallocZero(pParse->db, nByte );
50363   if( pFKey==0 ){
50364     goto fk_end;
50365   }
50366   pFKey->pFrom = p;
50367   pFKey->pNextFrom = p->pFKey;
50368   z = (char*)&pFKey[1];
50369   pFKey->aCol = (struct sColMap*)z;
50370   z += sizeof(struct sColMap)*nCol;
50371   pFKey->zTo = z;
50372   memcpy(z, pTo->z, pTo->n);
50373   z[pTo->n] = 0;
50374   z += pTo->n+1;
50375   pFKey->pNextTo = 0;
50376   pFKey->nCol = nCol;
50377   if( pFromCol==0 ){
50378     pFKey->aCol[0].iFrom = p->nCol-1;
50379   }else{
50380     for(i=0; i<nCol; i++){
50381       int j;
50382       for(j=0; j<p->nCol; j++){
50383         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
50384           pFKey->aCol[i].iFrom = j;
50385           break;
50386         }
50387       }
50388       if( j>=p->nCol ){
50389         sqlite3ErrorMsg(pParse, 
50390           "unknown column \"%s\" in foreign key definition", 
50391           pFromCol->a[i].zName);
50392         goto fk_end;
50393       }
50394     }
50395   }
50396   if( pToCol ){
50397     for(i=0; i<nCol; i++){
50398       int n = strlen(pToCol->a[i].zName);
50399       pFKey->aCol[i].zCol = z;
50400       memcpy(z, pToCol->a[i].zName, n);
50401       z[n] = 0;
50402       z += n+1;
50403     }
50404   }
50405   pFKey->isDeferred = 0;
50406   pFKey->deleteConf = flags & 0xff;
50407   pFKey->updateConf = (flags >> 8 ) & 0xff;
50408   pFKey->insertConf = (flags >> 16 ) & 0xff;
50409
50410   /* Link the foreign key to the table as the last step.
50411   */
50412   p->pFKey = pFKey;
50413   pFKey = 0;
50414
50415 fk_end:
50416   sqlite3_free(pFKey);
50417 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
50418   sqlite3ExprListDelete(pFromCol);
50419   sqlite3ExprListDelete(pToCol);
50420 }
50421
50422 /*
50423 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
50424 ** clause is seen as part of a foreign key definition.  The isDeferred
50425 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
50426 ** The behavior of the most recently created foreign key is adjusted
50427 ** accordingly.
50428 */
50429 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
50430 #ifndef SQLITE_OMIT_FOREIGN_KEY
50431   Table *pTab;
50432   FKey *pFKey;
50433   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
50434   pFKey->isDeferred = isDeferred;
50435 #endif
50436 }
50437
50438 /*
50439 ** Generate code that will erase and refill index *pIdx.  This is
50440 ** used to initialize a newly created index or to recompute the
50441 ** content of an index in response to a REINDEX command.
50442 **
50443 ** if memRootPage is not negative, it means that the index is newly
50444 ** created.  The memory cell specified by memRootPage contains the
50445 ** root page number of the index.  If memRootPage is negative, then
50446 ** the index already exists and must be cleared before being refilled and
50447 ** the root page number of the index is taken from pIndex->tnum.
50448 */
50449 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
50450   Table *pTab = pIndex->pTable;  /* The table that is indexed */
50451   int iTab = pParse->nTab;       /* Btree cursor used for pTab */
50452   int iIdx = pParse->nTab+1;     /* Btree cursor used for pIndex */
50453   int addr1;                     /* Address of top of loop */
50454   int tnum;                      /* Root page of index */
50455   Vdbe *v;                       /* Generate code into this virtual machine */
50456   KeyInfo *pKey;                 /* KeyInfo for index */
50457   sqlite3 *db = pParse->db;      /* The database connection */
50458   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
50459
50460 #ifndef SQLITE_OMIT_AUTHORIZATION
50461   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
50462       db->aDb[iDb].zName ) ){
50463     return;
50464   }
50465 #endif
50466
50467   /* Require a write-lock on the table to perform this operation */
50468   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
50469
50470   v = sqlite3GetVdbe(pParse);
50471   if( v==0 ) return;
50472   if( memRootPage>=0 ){
50473     sqlite3VdbeAddOp(v, OP_MemLoad, memRootPage, 0);
50474     tnum = 0;
50475   }else{
50476     tnum = pIndex->tnum;
50477     sqlite3VdbeAddOp(v, OP_Clear, tnum, iDb);
50478   }
50479   sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
50480   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
50481   sqlite3VdbeOp3(v, OP_OpenWrite, iIdx, tnum, (char *)pKey, P3_KEYINFO_HANDOFF);
50482   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
50483   addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0);
50484   sqlite3GenerateIndexKey(v, pIndex, iTab);
50485   if( pIndex->onError!=OE_None ){
50486     int curaddr = sqlite3VdbeCurrentAddr(v);
50487     int addr2 = curaddr+4;
50488     sqlite3VdbeChangeP2(v, curaddr-1, addr2);
50489     sqlite3VdbeAddOp(v, OP_Rowid, iTab, 0);
50490     sqlite3VdbeAddOp(v, OP_AddImm, 1, 0);
50491     sqlite3VdbeAddOp(v, OP_IsUnique, iIdx, addr2);
50492     sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort,
50493                     "indexed columns are not unique", P3_STATIC);
50494     assert( db->mallocFailed || addr2==sqlite3VdbeCurrentAddr(v) );
50495   }
50496   sqlite3VdbeAddOp(v, OP_IdxInsert, iIdx, 0);
50497   sqlite3VdbeAddOp(v, OP_Next, iTab, addr1+1);
50498   sqlite3VdbeJumpHere(v, addr1);
50499   sqlite3VdbeAddOp(v, OP_Close, iTab, 0);
50500   sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
50501 }
50502
50503 /*
50504 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
50505 ** and pTblList is the name of the table that is to be indexed.  Both will 
50506 ** be NULL for a primary key or an index that is created to satisfy a
50507 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
50508 ** as the table to be indexed.  pParse->pNewTable is a table that is
50509 ** currently being constructed by a CREATE TABLE statement.
50510 **
50511 ** pList is a list of columns to be indexed.  pList will be NULL if this
50512 ** is a primary key or unique-constraint on the most recent column added
50513 ** to the table currently under construction.  
50514 */
50515 SQLITE_PRIVATE void sqlite3CreateIndex(
50516   Parse *pParse,     /* All information about this parse */
50517   Token *pName1,     /* First part of index name. May be NULL */
50518   Token *pName2,     /* Second part of index name. May be NULL */
50519   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
50520   ExprList *pList,   /* A list of columns to be indexed */
50521   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
50522   Token *pStart,     /* The CREATE token that begins this statement */
50523   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
50524   int sortOrder,     /* Sort order of primary key when pList==NULL */
50525   int ifNotExist     /* Omit error if index already exists */
50526 ){
50527   Table *pTab = 0;     /* Table to be indexed */
50528   Index *pIndex = 0;   /* The index to be created */
50529   char *zName = 0;     /* Name of the index */
50530   int nName;           /* Number of characters in zName */
50531   int i, j;
50532   Token nullId;        /* Fake token for an empty ID list */
50533   DbFixer sFix;        /* For assigning database names to pTable */
50534   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
50535   sqlite3 *db = pParse->db;
50536   Db *pDb;             /* The specific table containing the indexed database */
50537   int iDb;             /* Index of the database that is being written */
50538   Token *pName = 0;    /* Unqualified name of the index to create */
50539   struct ExprList_item *pListItem; /* For looping over pList */
50540   int nCol;
50541   int nExtra = 0;
50542   char *zExtra;
50543
50544   if( pParse->nErr || db->mallocFailed || IN_DECLARE_VTAB ){
50545     goto exit_create_index;
50546   }
50547
50548   /*
50549   ** Find the table that is to be indexed.  Return early if not found.
50550   */
50551   if( pTblName!=0 ){
50552
50553     /* Use the two-part index name to determine the database 
50554     ** to search for the table. 'Fix' the table name to this db
50555     ** before looking up the table.
50556     */
50557     assert( pName1 && pName2 );
50558     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
50559     if( iDb<0 ) goto exit_create_index;
50560
50561 #ifndef SQLITE_OMIT_TEMPDB
50562     /* If the index name was unqualified, check if the the table
50563     ** is a temp table. If so, set the database to 1. Do not do this
50564     ** if initialising a database schema.
50565     */
50566     if( !db->init.busy ){
50567       pTab = sqlite3SrcListLookup(pParse, pTblName);
50568       if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
50569         iDb = 1;
50570       }
50571     }
50572 #endif
50573
50574     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
50575         sqlite3FixSrcList(&sFix, pTblName)
50576     ){
50577       /* Because the parser constructs pTblName from a single identifier,
50578       ** sqlite3FixSrcList can never fail. */
50579       assert(0);
50580     }
50581     pTab = sqlite3LocateTable(pParse, pTblName->a[0].zName, 
50582         pTblName->a[0].zDatabase);
50583     if( !pTab ) goto exit_create_index;
50584     assert( db->aDb[iDb].pSchema==pTab->pSchema );
50585   }else{
50586     assert( pName==0 );
50587     pTab = pParse->pNewTable;
50588     if( !pTab ) goto exit_create_index;
50589     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
50590   }
50591   pDb = &db->aDb[iDb];
50592
50593   if( pTab==0 || pParse->nErr ) goto exit_create_index;
50594   if( pTab->readOnly ){
50595     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
50596     goto exit_create_index;
50597   }
50598 #ifndef SQLITE_OMIT_VIEW
50599   if( pTab->pSelect ){
50600     sqlite3ErrorMsg(pParse, "views may not be indexed");
50601     goto exit_create_index;
50602   }
50603 #endif
50604 #ifndef SQLITE_OMIT_VIRTUALTABLE
50605   if( IsVirtual(pTab) ){
50606     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
50607     goto exit_create_index;
50608   }
50609 #endif
50610
50611   /*
50612   ** Find the name of the index.  Make sure there is not already another
50613   ** index or table with the same name.  
50614   **
50615   ** Exception:  If we are reading the names of permanent indices from the
50616   ** sqlite_master table (because some other process changed the schema) and
50617   ** one of the index names collides with the name of a temporary table or
50618   ** index, then we will continue to process this index.
50619   **
50620   ** If pName==0 it means that we are
50621   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
50622   ** own name.
50623   */
50624   if( pName ){
50625     zName = sqlite3NameFromToken(db, pName);
50626     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
50627     if( zName==0 ) goto exit_create_index;
50628     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
50629       goto exit_create_index;
50630     }
50631     if( !db->init.busy ){
50632       if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
50633       if( sqlite3FindTable(db, zName, 0)!=0 ){
50634         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
50635         goto exit_create_index;
50636       }
50637     }
50638     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
50639       if( !ifNotExist ){
50640         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
50641       }
50642       goto exit_create_index;
50643     }
50644   }else{
50645     char zBuf[30];
50646     int n;
50647     Index *pLoop;
50648     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
50649     sqlite3_snprintf(sizeof(zBuf),zBuf,"_%d",n);
50650     zName = 0;
50651     sqlite3SetString(&zName, "sqlite_autoindex_", pTab->zName, zBuf, (char*)0);
50652     if( zName==0 ){
50653       db->mallocFailed = 1;
50654       goto exit_create_index;
50655     }
50656   }
50657
50658   /* Check for authorization to create an index.
50659   */
50660 #ifndef SQLITE_OMIT_AUTHORIZATION
50661   {
50662     const char *zDb = pDb->zName;
50663     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
50664       goto exit_create_index;
50665     }
50666     i = SQLITE_CREATE_INDEX;
50667     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
50668     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
50669       goto exit_create_index;
50670     }
50671   }
50672 #endif
50673
50674   /* If pList==0, it means this routine was called to make a primary
50675   ** key out of the last column added to the table under construction.
50676   ** So create a fake list to simulate this.
50677   */
50678   if( pList==0 ){
50679     nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
50680     nullId.n = strlen((char*)nullId.z);
50681     pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId);
50682     if( pList==0 ) goto exit_create_index;
50683     pList->a[0].sortOrder = sortOrder;
50684   }
50685
50686   /* Figure out how many bytes of space are required to store explicitly
50687   ** specified collation sequence names.
50688   */
50689   for(i=0; i<pList->nExpr; i++){
50690     Expr *pExpr = pList->a[i].pExpr;
50691     if( pExpr ){
50692       nExtra += (1 + strlen(pExpr->pColl->zName));
50693     }
50694   }
50695
50696   /* 
50697   ** Allocate the index structure. 
50698   */
50699   nName = strlen(zName);
50700   nCol = pList->nExpr;
50701   pIndex = sqlite3DbMallocZero(db, 
50702       sizeof(Index) +              /* Index structure  */
50703       sizeof(int)*nCol +           /* Index.aiColumn   */
50704       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
50705       sizeof(char *)*nCol +        /* Index.azColl     */
50706       sizeof(u8)*nCol +            /* Index.aSortOrder */
50707       nName + 1 +                  /* Index.zName      */
50708       nExtra                       /* Collation sequence names */
50709   );
50710   if( db->mallocFailed ){
50711     goto exit_create_index;
50712   }
50713   pIndex->azColl = (char**)(&pIndex[1]);
50714   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
50715   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
50716   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
50717   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
50718   zExtra = (char *)(&pIndex->zName[nName+1]);
50719   memcpy(pIndex->zName, zName, nName+1);
50720   pIndex->pTable = pTab;
50721   pIndex->nColumn = pList->nExpr;
50722   pIndex->onError = onError;
50723   pIndex->autoIndex = pName==0;
50724   pIndex->pSchema = db->aDb[iDb].pSchema;
50725
50726   /* Check to see if we should honor DESC requests on index columns
50727   */
50728   if( pDb->pSchema->file_format>=4 ){
50729     sortOrderMask = -1;   /* Honor DESC */
50730   }else{
50731     sortOrderMask = 0;    /* Ignore DESC */
50732   }
50733
50734   /* Scan the names of the columns of the table to be indexed and
50735   ** load the column indices into the Index structure.  Report an error
50736   ** if any column is not found.
50737   */
50738   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
50739     const char *zColName = pListItem->zName;
50740     Column *pTabCol;
50741     int requestedSortOrder;
50742     char *zColl;                   /* Collation sequence name */
50743
50744     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
50745       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
50746     }
50747     if( j>=pTab->nCol ){
50748       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
50749         pTab->zName, zColName);
50750       goto exit_create_index;
50751     }
50752     /* TODO:  Add a test to make sure that the same column is not named
50753     ** more than once within the same index.  Only the first instance of
50754     ** the column will ever be used by the optimizer.  Note that using the
50755     ** same column more than once cannot be an error because that would 
50756     ** break backwards compatibility - it needs to be a warning.
50757     */
50758     pIndex->aiColumn[i] = j;
50759     if( pListItem->pExpr ){
50760       assert( pListItem->pExpr->pColl );
50761       zColl = zExtra;
50762       sqlite3_snprintf(nExtra, zExtra, "%s", pListItem->pExpr->pColl->zName);
50763       zExtra += (strlen(zColl) + 1);
50764     }else{
50765       zColl = pTab->aCol[j].zColl;
50766       if( !zColl ){
50767         zColl = db->pDfltColl->zName;
50768       }
50769     }
50770     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
50771       goto exit_create_index;
50772     }
50773     pIndex->azColl[i] = zColl;
50774     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
50775     pIndex->aSortOrder[i] = requestedSortOrder;
50776   }
50777   sqlite3DefaultRowEst(pIndex);
50778
50779   if( pTab==pParse->pNewTable ){
50780     /* This routine has been called to create an automatic index as a
50781     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
50782     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
50783     ** i.e. one of:
50784     **
50785     ** CREATE TABLE t(x PRIMARY KEY, y);
50786     ** CREATE TABLE t(x, y, UNIQUE(x, y));
50787     **
50788     ** Either way, check to see if the table already has such an index. If
50789     ** so, don't bother creating this one. This only applies to
50790     ** automatically created indices. Users can do as they wish with
50791     ** explicit indices.
50792     */
50793     Index *pIdx;
50794     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
50795       int k;
50796       assert( pIdx->onError!=OE_None );
50797       assert( pIdx->autoIndex );
50798       assert( pIndex->onError!=OE_None );
50799
50800       if( pIdx->nColumn!=pIndex->nColumn ) continue;
50801       for(k=0; k<pIdx->nColumn; k++){
50802         const char *z1 = pIdx->azColl[k];
50803         const char *z2 = pIndex->azColl[k];
50804         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
50805         if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
50806         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
50807       }
50808       if( k==pIdx->nColumn ){
50809         if( pIdx->onError!=pIndex->onError ){
50810           /* This constraint creates the same index as a previous
50811           ** constraint specified somewhere in the CREATE TABLE statement.
50812           ** However the ON CONFLICT clauses are different. If both this 
50813           ** constraint and the previous equivalent constraint have explicit
50814           ** ON CONFLICT clauses this is an error. Otherwise, use the
50815           ** explicitly specified behaviour for the index.
50816           */
50817           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
50818             sqlite3ErrorMsg(pParse, 
50819                 "conflicting ON CONFLICT clauses specified", 0);
50820           }
50821           if( pIdx->onError==OE_Default ){
50822             pIdx->onError = pIndex->onError;
50823           }
50824         }
50825         goto exit_create_index;
50826       }
50827     }
50828   }
50829
50830   /* Link the new Index structure to its table and to the other
50831   ** in-memory database structures. 
50832   */
50833   if( db->init.busy ){
50834     Index *p;
50835     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
50836                          pIndex->zName, strlen(pIndex->zName)+1, pIndex);
50837     if( p ){
50838       assert( p==pIndex );  /* Malloc must have failed */
50839       db->mallocFailed = 1;
50840       goto exit_create_index;
50841     }
50842     db->flags |= SQLITE_InternChanges;
50843     if( pTblName!=0 ){
50844       pIndex->tnum = db->init.newTnum;
50845     }
50846   }
50847
50848   /* If the db->init.busy is 0 then create the index on disk.  This
50849   ** involves writing the index into the master table and filling in the
50850   ** index with the current table contents.
50851   **
50852   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
50853   ** command.  db->init.busy is 1 when a database is opened and 
50854   ** CREATE INDEX statements are read out of the master table.  In
50855   ** the latter case the index already exists on disk, which is why
50856   ** we don't want to recreate it.
50857   **
50858   ** If pTblName==0 it means this index is generated as a primary key
50859   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
50860   ** has just been created, it contains no data and the index initialization
50861   ** step can be skipped.
50862   */
50863   else if( db->init.busy==0 ){
50864     Vdbe *v;
50865     char *zStmt;
50866     int iMem = pParse->nMem++;
50867
50868     v = sqlite3GetVdbe(pParse);
50869     if( v==0 ) goto exit_create_index;
50870
50871
50872     /* Create the rootpage for the index
50873     */
50874     sqlite3BeginWriteOperation(pParse, 1, iDb);
50875     sqlite3VdbeAddOp(v, OP_CreateIndex, iDb, 0);
50876     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
50877
50878     /* Gather the complete text of the CREATE INDEX statement into
50879     ** the zStmt variable
50880     */
50881     if( pStart && pEnd ){
50882       /* A named index with an explicit CREATE INDEX statement */
50883       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
50884         onError==OE_None ? "" : " UNIQUE",
50885         pEnd->z - pName->z + 1,
50886         pName->z);
50887     }else{
50888       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
50889       /* zStmt = sqlite3MPrintf(""); */
50890       zStmt = 0;
50891     }
50892
50893     /* Add an entry in sqlite_master for this index
50894     */
50895     sqlite3NestedParse(pParse, 
50896         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#0,%Q);",
50897         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
50898         pIndex->zName,
50899         pTab->zName,
50900         zStmt
50901     );
50902     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
50903     sqlite3_free(zStmt);
50904
50905     /* Fill the index with data and reparse the schema. Code an OP_Expire
50906     ** to invalidate all pre-compiled statements.
50907     */
50908     if( pTblName ){
50909       sqlite3RefillIndex(pParse, pIndex, iMem);
50910       sqlite3ChangeCookie(db, v, iDb);
50911       sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
50912          sqlite3MPrintf(db, "name='%q'", pIndex->zName), P3_DYNAMIC);
50913       sqlite3VdbeAddOp(v, OP_Expire, 0, 0);
50914     }
50915   }
50916
50917   /* When adding an index to the list of indices for a table, make
50918   ** sure all indices labeled OE_Replace come after all those labeled
50919   ** OE_Ignore.  This is necessary for the correct operation of UPDATE
50920   ** and INSERT.
50921   */
50922   if( db->init.busy || pTblName==0 ){
50923     if( onError!=OE_Replace || pTab->pIndex==0
50924          || pTab->pIndex->onError==OE_Replace){
50925       pIndex->pNext = pTab->pIndex;
50926       pTab->pIndex = pIndex;
50927     }else{
50928       Index *pOther = pTab->pIndex;
50929       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
50930         pOther = pOther->pNext;
50931       }
50932       pIndex->pNext = pOther->pNext;
50933       pOther->pNext = pIndex;
50934     }
50935     pIndex = 0;
50936   }
50937
50938   /* Clean up before exiting */
50939 exit_create_index:
50940   if( pIndex ){
50941     freeIndex(pIndex);
50942   }
50943   sqlite3ExprListDelete(pList);
50944   sqlite3SrcListDelete(pTblName);
50945   sqlite3_free(zName);
50946   return;
50947 }
50948
50949 /*
50950 ** Generate code to make sure the file format number is at least minFormat.
50951 ** The generated code will increase the file format number if necessary.
50952 */
50953 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
50954   Vdbe *v;
50955   v = sqlite3GetVdbe(pParse);
50956   if( v ){
50957     sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1);
50958     sqlite3VdbeUsesBtree(v, iDb);
50959     sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
50960     sqlite3VdbeAddOp(v, OP_Ge, 0, sqlite3VdbeCurrentAddr(v)+3);
50961     sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
50962     sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
50963   }
50964 }
50965
50966 /*
50967 ** Fill the Index.aiRowEst[] array with default information - information
50968 ** to be used when we have not run the ANALYZE command.
50969 **
50970 ** aiRowEst[0] is suppose to contain the number of elements in the index.
50971 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
50972 ** number of rows in the table that match any particular value of the
50973 ** first column of the index.  aiRowEst[2] is an estimate of the number
50974 ** of rows that match any particular combiniation of the first 2 columns
50975 ** of the index.  And so forth.  It must always be the case that
50976 *
50977 **           aiRowEst[N]<=aiRowEst[N-1]
50978 **           aiRowEst[N]>=1
50979 **
50980 ** Apart from that, we have little to go on besides intuition as to
50981 ** how aiRowEst[] should be initialized.  The numbers generated here
50982 ** are based on typical values found in actual indices.
50983 */
50984 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
50985   unsigned *a = pIdx->aiRowEst;
50986   int i;
50987   assert( a!=0 );
50988   a[0] = 1000000;
50989   for(i=pIdx->nColumn; i>=5; i--){
50990     a[i] = 5;
50991   }
50992   while( i>=1 ){
50993     a[i] = 11 - i;
50994     i--;
50995   }
50996   if( pIdx->onError!=OE_None ){
50997     a[pIdx->nColumn] = 1;
50998   }
50999 }
51000
51001 /*
51002 ** This routine will drop an existing named index.  This routine
51003 ** implements the DROP INDEX statement.
51004 */
51005 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
51006   Index *pIndex;
51007   Vdbe *v;
51008   sqlite3 *db = pParse->db;
51009   int iDb;
51010
51011   if( pParse->nErr || db->mallocFailed ){
51012     goto exit_drop_index;
51013   }
51014   assert( pName->nSrc==1 );
51015   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
51016     goto exit_drop_index;
51017   }
51018   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
51019   if( pIndex==0 ){
51020     if( !ifExists ){
51021       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
51022     }
51023     pParse->checkSchema = 1;
51024     goto exit_drop_index;
51025   }
51026   if( pIndex->autoIndex ){
51027     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
51028       "or PRIMARY KEY constraint cannot be dropped", 0);
51029     goto exit_drop_index;
51030   }
51031   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
51032 #ifndef SQLITE_OMIT_AUTHORIZATION
51033   {
51034     int code = SQLITE_DROP_INDEX;
51035     Table *pTab = pIndex->pTable;
51036     const char *zDb = db->aDb[iDb].zName;
51037     const char *zTab = SCHEMA_TABLE(iDb);
51038     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
51039       goto exit_drop_index;
51040     }
51041     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
51042     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
51043       goto exit_drop_index;
51044     }
51045   }
51046 #endif
51047
51048   /* Generate code to remove the index and from the master table */
51049   v = sqlite3GetVdbe(pParse);
51050   if( v ){
51051     sqlite3BeginWriteOperation(pParse, 1, iDb);
51052     sqlite3NestedParse(pParse,
51053        "DELETE FROM %Q.%s WHERE name=%Q",
51054        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
51055        pIndex->zName
51056     );
51057     sqlite3ChangeCookie(db, v, iDb);
51058     destroyRootPage(pParse, pIndex->tnum, iDb);
51059     sqlite3VdbeOp3(v, OP_DropIndex, iDb, 0, pIndex->zName, 0);
51060   }
51061
51062 exit_drop_index:
51063   sqlite3SrcListDelete(pName);
51064 }
51065
51066 /*
51067 ** pArray is a pointer to an array of objects.  Each object in the
51068 ** array is szEntry bytes in size.  This routine allocates a new
51069 ** object on the end of the array.
51070 **
51071 ** *pnEntry is the number of entries already in use.  *pnAlloc is
51072 ** the previously allocated size of the array.  initSize is the
51073 ** suggested initial array size allocation.
51074 **
51075 ** The index of the new entry is returned in *pIdx.
51076 **
51077 ** This routine returns a pointer to the array of objects.  This
51078 ** might be the same as the pArray parameter or it might be a different
51079 ** pointer if the array was resized.
51080 */
51081 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
51082   sqlite3 *db,      /* Connection to notify of malloc failures */
51083   void *pArray,     /* Array of objects.  Might be reallocated */
51084   int szEntry,      /* Size of each object in the array */
51085   int initSize,     /* Suggested initial allocation, in elements */
51086   int *pnEntry,     /* Number of objects currently in use */
51087   int *pnAlloc,     /* Current size of the allocation, in elements */
51088   int *pIdx         /* Write the index of a new slot here */
51089 ){
51090   char *z;
51091   if( *pnEntry >= *pnAlloc ){
51092     void *pNew;
51093     int newSize;
51094     newSize = (*pnAlloc)*2 + initSize;
51095     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
51096     if( pNew==0 ){
51097       *pIdx = -1;
51098       return pArray;
51099     }
51100     *pnAlloc = newSize;
51101     pArray = pNew;
51102   }
51103   z = (char*)pArray;
51104   memset(&z[*pnEntry * szEntry], 0, szEntry);
51105   *pIdx = *pnEntry;
51106   ++*pnEntry;
51107   return pArray;
51108 }
51109
51110 /*
51111 ** Append a new element to the given IdList.  Create a new IdList if
51112 ** need be.
51113 **
51114 ** A new IdList is returned, or NULL if malloc() fails.
51115 */
51116 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
51117   int i;
51118   if( pList==0 ){
51119     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
51120     if( pList==0 ) return 0;
51121     pList->nAlloc = 0;
51122   }
51123   pList->a = sqlite3ArrayAllocate(
51124       db,
51125       pList->a,
51126       sizeof(pList->a[0]),
51127       5,
51128       &pList->nId,
51129       &pList->nAlloc,
51130       &i
51131   );
51132   if( i<0 ){
51133     sqlite3IdListDelete(pList);
51134     return 0;
51135   }
51136   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
51137   return pList;
51138 }
51139
51140 /*
51141 ** Delete an IdList.
51142 */
51143 SQLITE_PRIVATE void sqlite3IdListDelete(IdList *pList){
51144   int i;
51145   if( pList==0 ) return;
51146   for(i=0; i<pList->nId; i++){
51147     sqlite3_free(pList->a[i].zName);
51148   }
51149   sqlite3_free(pList->a);
51150   sqlite3_free(pList);
51151 }
51152
51153 /*
51154 ** Return the index in pList of the identifier named zId.  Return -1
51155 ** if not found.
51156 */
51157 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
51158   int i;
51159   if( pList==0 ) return -1;
51160   for(i=0; i<pList->nId; i++){
51161     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
51162   }
51163   return -1;
51164 }
51165
51166 /*
51167 ** Append a new table name to the given SrcList.  Create a new SrcList if
51168 ** need be.  A new entry is created in the SrcList even if pToken is NULL.
51169 **
51170 ** A new SrcList is returned, or NULL if malloc() fails.
51171 **
51172 ** If pDatabase is not null, it means that the table has an optional
51173 ** database name prefix.  Like this:  "database.table".  The pDatabase
51174 ** points to the table name and the pTable points to the database name.
51175 ** The SrcList.a[].zName field is filled with the table name which might
51176 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
51177 ** SrcList.a[].zDatabase is filled with the database name from pTable,
51178 ** or with NULL if no database is specified.
51179 **
51180 ** In other words, if call like this:
51181 **
51182 **         sqlite3SrcListAppend(D,A,B,0);
51183 **
51184 ** Then B is a table name and the database name is unspecified.  If called
51185 ** like this:
51186 **
51187 **         sqlite3SrcListAppend(D,A,B,C);
51188 **
51189 ** Then C is the table name and B is the database name.
51190 */
51191 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
51192   sqlite3 *db,        /* Connection to notify of malloc failures */
51193   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
51194   Token *pTable,      /* Table to append */
51195   Token *pDatabase    /* Database of the table */
51196 ){
51197   struct SrcList_item *pItem;
51198   if( pList==0 ){
51199     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
51200     if( pList==0 ) return 0;
51201     pList->nAlloc = 1;
51202   }
51203   if( pList->nSrc>=pList->nAlloc ){
51204     SrcList *pNew;
51205     pList->nAlloc *= 2;
51206     pNew = sqlite3DbRealloc(db, pList,
51207                sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
51208     if( pNew==0 ){
51209       sqlite3SrcListDelete(pList);
51210       return 0;
51211     }
51212     pList = pNew;
51213   }
51214   pItem = &pList->a[pList->nSrc];
51215   memset(pItem, 0, sizeof(pList->a[0]));
51216   if( pDatabase && pDatabase->z==0 ){
51217     pDatabase = 0;
51218   }
51219   if( pDatabase && pTable ){
51220     Token *pTemp = pDatabase;
51221     pDatabase = pTable;
51222     pTable = pTemp;
51223   }
51224   pItem->zName = sqlite3NameFromToken(db, pTable);
51225   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
51226   pItem->iCursor = -1;
51227   pItem->isPopulated = 0;
51228   pList->nSrc++;
51229   return pList;
51230 }
51231
51232 /*
51233 ** Assign cursors to all tables in a SrcList
51234 */
51235 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
51236   int i;
51237   struct SrcList_item *pItem;
51238   assert(pList || pParse->db->mallocFailed );
51239   if( pList ){
51240     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
51241       if( pItem->iCursor>=0 ) break;
51242       pItem->iCursor = pParse->nTab++;
51243       if( pItem->pSelect ){
51244         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
51245       }
51246     }
51247   }
51248 }
51249
51250 /*
51251 ** Delete an entire SrcList including all its substructure.
51252 */
51253 SQLITE_PRIVATE void sqlite3SrcListDelete(SrcList *pList){
51254   int i;
51255   struct SrcList_item *pItem;
51256   if( pList==0 ) return;
51257   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
51258     sqlite3_free(pItem->zDatabase);
51259     sqlite3_free(pItem->zName);
51260     sqlite3_free(pItem->zAlias);
51261     sqlite3DeleteTable(pItem->pTab);
51262     sqlite3SelectDelete(pItem->pSelect);
51263     sqlite3ExprDelete(pItem->pOn);
51264     sqlite3IdListDelete(pItem->pUsing);
51265   }
51266   sqlite3_free(pList);
51267 }
51268
51269 /*
51270 ** This routine is called by the parser to add a new term to the
51271 ** end of a growing FROM clause.  The "p" parameter is the part of
51272 ** the FROM clause that has already been constructed.  "p" is NULL
51273 ** if this is the first term of the FROM clause.  pTable and pDatabase
51274 ** are the name of the table and database named in the FROM clause term.
51275 ** pDatabase is NULL if the database name qualifier is missing - the
51276 ** usual case.  If the term has a alias, then pAlias points to the
51277 ** alias token.  If the term is a subquery, then pSubquery is the
51278 ** SELECT statement that the subquery encodes.  The pTable and
51279 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
51280 ** parameters are the content of the ON and USING clauses.
51281 **
51282 ** Return a new SrcList which encodes is the FROM with the new
51283 ** term added.
51284 */
51285 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
51286   Parse *pParse,          /* Parsing context */
51287   SrcList *p,             /* The left part of the FROM clause already seen */
51288   Token *pTable,          /* Name of the table to add to the FROM clause */
51289   Token *pDatabase,       /* Name of the database containing pTable */
51290   Token *pAlias,          /* The right-hand side of the AS subexpression */
51291   Select *pSubquery,      /* A subquery used in place of a table name */
51292   Expr *pOn,              /* The ON clause of a join */
51293   IdList *pUsing          /* The USING clause of a join */
51294 ){
51295   struct SrcList_item *pItem;
51296   sqlite3 *db = pParse->db;
51297   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
51298   if( p==0 || p->nSrc==0 ){
51299     sqlite3ExprDelete(pOn);
51300     sqlite3IdListDelete(pUsing);
51301     sqlite3SelectDelete(pSubquery);
51302     return p;
51303   }
51304   pItem = &p->a[p->nSrc-1];
51305   if( pAlias && pAlias->n ){
51306     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
51307   }
51308   pItem->pSelect = pSubquery;
51309   pItem->pOn = pOn;
51310   pItem->pUsing = pUsing;
51311   return p;
51312 }
51313
51314 /*
51315 ** When building up a FROM clause in the parser, the join operator
51316 ** is initially attached to the left operand.  But the code generator
51317 ** expects the join operator to be on the right operand.  This routine
51318 ** Shifts all join operators from left to right for an entire FROM
51319 ** clause.
51320 **
51321 ** Example: Suppose the join is like this:
51322 **
51323 **           A natural cross join B
51324 **
51325 ** The operator is "natural cross join".  The A and B operands are stored
51326 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
51327 ** operator with A.  This routine shifts that operator over to B.
51328 */
51329 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
51330   if( p && p->a ){
51331     int i;
51332     for(i=p->nSrc-1; i>0; i--){
51333       p->a[i].jointype = p->a[i-1].jointype;
51334     }
51335     p->a[0].jointype = 0;
51336   }
51337 }
51338
51339 /*
51340 ** Begin a transaction
51341 */
51342 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
51343   sqlite3 *db;
51344   Vdbe *v;
51345   int i;
51346
51347   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
51348   if( pParse->nErr || db->mallocFailed ) return;
51349   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
51350
51351   v = sqlite3GetVdbe(pParse);
51352   if( !v ) return;
51353   if( type!=TK_DEFERRED ){
51354     for(i=0; i<db->nDb; i++){
51355       sqlite3VdbeAddOp(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
51356       sqlite3VdbeUsesBtree(v, i);
51357     }
51358   }
51359   sqlite3VdbeAddOp(v, OP_AutoCommit, 0, 0);
51360 }
51361
51362 /*
51363 ** Commit a transaction
51364 */
51365 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
51366   sqlite3 *db;
51367   Vdbe *v;
51368
51369   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
51370   if( pParse->nErr || db->mallocFailed ) return;
51371   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
51372
51373   v = sqlite3GetVdbe(pParse);
51374   if( v ){
51375     sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0);
51376   }
51377 }
51378
51379 /*
51380 ** Rollback a transaction
51381 */
51382 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
51383   sqlite3 *db;
51384   Vdbe *v;
51385
51386   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
51387   if( pParse->nErr || db->mallocFailed ) return;
51388   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
51389
51390   v = sqlite3GetVdbe(pParse);
51391   if( v ){
51392     sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1);
51393   }
51394 }
51395
51396 /*
51397 ** Make sure the TEMP database is open and available for use.  Return
51398 ** the number of errors.  Leave any error messages in the pParse structure.
51399 */
51400 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
51401   sqlite3 *db = pParse->db;
51402   if( db->aDb[1].pBt==0 && !pParse->explain ){
51403     int rc;
51404     static const int flags = 
51405           SQLITE_OPEN_READWRITE |
51406           SQLITE_OPEN_CREATE |
51407           SQLITE_OPEN_EXCLUSIVE |
51408           SQLITE_OPEN_DELETEONCLOSE |
51409           SQLITE_OPEN_TEMP_DB;
51410
51411     rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
51412                                  &db->aDb[1].pBt);
51413     if( rc!=SQLITE_OK ){
51414       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
51415         "file for storing temporary tables");
51416       pParse->rc = rc;
51417       return 1;
51418     }
51419     if( db->flags & !db->autoCommit ){
51420       rc = sqlite3BtreeBeginTrans(db->aDb[1].pBt, 1);
51421       if( rc!=SQLITE_OK ){
51422         sqlite3ErrorMsg(pParse, "unable to get a write lock on "
51423           "the temporary database file");
51424         pParse->rc = rc;
51425         return 1;
51426       }
51427     }
51428     assert( db->aDb[1].pSchema );
51429   }
51430   return 0;
51431 }
51432
51433 /*
51434 ** Generate VDBE code that will verify the schema cookie and start
51435 ** a read-transaction for all named database files.
51436 **
51437 ** It is important that all schema cookies be verified and all
51438 ** read transactions be started before anything else happens in
51439 ** the VDBE program.  But this routine can be called after much other
51440 ** code has been generated.  So here is what we do:
51441 **
51442 ** The first time this routine is called, we code an OP_Goto that
51443 ** will jump to a subroutine at the end of the program.  Then we
51444 ** record every database that needs its schema verified in the
51445 ** pParse->cookieMask field.  Later, after all other code has been
51446 ** generated, the subroutine that does the cookie verifications and
51447 ** starts the transactions will be coded and the OP_Goto P2 value
51448 ** will be made to point to that subroutine.  The generation of the
51449 ** cookie verification subroutine code happens in sqlite3FinishCoding().
51450 **
51451 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
51452 ** schema on any databases.  This can be used to position the OP_Goto
51453 ** early in the code, before we know if any database tables will be used.
51454 */
51455 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
51456   sqlite3 *db;
51457   Vdbe *v;
51458   int mask;
51459
51460   v = sqlite3GetVdbe(pParse);
51461   if( v==0 ) return;  /* This only happens if there was a prior error */
51462   db = pParse->db;
51463   if( pParse->cookieGoto==0 ){
51464     pParse->cookieGoto = sqlite3VdbeAddOp(v, OP_Goto, 0, 0)+1;
51465   }
51466   if( iDb>=0 ){
51467     assert( iDb<db->nDb );
51468     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
51469     assert( iDb<SQLITE_MAX_ATTACHED+2 );
51470     mask = 1<<iDb;
51471     if( (pParse->cookieMask & mask)==0 ){
51472       pParse->cookieMask |= mask;
51473       pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
51474       if( !OMIT_TEMPDB && iDb==1 ){
51475         sqlite3OpenTempDatabase(pParse);
51476       }
51477     }
51478   }
51479 }
51480
51481 /*
51482 ** Generate VDBE code that prepares for doing an operation that
51483 ** might change the database.
51484 **
51485 ** This routine starts a new transaction if we are not already within
51486 ** a transaction.  If we are already within a transaction, then a checkpoint
51487 ** is set if the setStatement parameter is true.  A checkpoint should
51488 ** be set for operations that might fail (due to a constraint) part of
51489 ** the way through and which will need to undo some writes without having to
51490 ** rollback the whole transaction.  For operations where all constraints
51491 ** can be checked before any changes are made to the database, it is never
51492 ** necessary to undo a write and the checkpoint should not be set.
51493 **
51494 ** Only database iDb and the temp database are made writable by this call.
51495 ** If iDb==0, then the main and temp databases are made writable.   If
51496 ** iDb==1 then only the temp database is made writable.  If iDb>1 then the
51497 ** specified auxiliary database and the temp database are made writable.
51498 */
51499 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
51500   Vdbe *v = sqlite3GetVdbe(pParse);
51501   if( v==0 ) return;
51502   sqlite3CodeVerifySchema(pParse, iDb);
51503   pParse->writeMask |= 1<<iDb;
51504   if( setStatement && pParse->nested==0 ){
51505     sqlite3VdbeAddOp(v, OP_Statement, iDb, 0);
51506   }
51507   if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
51508     sqlite3BeginWriteOperation(pParse, setStatement, 1);
51509   }
51510 }
51511
51512 /*
51513 ** Check to see if pIndex uses the collating sequence pColl.  Return
51514 ** true if it does and false if it does not.
51515 */
51516 #ifndef SQLITE_OMIT_REINDEX
51517 static int collationMatch(const char *zColl, Index *pIndex){
51518   int i;
51519   for(i=0; i<pIndex->nColumn; i++){
51520     const char *z = pIndex->azColl[i];
51521     if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
51522       return 1;
51523     }
51524   }
51525   return 0;
51526 }
51527 #endif
51528
51529 /*
51530 ** Recompute all indices of pTab that use the collating sequence pColl.
51531 ** If pColl==0 then recompute all indices of pTab.
51532 */
51533 #ifndef SQLITE_OMIT_REINDEX
51534 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
51535   Index *pIndex;              /* An index associated with pTab */
51536
51537   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
51538     if( zColl==0 || collationMatch(zColl, pIndex) ){
51539       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
51540       sqlite3BeginWriteOperation(pParse, 0, iDb);
51541       sqlite3RefillIndex(pParse, pIndex, -1);
51542     }
51543   }
51544 }
51545 #endif
51546
51547 /*
51548 ** Recompute all indices of all tables in all databases where the
51549 ** indices use the collating sequence pColl.  If pColl==0 then recompute
51550 ** all indices everywhere.
51551 */
51552 #ifndef SQLITE_OMIT_REINDEX
51553 static void reindexDatabases(Parse *pParse, char const *zColl){
51554   Db *pDb;                    /* A single database */
51555   int iDb;                    /* The database index number */
51556   sqlite3 *db = pParse->db;   /* The database connection */
51557   HashElem *k;                /* For looping over tables in pDb */
51558   Table *pTab;                /* A table in the database */
51559
51560   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
51561     assert( pDb!=0 );
51562     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
51563       pTab = (Table*)sqliteHashData(k);
51564       reindexTable(pParse, pTab, zColl);
51565     }
51566   }
51567 }
51568 #endif
51569
51570 /*
51571 ** Generate code for the REINDEX command.
51572 **
51573 **        REINDEX                            -- 1
51574 **        REINDEX  <collation>               -- 2
51575 **        REINDEX  ?<database>.?<tablename>  -- 3
51576 **        REINDEX  ?<database>.?<indexname>  -- 4
51577 **
51578 ** Form 1 causes all indices in all attached databases to be rebuilt.
51579 ** Form 2 rebuilds all indices in all databases that use the named
51580 ** collating function.  Forms 3 and 4 rebuild the named index or all
51581 ** indices associated with the named table.
51582 */
51583 #ifndef SQLITE_OMIT_REINDEX
51584 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
51585   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
51586   char *z;                    /* Name of a table or index */
51587   const char *zDb;            /* Name of the database */
51588   Table *pTab;                /* A table in the database */
51589   Index *pIndex;              /* An index associated with pTab */
51590   int iDb;                    /* The database index number */
51591   sqlite3 *db = pParse->db;   /* The database connection */
51592   Token *pObjName;            /* Name of the table or index to be reindexed */
51593
51594   /* Read the database schema. If an error occurs, leave an error message
51595   ** and code in pParse and return NULL. */
51596   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
51597     return;
51598   }
51599
51600   if( pName1==0 || pName1->z==0 ){
51601     reindexDatabases(pParse, 0);
51602     return;
51603   }else if( pName2==0 || pName2->z==0 ){
51604     char *zColl;
51605     assert( pName1->z );
51606     zColl = sqlite3NameFromToken(pParse->db, pName1);
51607     if( !zColl ) return;
51608     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
51609     if( pColl ){
51610       if( zColl ){
51611         reindexDatabases(pParse, zColl);
51612         sqlite3_free(zColl);
51613       }
51614       return;
51615     }
51616     sqlite3_free(zColl);
51617   }
51618   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
51619   if( iDb<0 ) return;
51620   z = sqlite3NameFromToken(db, pObjName);
51621   if( z==0 ) return;
51622   zDb = db->aDb[iDb].zName;
51623   pTab = sqlite3FindTable(db, z, zDb);
51624   if( pTab ){
51625     reindexTable(pParse, pTab, 0);
51626     sqlite3_free(z);
51627     return;
51628   }
51629   pIndex = sqlite3FindIndex(db, z, zDb);
51630   sqlite3_free(z);
51631   if( pIndex ){
51632     sqlite3BeginWriteOperation(pParse, 0, iDb);
51633     sqlite3RefillIndex(pParse, pIndex, -1);
51634     return;
51635   }
51636   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
51637 }
51638 #endif
51639
51640 /*
51641 ** Return a dynamicly allocated KeyInfo structure that can be used
51642 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
51643 **
51644 ** If successful, a pointer to the new structure is returned. In this case
51645 ** the caller is responsible for calling sqlite3_free() on the returned 
51646 ** pointer. If an error occurs (out of memory or missing collation 
51647 ** sequence), NULL is returned and the state of pParse updated to reflect
51648 ** the error.
51649 */
51650 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
51651   int i;
51652   int nCol = pIdx->nColumn;
51653   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
51654   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(pParse->db, nBytes);
51655
51656   if( pKey ){
51657     pKey->db = pParse->db;
51658     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
51659     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
51660     for(i=0; i<nCol; i++){
51661       char *zColl = pIdx->azColl[i];
51662       assert( zColl );
51663       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
51664       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
51665     }
51666     pKey->nField = nCol;
51667   }
51668
51669   if( pParse->nErr ){
51670     sqlite3_free(pKey);
51671     pKey = 0;
51672   }
51673   return pKey;
51674 }
51675
51676 /************** End of build.c ***********************************************/
51677 /************** Begin file callback.c ****************************************/
51678 /*
51679 ** 2005 May 23 
51680 **
51681 ** The author disclaims copyright to this source code.  In place of
51682 ** a legal notice, here is a blessing:
51683 **
51684 **    May you do good and not evil.
51685 **    May you find forgiveness for yourself and forgive others.
51686 **    May you share freely, never taking more than you give.
51687 **
51688 *************************************************************************
51689 **
51690 ** This file contains functions used to access the internal hash tables
51691 ** of user defined functions and collation sequences.
51692 **
51693 ** $Id: callback.c,v 1.23 2007/08/29 12:31:26 danielk1977 Exp $
51694 */
51695
51696
51697 /*
51698 ** Invoke the 'collation needed' callback to request a collation sequence
51699 ** in the database text encoding of name zName, length nName.
51700 ** If the collation sequence
51701 */
51702 static void callCollNeeded(sqlite3 *db, const char *zName, int nName){
51703   assert( !db->xCollNeeded || !db->xCollNeeded16 );
51704   if( nName<0 ) nName = strlen(zName);
51705   if( db->xCollNeeded ){
51706     char *zExternal = sqlite3DbStrNDup(db, zName, nName);
51707     if( !zExternal ) return;
51708     db->xCollNeeded(db->pCollNeededArg, db, (int)ENC(db), zExternal);
51709     sqlite3_free(zExternal);
51710   }
51711 #ifndef SQLITE_OMIT_UTF16
51712   if( db->xCollNeeded16 ){
51713     char const *zExternal;
51714     sqlite3_value *pTmp = sqlite3ValueNew(db);
51715     sqlite3ValueSetStr(pTmp, nName, zName, SQLITE_UTF8, SQLITE_STATIC);
51716     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
51717     if( zExternal ){
51718       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
51719     }
51720     sqlite3ValueFree(pTmp);
51721   }
51722 #endif
51723 }
51724
51725 /*
51726 ** This routine is called if the collation factory fails to deliver a
51727 ** collation function in the best encoding but there may be other versions
51728 ** of this collation function (for other text encodings) available. Use one
51729 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
51730 ** possible.
51731 */
51732 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
51733   CollSeq *pColl2;
51734   char *z = pColl->zName;
51735   int n = strlen(z);
51736   int i;
51737   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
51738   for(i=0; i<3; i++){
51739     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, n, 0);
51740     if( pColl2->xCmp!=0 ){
51741       memcpy(pColl, pColl2, sizeof(CollSeq));
51742       pColl->xDel = 0;         /* Do not copy the destructor */
51743       return SQLITE_OK;
51744     }
51745   }
51746   return SQLITE_ERROR;
51747 }
51748
51749 /*
51750 ** This function is responsible for invoking the collation factory callback
51751 ** or substituting a collation sequence of a different encoding when the
51752 ** requested collation sequence is not available in the database native
51753 ** encoding.
51754 ** 
51755 ** If it is not NULL, then pColl must point to the database native encoding 
51756 ** collation sequence with name zName, length nName.
51757 **
51758 ** The return value is either the collation sequence to be used in database
51759 ** db for collation type name zName, length nName, or NULL, if no collation
51760 ** sequence can be found.
51761 */
51762 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
51763   sqlite3* db, 
51764   CollSeq *pColl, 
51765   const char *zName, 
51766   int nName
51767 ){
51768   CollSeq *p;
51769
51770   p = pColl;
51771   if( !p ){
51772     p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
51773   }
51774   if( !p || !p->xCmp ){
51775     /* No collation sequence of this type for this encoding is registered.
51776     ** Call the collation factory to see if it can supply us with one.
51777     */
51778     callCollNeeded(db, zName, nName);
51779     p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
51780   }
51781   if( p && !p->xCmp && synthCollSeq(db, p) ){
51782     p = 0;
51783   }
51784   assert( !p || p->xCmp );
51785   return p;
51786 }
51787
51788 /*
51789 ** This routine is called on a collation sequence before it is used to
51790 ** check that it is defined. An undefined collation sequence exists when
51791 ** a database is loaded that contains references to collation sequences
51792 ** that have not been defined by sqlite3_create_collation() etc.
51793 **
51794 ** If required, this routine calls the 'collation needed' callback to
51795 ** request a definition of the collating sequence. If this doesn't work, 
51796 ** an equivalent collating sequence that uses a text encoding different
51797 ** from the main database is substituted, if one is available.
51798 */
51799 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
51800   if( pColl ){
51801     const char *zName = pColl->zName;
51802     CollSeq *p = sqlite3GetCollSeq(pParse->db, pColl, zName, -1);
51803     if( !p ){
51804       if( pParse->nErr==0 ){
51805         sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
51806       }
51807       pParse->nErr++;
51808       return SQLITE_ERROR;
51809     }
51810     assert( p==pColl );
51811   }
51812   return SQLITE_OK;
51813 }
51814
51815
51816
51817 /*
51818 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
51819 ** specified by zName and nName is not found and parameter 'create' is
51820 ** true, then create a new entry. Otherwise return NULL.
51821 **
51822 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
51823 ** array of three CollSeq structures. The first is the collation sequence
51824 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
51825 **
51826 ** Stored immediately after the three collation sequences is a copy of
51827 ** the collation sequence name. A pointer to this string is stored in
51828 ** each collation sequence structure.
51829 */
51830 static CollSeq *findCollSeqEntry(
51831   sqlite3 *db,
51832   const char *zName,
51833   int nName,
51834   int create
51835 ){
51836   CollSeq *pColl;
51837   if( nName<0 ) nName = strlen(zName);
51838   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
51839
51840   if( 0==pColl && create ){
51841     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
51842     if( pColl ){
51843       CollSeq *pDel = 0;
51844       pColl[0].zName = (char*)&pColl[3];
51845       pColl[0].enc = SQLITE_UTF8;
51846       pColl[1].zName = (char*)&pColl[3];
51847       pColl[1].enc = SQLITE_UTF16LE;
51848       pColl[2].zName = (char*)&pColl[3];
51849       pColl[2].enc = SQLITE_UTF16BE;
51850       memcpy(pColl[0].zName, zName, nName);
51851       pColl[0].zName[nName] = 0;
51852       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
51853
51854       /* If a malloc() failure occured in sqlite3HashInsert(), it will 
51855       ** return the pColl pointer to be deleted (because it wasn't added
51856       ** to the hash table).
51857       */
51858       assert( pDel==0 || pDel==pColl );
51859       if( pDel!=0 ){
51860         db->mallocFailed = 1;
51861         sqlite3_free(pDel);
51862         pColl = 0;
51863       }
51864     }
51865   }
51866   return pColl;
51867 }
51868
51869 /*
51870 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
51871 ** Return the CollSeq* pointer for the collation sequence named zName
51872 ** for the encoding 'enc' from the database 'db'.
51873 **
51874 ** If the entry specified is not found and 'create' is true, then create a
51875 ** new entry.  Otherwise return NULL.
51876 **
51877 ** A separate function sqlite3LocateCollSeq() is a wrapper around
51878 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
51879 ** if necessary and generates an error message if the collating sequence
51880 ** cannot be found.
51881 */
51882 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
51883   sqlite3 *db,
51884   u8 enc,
51885   const char *zName,
51886   int nName,
51887   int create
51888 ){
51889   CollSeq *pColl;
51890   if( zName ){
51891     pColl = findCollSeqEntry(db, zName, nName, create);
51892   }else{
51893     pColl = db->pDfltColl;
51894   }
51895   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
51896   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
51897   if( pColl ) pColl += enc-1;
51898   return pColl;
51899 }
51900
51901 /*
51902 ** Locate a user function given a name, a number of arguments and a flag
51903 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
51904 ** pointer to the FuncDef structure that defines that function, or return
51905 ** NULL if the function does not exist.
51906 **
51907 ** If the createFlag argument is true, then a new (blank) FuncDef
51908 ** structure is created and liked into the "db" structure if a
51909 ** no matching function previously existed.  When createFlag is true
51910 ** and the nArg parameter is -1, then only a function that accepts
51911 ** any number of arguments will be returned.
51912 **
51913 ** If createFlag is false and nArg is -1, then the first valid
51914 ** function found is returned.  A function is valid if either xFunc
51915 ** or xStep is non-zero.
51916 **
51917 ** If createFlag is false, then a function with the required name and
51918 ** number of arguments may be returned even if the eTextRep flag does not
51919 ** match that requested.
51920 */
51921 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
51922   sqlite3 *db,       /* An open database */
51923   const char *zName, /* Name of the function.  Not null-terminated */
51924   int nName,         /* Number of characters in the name */
51925   int nArg,          /* Number of arguments.  -1 means any number */
51926   u8 enc,            /* Preferred text encoding */
51927   int createFlag     /* Create new entry if true and does not otherwise exist */
51928 ){
51929   FuncDef *p;         /* Iterator variable */
51930   FuncDef *pFirst;    /* First function with this name */
51931   FuncDef *pBest = 0; /* Best match found so far */
51932   int bestmatch = 0;  
51933
51934
51935   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
51936   if( nArg<-1 ) nArg = -1;
51937
51938   pFirst = (FuncDef*)sqlite3HashFind(&db->aFunc, zName, nName);
51939   for(p=pFirst; p; p=p->pNext){
51940     /* During the search for the best function definition, bestmatch is set
51941     ** as follows to indicate the quality of the match with the definition
51942     ** pointed to by pBest:
51943     **
51944     ** 0: pBest is NULL. No match has been found.
51945     ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
51946     **    encoding is requested, or vice versa.
51947     ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
51948     **    requested, or vice versa.
51949     ** 3: A variable arguments function using the same text encoding.
51950     ** 4: A function with the exact number of arguments requested that
51951     **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
51952     ** 5: A function with the exact number of arguments requested that
51953     **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
51954     ** 6: An exact match.
51955     **
51956     ** A larger value of 'matchqual' indicates a more desirable match.
51957     */
51958     if( p->nArg==-1 || p->nArg==nArg || nArg==-1 ){
51959       int match = 1;          /* Quality of this match */
51960       if( p->nArg==nArg || nArg==-1 ){
51961         match = 4;
51962       }
51963       if( enc==p->iPrefEnc ){
51964         match += 2;
51965       }
51966       else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
51967                (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
51968         match += 1;
51969       }
51970
51971       if( match>bestmatch ){
51972         pBest = p;
51973         bestmatch = match;
51974       }
51975     }
51976   }
51977
51978   /* If the createFlag parameter is true, and the seach did not reveal an
51979   ** exact match for the name, number of arguments and encoding, then add a
51980   ** new entry to the hash table and return it.
51981   */
51982   if( createFlag && bestmatch<6 && 
51983       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName))!=0 ){
51984     pBest->nArg = nArg;
51985     pBest->pNext = pFirst;
51986     pBest->iPrefEnc = enc;
51987     memcpy(pBest->zName, zName, nName);
51988     pBest->zName[nName] = 0;
51989     if( pBest==sqlite3HashInsert(&db->aFunc,pBest->zName,nName,(void*)pBest) ){
51990       db->mallocFailed = 1;
51991       sqlite3_free(pBest);
51992       return 0;
51993     }
51994   }
51995
51996   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
51997     return pBest;
51998   }
51999   return 0;
52000 }
52001
52002 /*
52003 ** Free all resources held by the schema structure. The void* argument points
52004 ** at a Schema struct. This function does not call sqlite3_free() on the 
52005 ** pointer itself, it just cleans up subsiduary resources (i.e. the contents
52006 ** of the schema hash tables).
52007 */
52008 SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
52009   Hash temp1;
52010   Hash temp2;
52011   HashElem *pElem;
52012   Schema *pSchema = (Schema *)p;
52013
52014   temp1 = pSchema->tblHash;
52015   temp2 = pSchema->trigHash;
52016   sqlite3HashInit(&pSchema->trigHash, SQLITE_HASH_STRING, 0);
52017   sqlite3HashClear(&pSchema->aFKey);
52018   sqlite3HashClear(&pSchema->idxHash);
52019   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
52020     sqlite3DeleteTrigger((Trigger*)sqliteHashData(pElem));
52021   }
52022   sqlite3HashClear(&temp2);
52023   sqlite3HashInit(&pSchema->tblHash, SQLITE_HASH_STRING, 0);
52024   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
52025     Table *pTab = sqliteHashData(pElem);
52026     sqlite3DeleteTable(pTab);
52027   }
52028   sqlite3HashClear(&temp1);
52029   pSchema->pSeqTab = 0;
52030   pSchema->flags &= ~DB_SchemaLoaded;
52031 }
52032
52033 /*
52034 ** Find and return the schema associated with a BTree.  Create
52035 ** a new one if necessary.
52036 */
52037 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
52038   Schema * p;
52039   if( pBt ){
52040     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
52041   }else{
52042     p = (Schema *)sqlite3MallocZero(sizeof(Schema));
52043   }
52044   if( !p ){
52045     db->mallocFailed = 1;
52046   }else if ( 0==p->file_format ){
52047     sqlite3HashInit(&p->tblHash, SQLITE_HASH_STRING, 0);
52048     sqlite3HashInit(&p->idxHash, SQLITE_HASH_STRING, 0);
52049     sqlite3HashInit(&p->trigHash, SQLITE_HASH_STRING, 0);
52050     sqlite3HashInit(&p->aFKey, SQLITE_HASH_STRING, 1);
52051     p->enc = SQLITE_UTF8;
52052   }
52053   return p;
52054 }
52055
52056 /************** End of callback.c ********************************************/
52057 /************** Begin file delete.c ******************************************/
52058 /*
52059 ** 2001 September 15
52060 **
52061 ** The author disclaims copyright to this source code.  In place of
52062 ** a legal notice, here is a blessing:
52063 **
52064 **    May you do good and not evil.
52065 **    May you find forgiveness for yourself and forgive others.
52066 **    May you share freely, never taking more than you give.
52067 **
52068 *************************************************************************
52069 ** This file contains C code routines that are called by the parser
52070 ** in order to generate code for DELETE FROM statements.
52071 **
52072 ** $Id: delete.c,v 1.134 2007/12/12 17:42:53 danielk1977 Exp $
52073 */
52074
52075 /*
52076 ** Look up every table that is named in pSrc.  If any table is not found,
52077 ** add an error message to pParse->zErrMsg and return NULL.  If all tables
52078 ** are found, return a pointer to the last table.
52079 */
52080 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
52081   Table *pTab = 0;
52082   int i;
52083   struct SrcList_item *pItem;
52084   for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
52085     pTab = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
52086     sqlite3DeleteTable(pItem->pTab);
52087     pItem->pTab = pTab;
52088     if( pTab ){
52089       pTab->nRef++;
52090     }
52091   }
52092   return pTab;
52093 }
52094
52095 /*
52096 ** Check to make sure the given table is writable.  If it is not
52097 ** writable, generate an error message and return 1.  If it is
52098 ** writable return 0;
52099 */
52100 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
52101   if( (pTab->readOnly && (pParse->db->flags & SQLITE_WriteSchema)==0
52102         && pParse->nested==0) 
52103 #ifndef SQLITE_OMIT_VIRTUALTABLE
52104       || (pTab->pMod && pTab->pMod->pModule->xUpdate==0)
52105 #endif
52106   ){
52107     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
52108     return 1;
52109   }
52110 #ifndef SQLITE_OMIT_VIEW
52111   if( !viewOk && pTab->pSelect ){
52112     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
52113     return 1;
52114   }
52115 #endif
52116   return 0;
52117 }
52118
52119 /*
52120 ** Generate code that will open a table for reading.
52121 */
52122 SQLITE_PRIVATE void sqlite3OpenTable(
52123   Parse *p,       /* Generate code into this VDBE */
52124   int iCur,       /* The cursor number of the table */
52125   int iDb,        /* The database index in sqlite3.aDb[] */
52126   Table *pTab,    /* The table to be opened */
52127   int opcode      /* OP_OpenRead or OP_OpenWrite */
52128 ){
52129   Vdbe *v;
52130   if( IsVirtual(pTab) ) return;
52131   v = sqlite3GetVdbe(p);
52132   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
52133   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite), pTab->zName);
52134   sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
52135   VdbeComment((v, "# %s", pTab->zName));
52136   sqlite3VdbeAddOp(v, opcode, iCur, pTab->tnum);
52137   sqlite3VdbeAddOp(v, OP_SetNumColumns, iCur, pTab->nCol);
52138 }
52139
52140
52141 /*
52142 ** Generate code for a DELETE FROM statement.
52143 **
52144 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
52145 **                 \________/       \________________/
52146 **                  pTabList              pWhere
52147 */
52148 SQLITE_PRIVATE void sqlite3DeleteFrom(
52149   Parse *pParse,         /* The parser context */
52150   SrcList *pTabList,     /* The table from which we should delete things */
52151   Expr *pWhere           /* The WHERE clause.  May be null */
52152 ){
52153   Vdbe *v;               /* The virtual database engine */
52154   Table *pTab;           /* The table from which records will be deleted */
52155   const char *zDb;       /* Name of database holding pTab */
52156   int end, addr = 0;     /* A couple addresses of generated code */
52157   int i;                 /* Loop counter */
52158   WhereInfo *pWInfo;     /* Information about the WHERE clause */
52159   Index *pIdx;           /* For looping over indices of the table */
52160   int iCur;              /* VDBE Cursor number for pTab */
52161   sqlite3 *db;           /* Main database structure */
52162   AuthContext sContext;  /* Authorization context */
52163   int oldIdx = -1;       /* Cursor for the OLD table of AFTER triggers */
52164   NameContext sNC;       /* Name context to resolve expressions in */
52165   int iDb;               /* Database number */
52166   int memCnt = 0;        /* Memory cell used for change counting */
52167
52168 #ifndef SQLITE_OMIT_TRIGGER
52169   int isView;                  /* True if attempting to delete from a view */
52170   int triggers_exist = 0;      /* True if any triggers exist */
52171 #endif
52172
52173   sContext.pParse = 0;
52174   db = pParse->db;
52175   if( pParse->nErr || db->mallocFailed ){
52176     goto delete_from_cleanup;
52177   }
52178   assert( pTabList->nSrc==1 );
52179
52180   /* Locate the table which we want to delete.  This table has to be
52181   ** put in an SrcList structure because some of the subroutines we
52182   ** will be calling are designed to work with multiple tables and expect
52183   ** an SrcList* parameter instead of just a Table* parameter.
52184   */
52185   pTab = sqlite3SrcListLookup(pParse, pTabList);
52186   if( pTab==0 )  goto delete_from_cleanup;
52187
52188   /* Figure out if we have any triggers and if the table being
52189   ** deleted from is a view
52190   */
52191 #ifndef SQLITE_OMIT_TRIGGER
52192   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0);
52193   isView = pTab->pSelect!=0;
52194 #else
52195 # define triggers_exist 0
52196 # define isView 0
52197 #endif
52198 #ifdef SQLITE_OMIT_VIEW
52199 # undef isView
52200 # define isView 0
52201 #endif
52202
52203   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
52204     goto delete_from_cleanup;
52205   }
52206   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
52207   assert( iDb<db->nDb );
52208   zDb = db->aDb[iDb].zName;
52209   if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
52210     goto delete_from_cleanup;
52211   }
52212
52213   /* If pTab is really a view, make sure it has been initialized.
52214   */
52215   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
52216     goto delete_from_cleanup;
52217   }
52218
52219   /* Allocate a cursor used to store the old.* data for a trigger.
52220   */
52221   if( triggers_exist ){ 
52222     oldIdx = pParse->nTab++;
52223   }
52224
52225   /* Resolve the column names in the WHERE clause.
52226   */
52227   assert( pTabList->nSrc==1 );
52228   iCur = pTabList->a[0].iCursor = pParse->nTab++;
52229   memset(&sNC, 0, sizeof(sNC));
52230   sNC.pParse = pParse;
52231   sNC.pSrcList = pTabList;
52232   if( sqlite3ExprResolveNames(&sNC, pWhere) ){
52233     goto delete_from_cleanup;
52234   }
52235
52236   /* Start the view context
52237   */
52238   if( isView ){
52239     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
52240   }
52241
52242   /* Begin generating code.
52243   */
52244   v = sqlite3GetVdbe(pParse);
52245   if( v==0 ){
52246     goto delete_from_cleanup;
52247   }
52248   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
52249   sqlite3BeginWriteOperation(pParse, triggers_exist, iDb);
52250
52251   /* If we are trying to delete from a view, realize that view into
52252   ** a ephemeral table.
52253   */
52254   if( isView ){
52255     Select *pView = sqlite3SelectDup(db, pTab->pSelect);
52256     sqlite3Select(pParse, pView, SRT_EphemTab, iCur, 0, 0, 0, 0);
52257     sqlite3SelectDelete(pView);
52258   }
52259
52260   /* Initialize the counter of the number of rows deleted, if
52261   ** we are counting rows.
52262   */
52263   if( db->flags & SQLITE_CountRows ){
52264     memCnt = pParse->nMem++;
52265     sqlite3VdbeAddOp(v, OP_MemInt, 0, memCnt);
52266   }
52267
52268   /* Special case: A DELETE without a WHERE clause deletes everything.
52269   ** It is easier just to erase the whole table.  Note, however, that
52270   ** this means that the row change count will be incorrect.
52271   */
52272   if( pWhere==0 && !triggers_exist && !IsVirtual(pTab) ){
52273     if( db->flags & SQLITE_CountRows ){
52274       /* If counting rows deleted, just count the total number of
52275       ** entries in the table. */
52276       int addr2;
52277       if( !isView ){
52278         sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
52279       }
52280       sqlite3VdbeAddOp(v, OP_Rewind, iCur, sqlite3VdbeCurrentAddr(v)+2);
52281       addr2 = sqlite3VdbeAddOp(v, OP_MemIncr, 1, memCnt);
52282       sqlite3VdbeAddOp(v, OP_Next, iCur, addr2);
52283       sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
52284     }
52285     if( !isView ){
52286       sqlite3VdbeAddOp(v, OP_Clear, pTab->tnum, iDb);
52287       if( !pParse->nested ){
52288         sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
52289       }
52290       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
52291         assert( pIdx->pSchema==pTab->pSchema );
52292         sqlite3VdbeAddOp(v, OP_Clear, pIdx->tnum, iDb);
52293       }
52294     }
52295   } 
52296   /* The usual case: There is a WHERE clause so we have to scan through
52297   ** the table and pick which records to delete.
52298   */
52299   else{
52300     /* Begin the database scan
52301     */
52302     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
52303     if( pWInfo==0 ) goto delete_from_cleanup;
52304
52305     /* Remember the rowid of every item to be deleted.
52306     */
52307     sqlite3VdbeAddOp(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid, iCur, 0);
52308     sqlite3VdbeAddOp(v, OP_FifoWrite, 0, 0);
52309     if( db->flags & SQLITE_CountRows ){
52310       sqlite3VdbeAddOp(v, OP_MemIncr, 1, memCnt);
52311     }
52312
52313     /* End the database scan loop.
52314     */
52315     sqlite3WhereEnd(pWInfo);
52316
52317     /* Open the pseudo-table used to store OLD if there are triggers.
52318     */
52319     if( triggers_exist ){
52320       sqlite3VdbeAddOp(v, OP_OpenPseudo, oldIdx, 0);
52321       sqlite3VdbeAddOp(v, OP_SetNumColumns, oldIdx, pTab->nCol);
52322     }
52323
52324     /* Delete every item whose key was written to the list during the
52325     ** database scan.  We have to delete items after the scan is complete
52326     ** because deleting an item can change the scan order.
52327     */
52328     end = sqlite3VdbeMakeLabel(v);
52329
52330     /* This is the beginning of the delete loop when there are
52331     ** row triggers.
52332     */
52333     if( triggers_exist ){
52334       int mem1 = pParse->nMem++;
52335       addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, end);
52336       sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0);
52337       sqlite3VdbeAddOp(v, OP_MemStore, mem1, 0);
52338       if( !isView ){
52339         sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
52340       }
52341       sqlite3VdbeAddOp(v, OP_NotExists, iCur, addr);
52342       sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
52343       sqlite3VdbeAddOp(v, OP_RowData, iCur, 0);
52344       sqlite3VdbeAddOp(v, OP_Insert, oldIdx, 0);
52345       if( !isView ){
52346         sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
52347       }
52348
52349       (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_BEFORE, pTab,
52350           -1, oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default,
52351           addr);
52352       if( !isView ){
52353         sqlite3VdbeAddOp(v, OP_MemLoad, mem1, 0);
52354       }
52355     }
52356
52357     if( !isView ){
52358       /* Open cursors for the table we are deleting from and all its
52359       ** indices.  If there are row triggers, this happens inside the
52360       ** OP_FifoRead loop because the cursor have to all be closed
52361       ** before the trigger fires.  If there are no row triggers, the
52362       ** cursors are opened only once on the outside the loop.
52363       */
52364       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
52365
52366       /* This is the beginning of the delete loop when there are no
52367       ** row triggers */
52368       if( !triggers_exist ){ 
52369         addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, end);
52370         sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0);
52371       }
52372
52373       /* Delete the row */
52374 #ifndef SQLITE_OMIT_VIRTUALTABLE
52375       if( IsVirtual(pTab) ){
52376         pParse->pVirtualLock = pTab;
52377         sqlite3VdbeOp3(v, OP_VUpdate, 0, 1, (const char*)pTab->pVtab, P3_VTAB);
52378       }else
52379 #endif
52380       {
52381         sqlite3GenerateRowDelete(db, v, pTab, iCur, pParse->nested==0);
52382       }
52383     }
52384
52385     /* If there are row triggers, close all cursors then invoke
52386     ** the AFTER triggers
52387     */
52388     if( triggers_exist ){
52389       if( !isView ){
52390         for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
52391           sqlite3VdbeAddOp(v, OP_Close, iCur + i, pIdx->tnum);
52392         }
52393         sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
52394       }
52395       (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_AFTER, pTab, -1,
52396           oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default,
52397           addr);
52398     }
52399
52400     /* End of the delete loop */
52401     sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
52402     sqlite3VdbeResolveLabel(v, end);
52403
52404     /* Close the cursors after the loop if there are no row triggers */
52405     if( !triggers_exist && !IsVirtual(pTab) ){
52406       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
52407         sqlite3VdbeAddOp(v, OP_Close, iCur + i, pIdx->tnum);
52408       }
52409       sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
52410     }
52411   }
52412
52413   /*
52414   ** Return the number of rows that were deleted. If this routine is 
52415   ** generating code because of a call to sqlite3NestedParse(), do not
52416   ** invoke the callback function.
52417   */
52418   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
52419     sqlite3VdbeAddOp(v, OP_MemLoad, memCnt, 0);
52420     sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
52421     sqlite3VdbeSetNumCols(v, 1);
52422     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", P3_STATIC);
52423   }
52424
52425 delete_from_cleanup:
52426   sqlite3AuthContextPop(&sContext);
52427   sqlite3SrcListDelete(pTabList);
52428   sqlite3ExprDelete(pWhere);
52429   return;
52430 }
52431
52432 /*
52433 ** This routine generates VDBE code that causes a single row of a
52434 ** single table to be deleted.
52435 **
52436 ** The VDBE must be in a particular state when this routine is called.
52437 ** These are the requirements:
52438 **
52439 **   1.  A read/write cursor pointing to pTab, the table containing the row
52440 **       to be deleted, must be opened as cursor number "base".
52441 **
52442 **   2.  Read/write cursors for all indices of pTab must be open as
52443 **       cursor number base+i for the i-th index.
52444 **
52445 **   3.  The record number of the row to be deleted must be on the top
52446 **       of the stack.
52447 **
52448 ** This routine pops the top of the stack to remove the record number
52449 ** and then generates code to remove both the table record and all index
52450 ** entries that point to that record.
52451 */
52452 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
52453   sqlite3 *db,       /* The database containing the index */
52454   Vdbe *v,           /* Generate code into this VDBE */
52455   Table *pTab,       /* Table containing the row to be deleted */
52456   int iCur,          /* Cursor number for the table */
52457   int count          /* Increment the row change counter */
52458 ){
52459   int addr;
52460   addr = sqlite3VdbeAddOp(v, OP_NotExists, iCur, 0);
52461   sqlite3GenerateRowIndexDelete(v, pTab, iCur, 0);
52462   sqlite3VdbeAddOp(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
52463   if( count ){
52464     sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
52465   }
52466   sqlite3VdbeJumpHere(v, addr);
52467 }
52468
52469 /*
52470 ** This routine generates VDBE code that causes the deletion of all
52471 ** index entries associated with a single row of a single table.
52472 **
52473 ** The VDBE must be in a particular state when this routine is called.
52474 ** These are the requirements:
52475 **
52476 **   1.  A read/write cursor pointing to pTab, the table containing the row
52477 **       to be deleted, must be opened as cursor number "iCur".
52478 **
52479 **   2.  Read/write cursors for all indices of pTab must be open as
52480 **       cursor number iCur+i for the i-th index.
52481 **
52482 **   3.  The "iCur" cursor must be pointing to the row that is to be
52483 **       deleted.
52484 */
52485 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
52486   Vdbe *v,           /* Generate code into this VDBE */
52487   Table *pTab,       /* Table containing the row to be deleted */
52488   int iCur,          /* Cursor number for the table */
52489   char *aIdxUsed     /* Only delete if aIdxUsed!=0 && aIdxUsed[i]!=0 */
52490 ){
52491   int i;
52492   Index *pIdx;
52493
52494   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
52495     if( aIdxUsed!=0 && aIdxUsed[i-1]==0 ) continue;
52496     sqlite3GenerateIndexKey(v, pIdx, iCur);
52497     sqlite3VdbeAddOp(v, OP_IdxDelete, iCur+i, 0);
52498   }
52499 }
52500
52501 /*
52502 ** Generate code that will assemble an index key and put it on the top
52503 ** of the tack.  The key with be for index pIdx which is an index on pTab.
52504 ** iCur is the index of a cursor open on the pTab table and pointing to
52505 ** the entry that needs indexing.
52506 */
52507 SQLITE_PRIVATE void sqlite3GenerateIndexKey(
52508   Vdbe *v,           /* Generate code into this VDBE */
52509   Index *pIdx,       /* The index for which to generate a key */
52510   int iCur           /* Cursor number for the pIdx->pTable table */
52511 ){
52512   int j;
52513   Table *pTab = pIdx->pTable;
52514
52515   sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
52516   for(j=0; j<pIdx->nColumn; j++){
52517     int idx = pIdx->aiColumn[j];
52518     if( idx==pTab->iPKey ){
52519       sqlite3VdbeAddOp(v, OP_Dup, j, 0);
52520     }else{
52521       sqlite3VdbeAddOp(v, OP_Column, iCur, idx);
52522       sqlite3ColumnDefault(v, pTab, idx);
52523     }
52524   }
52525   sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
52526   sqlite3IndexAffinityStr(v, pIdx);
52527 }
52528
52529 /************** End of delete.c **********************************************/
52530 /************** Begin file func.c ********************************************/
52531 /*
52532 ** 2002 February 23
52533 **
52534 ** The author disclaims copyright to this source code.  In place of
52535 ** a legal notice, here is a blessing:
52536 **
52537 **    May you do good and not evil.
52538 **    May you find forgiveness for yourself and forgive others.
52539 **    May you share freely, never taking more than you give.
52540 **
52541 *************************************************************************
52542 ** This file contains the C functions that implement various SQL
52543 ** functions of SQLite.  
52544 **
52545 ** There is only one exported symbol in this file - the function
52546 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
52547 ** All other code has file scope.
52548 **
52549 ** $Id: func.c,v 1.181 2007/12/13 21:54:11 drh Exp $
52550 */
52551
52552
52553 /*
52554 ** Return the collating function associated with a function.
52555 */
52556 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
52557   return context->pColl;
52558 }
52559
52560 /*
52561 ** Implementation of the non-aggregate min() and max() functions
52562 */
52563 static void minmaxFunc(
52564   sqlite3_context *context,
52565   int argc,
52566   sqlite3_value **argv
52567 ){
52568   int i;
52569   int mask;    /* 0 for min() or 0xffffffff for max() */
52570   int iBest;
52571   CollSeq *pColl;
52572
52573   if( argc==0 ) return;
52574   mask = sqlite3_user_data(context)==0 ? 0 : -1;
52575   pColl = sqlite3GetFuncCollSeq(context);
52576   assert( pColl );
52577   assert( mask==-1 || mask==0 );
52578   iBest = 0;
52579   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
52580   for(i=1; i<argc; i++){
52581     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
52582     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
52583       iBest = i;
52584     }
52585   }
52586   sqlite3_result_value(context, argv[iBest]);
52587 }
52588
52589 /*
52590 ** Return the type of the argument.
52591 */
52592 static void typeofFunc(
52593   sqlite3_context *context,
52594   int argc,
52595   sqlite3_value **argv
52596 ){
52597   const char *z = 0;
52598   switch( sqlite3_value_type(argv[0]) ){
52599     case SQLITE_NULL:    z = "null";    break;
52600     case SQLITE_INTEGER: z = "integer"; break;
52601     case SQLITE_TEXT:    z = "text";    break;
52602     case SQLITE_FLOAT:   z = "real";    break;
52603     case SQLITE_BLOB:    z = "blob";    break;
52604   }
52605   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
52606 }
52607
52608
52609 /*
52610 ** Implementation of the length() function
52611 */
52612 static void lengthFunc(
52613   sqlite3_context *context,
52614   int argc,
52615   sqlite3_value **argv
52616 ){
52617   int len;
52618
52619   assert( argc==1 );
52620   switch( sqlite3_value_type(argv[0]) ){
52621     case SQLITE_BLOB:
52622     case SQLITE_INTEGER:
52623     case SQLITE_FLOAT: {
52624       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
52625       break;
52626     }
52627     case SQLITE_TEXT: {
52628       const unsigned char *z = sqlite3_value_text(argv[0]);
52629       if( z==0 ) return;
52630       len = 0;
52631       while( *z ){
52632         len++;
52633         SQLITE_SKIP_UTF8(z);
52634       }
52635       sqlite3_result_int(context, len);
52636       break;
52637     }
52638     default: {
52639       sqlite3_result_null(context);
52640       break;
52641     }
52642   }
52643 }
52644
52645 /*
52646 ** Implementation of the abs() function
52647 */
52648 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
52649   assert( argc==1 );
52650   switch( sqlite3_value_type(argv[0]) ){
52651     case SQLITE_INTEGER: {
52652       i64 iVal = sqlite3_value_int64(argv[0]);
52653       if( iVal<0 ){
52654         if( (iVal<<1)==0 ){
52655           sqlite3_result_error(context, "integer overflow", -1);
52656           return;
52657         }
52658         iVal = -iVal;
52659       } 
52660       sqlite3_result_int64(context, iVal);
52661       break;
52662     }
52663     case SQLITE_NULL: {
52664       sqlite3_result_null(context);
52665       break;
52666     }
52667     default: {
52668       double rVal = sqlite3_value_double(argv[0]);
52669       if( rVal<0 ) rVal = -rVal;
52670       sqlite3_result_double(context, rVal);
52671       break;
52672     }
52673   }
52674 }
52675
52676 /*
52677 ** Implementation of the substr() function.
52678 **
52679 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
52680 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
52681 ** of x.  If x is text, then we actually count UTF-8 characters.
52682 ** If x is a blob, then we count bytes.
52683 **
52684 ** If p1 is negative, then we begin abs(p1) from the end of x[].
52685 */
52686 static void substrFunc(
52687   sqlite3_context *context,
52688   int argc,
52689   sqlite3_value **argv
52690 ){
52691   const unsigned char *z;
52692   const unsigned char *z2;
52693   int len;
52694   int p0type;
52695   i64 p1, p2;
52696
52697   assert( argc==3 || argc==2 );
52698   p0type = sqlite3_value_type(argv[0]);
52699   if( p0type==SQLITE_BLOB ){
52700     len = sqlite3_value_bytes(argv[0]);
52701     z = sqlite3_value_blob(argv[0]);
52702     if( z==0 ) return;
52703     assert( len==sqlite3_value_bytes(argv[0]) );
52704   }else{
52705     z = sqlite3_value_text(argv[0]);
52706     if( z==0 ) return;
52707     len = 0;
52708     for(z2=z; *z2; len++){
52709       SQLITE_SKIP_UTF8(z2);
52710     }
52711   }
52712   p1 = sqlite3_value_int(argv[1]);
52713   if( argc==3 ){
52714     p2 = sqlite3_value_int(argv[2]);
52715   }else{
52716     p2 = SQLITE_MAX_LENGTH;
52717   }
52718   if( p1<0 ){
52719     p1 += len;
52720     if( p1<0 ){
52721       p2 += p1;
52722       p1 = 0;
52723     }
52724   }else if( p1>0 ){
52725     p1--;
52726   }
52727   if( p1+p2>len ){
52728     p2 = len-p1;
52729   }
52730   if( p0type!=SQLITE_BLOB ){
52731     while( *z && p1 ){
52732       SQLITE_SKIP_UTF8(z);
52733       p1--;
52734     }
52735     for(z2=z; *z2 && p2; p2--){
52736       SQLITE_SKIP_UTF8(z2);
52737     }
52738     sqlite3_result_text(context, (char*)z, z2-z, SQLITE_TRANSIENT);
52739   }else{
52740     if( p2<0 ) p2 = 0;
52741     sqlite3_result_blob(context, (char*)&z[p1], p2, SQLITE_TRANSIENT);
52742   }
52743 }
52744
52745 /*
52746 ** Implementation of the round() function
52747 */
52748 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
52749   int n = 0;
52750   double r;
52751   char zBuf[500];  /* larger than the %f representation of the largest double */
52752   assert( argc==1 || argc==2 );
52753   if( argc==2 ){
52754     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
52755     n = sqlite3_value_int(argv[1]);
52756     if( n>30 ) n = 30;
52757     if( n<0 ) n = 0;
52758   }
52759   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
52760   r = sqlite3_value_double(argv[0]);
52761   sqlite3_snprintf(sizeof(zBuf),zBuf,"%.*f",n,r);
52762   sqlite3AtoF(zBuf, &r);
52763   sqlite3_result_double(context, r);
52764 }
52765
52766 /*
52767 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
52768 ** allocation fails, call sqlite3_result_error_nomem() to notify
52769 ** the database handle that malloc() has failed.
52770 */
52771 static void *contextMalloc(sqlite3_context *context, int nByte){
52772   char *z = sqlite3_malloc(nByte);
52773   if( !z && nByte>0 ){
52774     sqlite3_result_error_nomem(context);
52775   }
52776   return z;
52777 }
52778
52779 /*
52780 ** Implementation of the upper() and lower() SQL functions.
52781 */
52782 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
52783   char *z1;
52784   const char *z2;
52785   int i, n;
52786   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
52787   z2 = (char*)sqlite3_value_text(argv[0]);
52788   n = sqlite3_value_bytes(argv[0]);
52789   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
52790   assert( z2==(char*)sqlite3_value_text(argv[0]) );
52791   if( z2 ){
52792     z1 = contextMalloc(context, n+1);
52793     if( z1 ){
52794       memcpy(z1, z2, n+1);
52795       for(i=0; z1[i]; i++){
52796         z1[i] = toupper(z1[i]);
52797       }
52798       sqlite3_result_text(context, z1, -1, sqlite3_free);
52799     }
52800   }
52801 }
52802 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
52803   char *z1;
52804   const char *z2;
52805   int i, n;
52806   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
52807   z2 = (char*)sqlite3_value_text(argv[0]);
52808   n = sqlite3_value_bytes(argv[0]);
52809   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
52810   assert( z2==(char*)sqlite3_value_text(argv[0]) );
52811   if( z2 ){
52812     z1 = contextMalloc(context, n+1);
52813     if( z1 ){
52814       memcpy(z1, z2, n+1);
52815       for(i=0; z1[i]; i++){
52816         z1[i] = tolower(z1[i]);
52817       }
52818       sqlite3_result_text(context, z1, -1, sqlite3_free);
52819     }
52820   }
52821 }
52822
52823 /*
52824 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
52825 ** All three do the same thing.  They return the first non-NULL
52826 ** argument.
52827 */
52828 static void ifnullFunc(
52829   sqlite3_context *context,
52830   int argc,
52831   sqlite3_value **argv
52832 ){
52833   int i;
52834   for(i=0; i<argc; i++){
52835     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
52836       sqlite3_result_value(context, argv[i]);
52837       break;
52838     }
52839   }
52840 }
52841
52842 /*
52843 ** Implementation of random().  Return a random integer.  
52844 */
52845 static void randomFunc(
52846   sqlite3_context *context,
52847   int argc,
52848   sqlite3_value **argv
52849 ){
52850   sqlite_int64 r;
52851   sqlite3Randomness(sizeof(r), &r);
52852   if( (r<<1)==0 ) r = 0;  /* Prevent 0x8000.... as the result so that we */
52853                           /* can always do abs() of the result */
52854   sqlite3_result_int64(context, r);
52855 }
52856
52857 /*
52858 ** Implementation of randomblob(N).  Return a random blob
52859 ** that is N bytes long.
52860 */
52861 static void randomBlob(
52862   sqlite3_context *context,
52863   int argc,
52864   sqlite3_value **argv
52865 ){
52866   int n;
52867   unsigned char *p;
52868   assert( argc==1 );
52869   n = sqlite3_value_int(argv[0]);
52870   if( n<1 ){
52871     n = 1;
52872   }
52873   if( n>SQLITE_MAX_LENGTH ){
52874     sqlite3_result_error_toobig(context);
52875     return;
52876   }
52877   p = contextMalloc(context, n);
52878   if( p ){
52879     sqlite3Randomness(n, p);
52880     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
52881   }
52882 }
52883
52884 /*
52885 ** Implementation of the last_insert_rowid() SQL function.  The return
52886 ** value is the same as the sqlite3_last_insert_rowid() API function.
52887 */
52888 static void last_insert_rowid(
52889   sqlite3_context *context, 
52890   int arg, 
52891   sqlite3_value **argv
52892 ){
52893   sqlite3 *db = sqlite3_user_data(context);
52894   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
52895 }
52896
52897 /*
52898 ** Implementation of the changes() SQL function.  The return value is the
52899 ** same as the sqlite3_changes() API function.
52900 */
52901 static void changes(
52902   sqlite3_context *context,
52903   int arg,
52904   sqlite3_value **argv
52905 ){
52906   sqlite3 *db = sqlite3_user_data(context);
52907   sqlite3_result_int(context, sqlite3_changes(db));
52908 }
52909
52910 /*
52911 ** Implementation of the total_changes() SQL function.  The return value is
52912 ** the same as the sqlite3_total_changes() API function.
52913 */
52914 static void total_changes(
52915   sqlite3_context *context,
52916   int arg,
52917   sqlite3_value **argv
52918 ){
52919   sqlite3 *db = sqlite3_user_data(context);
52920   sqlite3_result_int(context, sqlite3_total_changes(db));
52921 }
52922
52923 /*
52924 ** A structure defining how to do GLOB-style comparisons.
52925 */
52926 struct compareInfo {
52927   u8 matchAll;
52928   u8 matchOne;
52929   u8 matchSet;
52930   u8 noCase;
52931 };
52932
52933 /*
52934 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
52935 ** character is exactly one byte in size.  Also, all characters are
52936 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
52937 ** whereas only characters less than 0x80 do in ASCII.
52938 */
52939 #if defined(SQLITE_EBCDIC)
52940 # define sqlite3Utf8Read(A,B,C)  (*(A++))
52941 # define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
52942 #else
52943 # define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
52944 #endif
52945
52946 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
52947 /* The correct SQL-92 behavior is for the LIKE operator to ignore
52948 ** case.  Thus  'a' LIKE 'A' would be true. */
52949 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
52950 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
52951 ** is case sensitive causing 'a' LIKE 'A' to be false */
52952 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
52953
52954 /*
52955 ** Compare two UTF-8 strings for equality where the first string can
52956 ** potentially be a "glob" expression.  Return true (1) if they
52957 ** are the same and false (0) if they are different.
52958 **
52959 ** Globbing rules:
52960 **
52961 **      '*'       Matches any sequence of zero or more characters.
52962 **
52963 **      '?'       Matches exactly one character.
52964 **
52965 **     [...]      Matches one character from the enclosed list of
52966 **                characters.
52967 **
52968 **     [^...]     Matches one character not in the enclosed list.
52969 **
52970 ** With the [...] and [^...] matching, a ']' character can be included
52971 ** in the list by making it the first character after '[' or '^'.  A
52972 ** range of characters can be specified using '-'.  Example:
52973 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
52974 ** it the last character in the list.
52975 **
52976 ** This routine is usually quick, but can be N**2 in the worst case.
52977 **
52978 ** Hints: to match '*' or '?', put them in "[]".  Like this:
52979 **
52980 **         abc[*]xyz        Matches "abc*xyz" only
52981 */
52982 static int patternCompare(
52983   const u8 *zPattern,              /* The glob pattern */
52984   const u8 *zString,               /* The string to compare against the glob */
52985   const struct compareInfo *pInfo, /* Information about how to do the compare */
52986   const int esc                    /* The escape character */
52987 ){
52988   int c, c2;
52989   int invert;
52990   int seen;
52991   u8 matchOne = pInfo->matchOne;
52992   u8 matchAll = pInfo->matchAll;
52993   u8 matchSet = pInfo->matchSet;
52994   u8 noCase = pInfo->noCase; 
52995   int prevEscape = 0;     /* True if the previous character was 'escape' */
52996
52997   while( (c = sqlite3Utf8Read(zPattern,0,&zPattern))!=0 ){
52998     if( !prevEscape && c==matchAll ){
52999       while( (c=sqlite3Utf8Read(zPattern,0,&zPattern)) == matchAll
53000                || c == matchOne ){
53001         if( c==matchOne && sqlite3Utf8Read(zString, 0, &zString)==0 ){
53002           return 0;
53003         }
53004       }
53005       if( c==0 ){
53006         return 1;
53007       }else if( c==esc ){
53008         c = sqlite3Utf8Read(zPattern, 0, &zPattern);
53009         if( c==0 ){
53010           return 0;
53011         }
53012       }else if( c==matchSet ){
53013         assert( esc==0 );         /* This is GLOB, not LIKE */
53014         assert( matchSet<0x80 );  /* '[' is a single-byte character */
53015         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
53016           SQLITE_SKIP_UTF8(zString);
53017         }
53018         return *zString!=0;
53019       }
53020       while( (c2 = sqlite3Utf8Read(zString,0,&zString))!=0 ){
53021         if( noCase ){
53022           GlogUpperToLower(c2);
53023           GlogUpperToLower(c);
53024           while( c2 != 0 && c2 != c ){
53025             c2 = sqlite3Utf8Read(zString, 0, &zString);
53026             GlogUpperToLower(c2);
53027           }
53028         }else{
53029           while( c2 != 0 && c2 != c ){
53030             c2 = sqlite3Utf8Read(zString, 0, &zString);
53031           }
53032         }
53033         if( c2==0 ) return 0;
53034         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
53035       }
53036       return 0;
53037     }else if( !prevEscape && c==matchOne ){
53038       if( sqlite3Utf8Read(zString, 0, &zString)==0 ){
53039         return 0;
53040       }
53041     }else if( c==matchSet ){
53042       int prior_c = 0;
53043       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
53044       seen = 0;
53045       invert = 0;
53046       c = sqlite3Utf8Read(zString, 0, &zString);
53047       if( c==0 ) return 0;
53048       c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
53049       if( c2=='^' ){
53050         invert = 1;
53051         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
53052       }
53053       if( c2==']' ){
53054         if( c==']' ) seen = 1;
53055         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
53056       }
53057       while( c2 && c2!=']' ){
53058         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
53059           c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
53060           if( c>=prior_c && c<=c2 ) seen = 1;
53061           prior_c = 0;
53062         }else{
53063           if( c==c2 ){
53064             seen = 1;
53065           }
53066           prior_c = c2;
53067         }
53068         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
53069       }
53070       if( c2==0 || (seen ^ invert)==0 ){
53071         return 0;
53072       }
53073     }else if( esc==c && !prevEscape ){
53074       prevEscape = 1;
53075     }else{
53076       c2 = sqlite3Utf8Read(zString, 0, &zString);
53077       if( noCase ){
53078         GlogUpperToLower(c);
53079         GlogUpperToLower(c2);
53080       }
53081       if( c!=c2 ){
53082         return 0;
53083       }
53084       prevEscape = 0;
53085     }
53086   }
53087   return *zString==0;
53088 }
53089
53090 /*
53091 ** Count the number of times that the LIKE operator (or GLOB which is
53092 ** just a variation of LIKE) gets called.  This is used for testing
53093 ** only.
53094 */
53095 #ifdef SQLITE_TEST
53096 SQLITE_API int sqlite3_like_count = 0;
53097 #endif
53098
53099
53100 /*
53101 ** Implementation of the like() SQL function.  This function implements
53102 ** the build-in LIKE operator.  The first argument to the function is the
53103 ** pattern and the second argument is the string.  So, the SQL statements:
53104 **
53105 **       A LIKE B
53106 **
53107 ** is implemented as like(B,A).
53108 **
53109 ** This same function (with a different compareInfo structure) computes
53110 ** the GLOB operator.
53111 */
53112 static void likeFunc(
53113   sqlite3_context *context, 
53114   int argc, 
53115   sqlite3_value **argv
53116 ){
53117   const unsigned char *zA, *zB;
53118   int escape = 0;
53119
53120   zB = sqlite3_value_text(argv[0]);
53121   zA = sqlite3_value_text(argv[1]);
53122
53123   /* Limit the length of the LIKE or GLOB pattern to avoid problems
53124   ** of deep recursion and N*N behavior in patternCompare().
53125   */
53126   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
53127     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
53128     return;
53129   }
53130   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
53131
53132   if( argc==3 ){
53133     /* The escape character string must consist of a single UTF-8 character.
53134     ** Otherwise, return an error.
53135     */
53136     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
53137     if( zEsc==0 ) return;
53138     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
53139       sqlite3_result_error(context, 
53140           "ESCAPE expression must be a single character", -1);
53141       return;
53142     }
53143     escape = sqlite3Utf8Read(zEsc, 0, &zEsc);
53144   }
53145   if( zA && zB ){
53146     struct compareInfo *pInfo = sqlite3_user_data(context);
53147 #ifdef SQLITE_TEST
53148     sqlite3_like_count++;
53149 #endif
53150     
53151     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
53152   }
53153 }
53154
53155 /*
53156 ** Implementation of the NULLIF(x,y) function.  The result is the first
53157 ** argument if the arguments are different.  The result is NULL if the
53158 ** arguments are equal to each other.
53159 */
53160 static void nullifFunc(
53161   sqlite3_context *context,
53162   int argc,
53163   sqlite3_value **argv
53164 ){
53165   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
53166   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
53167     sqlite3_result_value(context, argv[0]);
53168   }
53169 }
53170
53171 /*
53172 ** Implementation of the VERSION(*) function.  The result is the version
53173 ** of the SQLite library that is running.
53174 */
53175 static void versionFunc(
53176   sqlite3_context *context,
53177   int argc,
53178   sqlite3_value **argv
53179 ){
53180   sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
53181 }
53182
53183 /* Array for converting from half-bytes (nybbles) into ASCII hex
53184 ** digits. */
53185 static const char hexdigits[] = {
53186   '0', '1', '2', '3', '4', '5', '6', '7',
53187   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
53188 };
53189
53190 /*
53191 ** EXPERIMENTAL - This is not an official function.  The interface may
53192 ** change.  This function may disappear.  Do not write code that depends
53193 ** on this function.
53194 **
53195 ** Implementation of the QUOTE() function.  This function takes a single
53196 ** argument.  If the argument is numeric, the return value is the same as
53197 ** the argument.  If the argument is NULL, the return value is the string
53198 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
53199 ** single-quote escapes.
53200 */
53201 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
53202   if( argc<1 ) return;
53203   switch( sqlite3_value_type(argv[0]) ){
53204     case SQLITE_NULL: {
53205       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
53206       break;
53207     }
53208     case SQLITE_INTEGER:
53209     case SQLITE_FLOAT: {
53210       sqlite3_result_value(context, argv[0]);
53211       break;
53212     }
53213     case SQLITE_BLOB: {
53214       char *zText = 0;
53215       char const *zBlob = sqlite3_value_blob(argv[0]);
53216       int nBlob = sqlite3_value_bytes(argv[0]);
53217       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
53218
53219       if( 2*nBlob+4>SQLITE_MAX_LENGTH ){
53220         sqlite3_result_error_toobig(context);
53221         return;
53222       }
53223       zText = (char *)contextMalloc(context, (2*nBlob)+4); 
53224       if( zText ){
53225         int i;
53226         for(i=0; i<nBlob; i++){
53227           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
53228           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
53229         }
53230         zText[(nBlob*2)+2] = '\'';
53231         zText[(nBlob*2)+3] = '\0';
53232         zText[0] = 'X';
53233         zText[1] = '\'';
53234         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
53235         sqlite3_free(zText);
53236       }
53237       break;
53238     }
53239     case SQLITE_TEXT: {
53240       int i,j;
53241       u64 n;
53242       const unsigned char *zArg = sqlite3_value_text(argv[0]);
53243       char *z;
53244
53245       if( zArg==0 ) return;
53246       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
53247       if( i+n+3>SQLITE_MAX_LENGTH ){
53248         sqlite3_result_error_toobig(context);
53249         return;
53250       }
53251       z = contextMalloc(context, i+n+3);
53252       if( z ){
53253         z[0] = '\'';
53254         for(i=0, j=1; zArg[i]; i++){
53255           z[j++] = zArg[i];
53256           if( zArg[i]=='\'' ){
53257             z[j++] = '\'';
53258           }
53259         }
53260         z[j++] = '\'';
53261         z[j] = 0;
53262         sqlite3_result_text(context, z, j, sqlite3_free);
53263       }
53264     }
53265   }
53266 }
53267
53268 /*
53269 ** The hex() function.  Interpret the argument as a blob.  Return
53270 ** a hexadecimal rendering as text.
53271 */
53272 static void hexFunc(
53273   sqlite3_context *context,
53274   int argc,
53275   sqlite3_value **argv
53276 ){
53277   int i, n;
53278   const unsigned char *pBlob;
53279   char *zHex, *z;
53280   assert( argc==1 );
53281   pBlob = sqlite3_value_blob(argv[0]);
53282   n = sqlite3_value_bytes(argv[0]);
53283   if( n*2+1>SQLITE_MAX_LENGTH ){
53284     sqlite3_result_error_toobig(context);
53285     return;
53286   }
53287   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
53288   z = zHex = contextMalloc(context, n*2 + 1);
53289   if( zHex ){
53290     for(i=0; i<n; i++, pBlob++){
53291       unsigned char c = *pBlob;
53292       *(z++) = hexdigits[(c>>4)&0xf];
53293       *(z++) = hexdigits[c&0xf];
53294     }
53295     *z = 0;
53296     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
53297   }
53298 }
53299
53300 /*
53301 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
53302 */
53303 static void zeroblobFunc(
53304   sqlite3_context *context,
53305   int argc,
53306   sqlite3_value **argv
53307 ){
53308   i64 n;
53309   assert( argc==1 );
53310   n = sqlite3_value_int64(argv[0]);
53311   if( n>SQLITE_MAX_LENGTH ){
53312     sqlite3_result_error_toobig(context);
53313   }else{
53314     sqlite3_result_zeroblob(context, n);
53315   }
53316 }
53317
53318 /*
53319 ** The replace() function.  Three arguments are all strings: call
53320 ** them A, B, and C. The result is also a string which is derived
53321 ** from A by replacing every occurance of B with C.  The match
53322 ** must be exact.  Collating sequences are not used.
53323 */
53324 static void replaceFunc(
53325   sqlite3_context *context,
53326   int argc,
53327   sqlite3_value **argv
53328 ){
53329   const unsigned char *zStr;        /* The input string A */
53330   const unsigned char *zPattern;    /* The pattern string B */
53331   const unsigned char *zRep;        /* The replacement string C */
53332   unsigned char *zOut;              /* The output */
53333   int nStr;                /* Size of zStr */
53334   int nPattern;            /* Size of zPattern */
53335   int nRep;                /* Size of zRep */
53336   i64 nOut;                /* Maximum size of zOut */
53337   int loopLimit;           /* Last zStr[] that might match zPattern[] */
53338   int i, j;                /* Loop counters */
53339
53340   assert( argc==3 );
53341   zStr = sqlite3_value_text(argv[0]);
53342   if( zStr==0 ) return;
53343   nStr = sqlite3_value_bytes(argv[0]);
53344   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
53345   zPattern = sqlite3_value_text(argv[1]);
53346   if( zPattern==0 || zPattern[0]==0 ) return;
53347   nPattern = sqlite3_value_bytes(argv[1]);
53348   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
53349   zRep = sqlite3_value_text(argv[2]);
53350   if( zRep==0 ) return;
53351   nRep = sqlite3_value_bytes(argv[2]);
53352   assert( zRep==sqlite3_value_text(argv[2]) );
53353   nOut = nStr + 1;
53354   assert( nOut<SQLITE_MAX_LENGTH );
53355   zOut = contextMalloc(context, (int)nOut);
53356   if( zOut==0 ){
53357     return;
53358   }
53359   loopLimit = nStr - nPattern;  
53360   for(i=j=0; i<=loopLimit; i++){
53361     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
53362       zOut[j++] = zStr[i];
53363     }else{
53364       u8 *zOld;
53365       nOut += nRep - nPattern;
53366       if( nOut>=SQLITE_MAX_LENGTH ){
53367         sqlite3_result_error_toobig(context);
53368         sqlite3_free(zOut);
53369         return;
53370       }
53371       zOld = zOut;
53372       zOut = sqlite3_realloc(zOut, (int)nOut);
53373       if( zOut==0 ){
53374         sqlite3_result_error_nomem(context);
53375         sqlite3_free(zOld);
53376         return;
53377       }
53378       memcpy(&zOut[j], zRep, nRep);
53379       j += nRep;
53380       i += nPattern-1;
53381     }
53382   }
53383   assert( j+nStr-i+1==nOut );
53384   memcpy(&zOut[j], &zStr[i], nStr-i);
53385   j += nStr - i;
53386   assert( j<=nOut );
53387   zOut[j] = 0;
53388   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
53389 }
53390
53391 /*
53392 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
53393 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
53394 */
53395 static void trimFunc(
53396   sqlite3_context *context,
53397   int argc,
53398   sqlite3_value **argv
53399 ){
53400   const unsigned char *zIn;         /* Input string */
53401   const unsigned char *zCharSet;    /* Set of characters to trim */
53402   int nIn;                          /* Number of bytes in input */
53403   int flags;                        /* 1: trimleft  2: trimright  3: trim */
53404   int i;                            /* Loop counter */
53405   unsigned char *aLen;              /* Length of each character in zCharSet */
53406   unsigned char **azChar;           /* Individual characters in zCharSet */
53407   int nChar;                        /* Number of characters in zCharSet */
53408
53409   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
53410     return;
53411   }
53412   zIn = sqlite3_value_text(argv[0]);
53413   if( zIn==0 ) return;
53414   nIn = sqlite3_value_bytes(argv[0]);
53415   assert( zIn==sqlite3_value_text(argv[0]) );
53416   if( argc==1 ){
53417     static const unsigned char lenOne[] = { 1 };
53418     static const unsigned char *azOne[] = { (u8*)" " };
53419     nChar = 1;
53420     aLen = (u8*)lenOne;
53421     azChar = (unsigned char **)azOne;
53422     zCharSet = 0;
53423   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
53424     return;
53425   }else{
53426     const unsigned char *z;
53427     for(z=zCharSet, nChar=0; *z; nChar++){
53428       SQLITE_SKIP_UTF8(z);
53429     }
53430     if( nChar>0 ){
53431       azChar = contextMalloc(context, nChar*(sizeof(char*)+1));
53432       if( azChar==0 ){
53433         return;
53434       }
53435       aLen = (unsigned char*)&azChar[nChar];
53436       for(z=zCharSet, nChar=0; *z; nChar++){
53437         azChar[nChar] = (unsigned char *)z;
53438         SQLITE_SKIP_UTF8(z);
53439         aLen[nChar] = z - azChar[nChar];
53440       }
53441     }
53442   }
53443   if( nChar>0 ){
53444     flags = (int)sqlite3_user_data(context);
53445     if( flags & 1 ){
53446       while( nIn>0 ){
53447         int len;
53448         for(i=0; i<nChar; i++){
53449           len = aLen[i];
53450           if( memcmp(zIn, azChar[i], len)==0 ) break;
53451         }
53452         if( i>=nChar ) break;
53453         zIn += len;
53454         nIn -= len;
53455       }
53456     }
53457     if( flags & 2 ){
53458       while( nIn>0 ){
53459         int len;
53460         for(i=0; i<nChar; i++){
53461           len = aLen[i];
53462           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
53463         }
53464         if( i>=nChar ) break;
53465         nIn -= len;
53466       }
53467     }
53468     if( zCharSet ){
53469       sqlite3_free(azChar);
53470     }
53471   }
53472   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
53473 }
53474
53475 #ifdef SQLITE_SOUNDEX
53476 /*
53477 ** Compute the soundex encoding of a word.
53478 */
53479 static void soundexFunc(
53480   sqlite3_context *context,
53481   int argc,
53482   sqlite3_value **argv
53483 ){
53484   char zResult[8];
53485   const u8 *zIn;
53486   int i, j;
53487   static const unsigned char iCode[] = {
53488     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
53489     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
53490     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
53491     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
53492     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
53493     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
53494     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
53495     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
53496   };
53497   assert( argc==1 );
53498   zIn = (u8*)sqlite3_value_text(argv[0]);
53499   if( zIn==0 ) zIn = (u8*)"";
53500   for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
53501   if( zIn[i] ){
53502     u8 prevcode = iCode[zIn[i]&0x7f];
53503     zResult[0] = toupper(zIn[i]);
53504     for(j=1; j<4 && zIn[i]; i++){
53505       int code = iCode[zIn[i]&0x7f];
53506       if( code>0 ){
53507         if( code!=prevcode ){
53508           prevcode = code;
53509           zResult[j++] = code + '0';
53510         }
53511       }else{
53512         prevcode = 0;
53513       }
53514     }
53515     while( j<4 ){
53516       zResult[j++] = '0';
53517     }
53518     zResult[j] = 0;
53519     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
53520   }else{
53521     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
53522   }
53523 }
53524 #endif
53525
53526 #ifndef SQLITE_OMIT_LOAD_EXTENSION
53527 /*
53528 ** A function that loads a shared-library extension then returns NULL.
53529 */
53530 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
53531   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
53532   const char *zProc;
53533   sqlite3 *db = sqlite3_user_data(context);
53534   char *zErrMsg = 0;
53535
53536   if( argc==2 ){
53537     zProc = (const char *)sqlite3_value_text(argv[1]);
53538   }else{
53539     zProc = 0;
53540   }
53541   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
53542     sqlite3_result_error(context, zErrMsg, -1);
53543     sqlite3_free(zErrMsg);
53544   }
53545 }
53546 #endif
53547
53548 #ifdef SQLITE_TEST
53549 /*
53550 ** This function generates a string of random characters.  Used for
53551 ** generating test data.
53552 */
53553 static void randStr(sqlite3_context *context, int argc, sqlite3_value **argv){
53554   static const unsigned char zSrc[] = 
53555      "abcdefghijklmnopqrstuvwxyz"
53556      "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
53557      "0123456789"
53558      ".-!,:*^+=_|?/<> ";
53559   int iMin, iMax, n, r, i;
53560   unsigned char zBuf[1000];
53561
53562   /* It used to be possible to call randstr() with any number of arguments,
53563   ** but now it is registered with SQLite as requiring exactly 2.
53564   */
53565   assert(argc==2);
53566
53567   iMin = sqlite3_value_int(argv[0]);
53568   if( iMin<0 ) iMin = 0;
53569   if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
53570   iMax = sqlite3_value_int(argv[1]);
53571   if( iMax<iMin ) iMax = iMin;
53572   if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf)-1;
53573   n = iMin;
53574   if( iMax>iMin ){
53575     sqlite3Randomness(sizeof(r), &r);
53576     r &= 0x7fffffff;
53577     n += r%(iMax + 1 - iMin);
53578   }
53579   assert( n<sizeof(zBuf) );
53580   sqlite3Randomness(n, zBuf);
53581   for(i=0; i<n; i++){
53582     zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
53583   }
53584   zBuf[n] = 0;
53585   sqlite3_result_text(context, (char*)zBuf, n, SQLITE_TRANSIENT);
53586 }
53587 #endif /* SQLITE_TEST */
53588
53589 #ifdef SQLITE_TEST
53590 /*
53591 ** The following two SQL functions are used to test returning a text
53592 ** result with a destructor. Function 'test_destructor' takes one argument
53593 ** and returns the same argument interpreted as TEXT. A destructor is
53594 ** passed with the sqlite3_result_text() call.
53595 **
53596 ** SQL function 'test_destructor_count' returns the number of outstanding 
53597 ** allocations made by 'test_destructor';
53598 **
53599 ** WARNING: Not threadsafe.
53600 */
53601 static int test_destructor_count_var = 0;
53602 static void destructor(void *p){
53603   char *zVal = (char *)p;
53604   assert(zVal);
53605   zVal--;
53606   sqlite3_free(zVal);
53607   test_destructor_count_var--;
53608 }
53609 static void test_destructor(
53610   sqlite3_context *pCtx, 
53611   int nArg,
53612   sqlite3_value **argv
53613 ){
53614   char *zVal;
53615   int len;
53616   sqlite3 *db = sqlite3_user_data(pCtx);
53617  
53618   test_destructor_count_var++;
53619   assert( nArg==1 );
53620   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
53621   len = sqlite3ValueBytes(argv[0], ENC(db)); 
53622   zVal = contextMalloc(pCtx, len+3);
53623   if( !zVal ){
53624     return;
53625   }
53626   zVal[len+1] = 0;
53627   zVal[len+2] = 0;
53628   zVal++;
53629   memcpy(zVal, sqlite3ValueText(argv[0], ENC(db)), len);
53630   if( ENC(db)==SQLITE_UTF8 ){
53631     sqlite3_result_text(pCtx, zVal, -1, destructor);
53632 #ifndef SQLITE_OMIT_UTF16
53633   }else if( ENC(db)==SQLITE_UTF16LE ){
53634     sqlite3_result_text16le(pCtx, zVal, -1, destructor);
53635   }else{
53636     sqlite3_result_text16be(pCtx, zVal, -1, destructor);
53637 #endif /* SQLITE_OMIT_UTF16 */
53638   }
53639 }
53640 static void test_destructor_count(
53641   sqlite3_context *pCtx, 
53642   int nArg,
53643   sqlite3_value **argv
53644 ){
53645   sqlite3_result_int(pCtx, test_destructor_count_var);
53646 }
53647 #endif /* SQLITE_TEST */
53648
53649 #ifdef SQLITE_TEST
53650 /*
53651 ** Routines for testing the sqlite3_get_auxdata() and sqlite3_set_auxdata()
53652 ** interface.
53653 **
53654 ** The test_auxdata() SQL function attempts to register each of its arguments
53655 ** as auxiliary data.  If there are no prior registrations of aux data for
53656 ** that argument (meaning the argument is not a constant or this is its first
53657 ** call) then the result for that argument is 0.  If there is a prior
53658 ** registration, the result for that argument is 1.  The overall result
53659 ** is the individual argument results separated by spaces.
53660 */
53661 static void free_test_auxdata(void *p) {sqlite3_free(p);}
53662 static void test_auxdata(
53663   sqlite3_context *pCtx, 
53664   int nArg,
53665   sqlite3_value **argv
53666 ){
53667   int i;
53668   char *zRet = contextMalloc(pCtx, nArg*2);
53669   if( !zRet ) return;
53670   memset(zRet, 0, nArg*2);
53671   for(i=0; i<nArg; i++){
53672     char const *z = (char*)sqlite3_value_text(argv[i]);
53673     if( z ){
53674       char *zAux = sqlite3_get_auxdata(pCtx, i);
53675       if( zAux ){
53676         zRet[i*2] = '1';
53677         if( strcmp(zAux, z) ){
53678           sqlite3_result_error(pCtx, "Auxilary data corruption", -1);
53679           return;
53680         }
53681       }else {
53682         zRet[i*2] = '0';
53683       }
53684
53685       zAux = contextMalloc(pCtx, strlen(z)+1);
53686       if( zAux ){
53687         strcpy(zAux, z);
53688         sqlite3_set_auxdata(pCtx, i, zAux, free_test_auxdata);
53689       }
53690       zRet[i*2+1] = ' ';
53691     }
53692   }
53693   sqlite3_result_text(pCtx, zRet, 2*nArg-1, free_test_auxdata);
53694 }
53695 #endif /* SQLITE_TEST */
53696
53697 #ifdef SQLITE_TEST
53698 /*
53699 ** A function to test error reporting from user functions. This function
53700 ** returns a copy of its first argument as an error.
53701 */
53702 static void test_error(
53703   sqlite3_context *pCtx, 
53704   int nArg,
53705   sqlite3_value **argv
53706 ){
53707   sqlite3_result_error(pCtx, (char*)sqlite3_value_text(argv[0]), 0);
53708 }
53709 #endif /* SQLITE_TEST */
53710
53711 /*
53712 ** An instance of the following structure holds the context of a
53713 ** sum() or avg() aggregate computation.
53714 */
53715 typedef struct SumCtx SumCtx;
53716 struct SumCtx {
53717   double rSum;      /* Floating point sum */
53718   i64 iSum;         /* Integer sum */   
53719   i64 cnt;          /* Number of elements summed */
53720   u8 overflow;      /* True if integer overflow seen */
53721   u8 approx;        /* True if non-integer value was input to the sum */
53722 };
53723
53724 /*
53725 ** Routines used to compute the sum, average, and total.
53726 **
53727 ** The SUM() function follows the (broken) SQL standard which means
53728 ** that it returns NULL if it sums over no inputs.  TOTAL returns
53729 ** 0.0 in that case.  In addition, TOTAL always returns a float where
53730 ** SUM might return an integer if it never encounters a floating point
53731 ** value.  TOTAL never fails, but SUM might through an exception if
53732 ** it overflows an integer.
53733 */
53734 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
53735   SumCtx *p;
53736   int type;
53737   assert( argc==1 );
53738   p = sqlite3_aggregate_context(context, sizeof(*p));
53739   type = sqlite3_value_numeric_type(argv[0]);
53740   if( p && type!=SQLITE_NULL ){
53741     p->cnt++;
53742     if( type==SQLITE_INTEGER ){
53743       i64 v = sqlite3_value_int64(argv[0]);
53744       p->rSum += v;
53745       if( (p->approx|p->overflow)==0 ){
53746         i64 iNewSum = p->iSum + v;
53747         int s1 = p->iSum >> (sizeof(i64)*8-1);
53748         int s2 = v       >> (sizeof(i64)*8-1);
53749         int s3 = iNewSum >> (sizeof(i64)*8-1);
53750         p->overflow = (s1&s2&~s3) | (~s1&~s2&s3);
53751         p->iSum = iNewSum;
53752       }
53753     }else{
53754       p->rSum += sqlite3_value_double(argv[0]);
53755       p->approx = 1;
53756     }
53757   }
53758 }
53759 static void sumFinalize(sqlite3_context *context){
53760   SumCtx *p;
53761   p = sqlite3_aggregate_context(context, 0);
53762   if( p && p->cnt>0 ){
53763     if( p->overflow ){
53764       sqlite3_result_error(context,"integer overflow",-1);
53765     }else if( p->approx ){
53766       sqlite3_result_double(context, p->rSum);
53767     }else{
53768       sqlite3_result_int64(context, p->iSum);
53769     }
53770   }
53771 }
53772 static void avgFinalize(sqlite3_context *context){
53773   SumCtx *p;
53774   p = sqlite3_aggregate_context(context, 0);
53775   if( p && p->cnt>0 ){
53776     sqlite3_result_double(context, p->rSum/(double)p->cnt);
53777   }
53778 }
53779 static void totalFinalize(sqlite3_context *context){
53780   SumCtx *p;
53781   p = sqlite3_aggregate_context(context, 0);
53782   sqlite3_result_double(context, p ? p->rSum : 0.0);
53783 }
53784
53785 /*
53786 ** The following structure keeps track of state information for the
53787 ** count() aggregate function.
53788 */
53789 typedef struct CountCtx CountCtx;
53790 struct CountCtx {
53791   i64 n;
53792 };
53793
53794 /*
53795 ** Routines to implement the count() aggregate function.
53796 */
53797 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
53798   CountCtx *p;
53799   p = sqlite3_aggregate_context(context, sizeof(*p));
53800   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
53801     p->n++;
53802   }
53803 }   
53804 static void countFinalize(sqlite3_context *context){
53805   CountCtx *p;
53806   p = sqlite3_aggregate_context(context, 0);
53807   sqlite3_result_int64(context, p ? p->n : 0);
53808 }
53809
53810 /*
53811 ** Routines to implement min() and max() aggregate functions.
53812 */
53813 static void minmaxStep(sqlite3_context *context, int argc, sqlite3_value **argv){
53814   Mem *pArg  = (Mem *)argv[0];
53815   Mem *pBest;
53816
53817   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
53818   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
53819   if( !pBest ) return;
53820
53821   if( pBest->flags ){
53822     int max;
53823     int cmp;
53824     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
53825     /* This step function is used for both the min() and max() aggregates,
53826     ** the only difference between the two being that the sense of the
53827     ** comparison is inverted. For the max() aggregate, the
53828     ** sqlite3_user_data() function returns (void *)-1. For min() it
53829     ** returns (void *)db, where db is the sqlite3* database pointer.
53830     ** Therefore the next statement sets variable 'max' to 1 for the max()
53831     ** aggregate, or 0 for min().
53832     */
53833     max = sqlite3_user_data(context)!=0;
53834     cmp = sqlite3MemCompare(pBest, pArg, pColl);
53835     if( (max && cmp<0) || (!max && cmp>0) ){
53836       sqlite3VdbeMemCopy(pBest, pArg);
53837     }
53838   }else{
53839     sqlite3VdbeMemCopy(pBest, pArg);
53840   }
53841 }
53842 static void minMaxFinalize(sqlite3_context *context){
53843   sqlite3_value *pRes;
53844   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
53845   if( pRes ){
53846     if( pRes->flags ){
53847       sqlite3_result_value(context, pRes);
53848     }
53849     sqlite3VdbeMemRelease(pRes);
53850   }
53851 }
53852
53853 /*
53854 ** group_concat(EXPR, ?SEPARATOR?)
53855 */
53856 static void groupConcatStep(
53857   sqlite3_context *context,
53858   int argc,
53859   sqlite3_value **argv
53860 ){
53861   const char *zVal;
53862   StrAccum *pAccum;
53863   const char *zSep;
53864   int nVal, nSep;
53865   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
53866   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
53867
53868   if( pAccum ){
53869     pAccum->useMalloc = 1;
53870     if( pAccum->nChar ){
53871       if( argc==2 ){
53872         zSep = (char*)sqlite3_value_text(argv[1]);
53873         nSep = sqlite3_value_bytes(argv[1]);
53874       }else{
53875         zSep = ",";
53876         nSep = 1;
53877       }
53878       sqlite3StrAccumAppend(pAccum, zSep, nSep);
53879     }
53880     zVal = (char*)sqlite3_value_text(argv[0]);
53881     nVal = sqlite3_value_bytes(argv[0]);
53882     sqlite3StrAccumAppend(pAccum, zVal, nVal);
53883   }
53884 }
53885 static void groupConcatFinalize(sqlite3_context *context){
53886   StrAccum *pAccum;
53887   pAccum = sqlite3_aggregate_context(context, 0);
53888   if( pAccum ){
53889     if( pAccum->tooBig ){
53890       sqlite3_result_error_toobig(context);
53891     }else if( pAccum->mallocFailed ){
53892       sqlite3_result_error_nomem(context);
53893     }else{    
53894       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
53895                           sqlite3_free);
53896     }
53897   }
53898 }
53899
53900 /*
53901 ** This function registered all of the above C functions as SQL
53902 ** functions.  This should be the only routine in this file with
53903 ** external linkage.
53904 */
53905 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
53906   static const struct {
53907      char *zName;
53908      signed char nArg;
53909      u8 argType;           /* ff: db   1: 0, 2: 1, 3: 2,...  N:  N-1. */
53910      u8 eTextRep;          /* 1: UTF-16.  0: UTF-8 */
53911      u8 needCollSeq;
53912      void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
53913   } aFuncs[] = {
53914     { "min",               -1, 0, SQLITE_UTF8,    1, minmaxFunc },
53915     { "min",                0, 0, SQLITE_UTF8,    1, 0          },
53916     { "max",               -1, 1, SQLITE_UTF8,    1, minmaxFunc },
53917     { "max",                0, 1, SQLITE_UTF8,    1, 0          },
53918     { "typeof",             1, 0, SQLITE_UTF8,    0, typeofFunc },
53919     { "length",             1, 0, SQLITE_UTF8,    0, lengthFunc },
53920     { "substr",             2, 0, SQLITE_UTF8,    0, substrFunc },
53921     { "substr",             3, 0, SQLITE_UTF8,    0, substrFunc },
53922     { "abs",                1, 0, SQLITE_UTF8,    0, absFunc    },
53923     { "round",              1, 0, SQLITE_UTF8,    0, roundFunc  },
53924     { "round",              2, 0, SQLITE_UTF8,    0, roundFunc  },
53925     { "upper",              1, 0, SQLITE_UTF8,    0, upperFunc  },
53926     { "lower",              1, 0, SQLITE_UTF8,    0, lowerFunc  },
53927     { "coalesce",          -1, 0, SQLITE_UTF8,    0, ifnullFunc },
53928     { "coalesce",           0, 0, SQLITE_UTF8,    0, 0          },
53929     { "coalesce",           1, 0, SQLITE_UTF8,    0, 0          },
53930     { "hex",                1, 0, SQLITE_UTF8,    0, hexFunc    },
53931     { "ifnull",             2, 0, SQLITE_UTF8,    1, ifnullFunc },
53932     { "random",            -1, 0, SQLITE_UTF8,    0, randomFunc },
53933     { "randomblob",         1, 0, SQLITE_UTF8,    0, randomBlob },
53934     { "nullif",             2, 0, SQLITE_UTF8,    1, nullifFunc },
53935     { "sqlite_version",     0, 0, SQLITE_UTF8,    0, versionFunc},
53936     { "quote",              1, 0, SQLITE_UTF8,    0, quoteFunc  },
53937     { "last_insert_rowid",  0, 0xff, SQLITE_UTF8, 0, last_insert_rowid },
53938     { "changes",            0, 0xff, SQLITE_UTF8, 0, changes           },
53939     { "total_changes",      0, 0xff, SQLITE_UTF8, 0, total_changes     },
53940     { "replace",            3, 0, SQLITE_UTF8,    0, replaceFunc       },
53941     { "ltrim",              1, 1, SQLITE_UTF8,    0, trimFunc          },
53942     { "ltrim",              2, 1, SQLITE_UTF8,    0, trimFunc          },
53943     { "rtrim",              1, 2, SQLITE_UTF8,    0, trimFunc          },
53944     { "rtrim",              2, 2, SQLITE_UTF8,    0, trimFunc          },
53945     { "trim",               1, 3, SQLITE_UTF8,    0, trimFunc          },
53946     { "trim",               2, 3, SQLITE_UTF8,    0, trimFunc          },
53947     { "zeroblob",           1, 0, SQLITE_UTF8,    0, zeroblobFunc      },
53948 #ifdef SQLITE_SOUNDEX
53949     { "soundex",            1, 0, SQLITE_UTF8,    0, soundexFunc},
53950 #endif
53951 #ifndef SQLITE_OMIT_LOAD_EXTENSION
53952     { "load_extension",     1, 0xff, SQLITE_UTF8, 0, loadExt },
53953     { "load_extension",     2, 0xff, SQLITE_UTF8, 0, loadExt },
53954 #endif
53955 #ifdef SQLITE_TEST
53956     { "randstr",               2, 0,    SQLITE_UTF8, 0, randStr    },
53957     { "test_destructor",       1, 0xff, SQLITE_UTF8, 0, test_destructor},
53958     { "test_destructor_count", 0, 0,    SQLITE_UTF8, 0, test_destructor_count},
53959     { "test_auxdata",         -1, 0,    SQLITE_UTF8, 0, test_auxdata},
53960     { "test_error",            1, 0,    SQLITE_UTF8, 0, test_error},
53961 #endif
53962   };
53963   static const struct {
53964     char *zName;
53965     signed char nArg;
53966     u8 argType;
53967     u8 needCollSeq;
53968     void (*xStep)(sqlite3_context*,int,sqlite3_value**);
53969     void (*xFinalize)(sqlite3_context*);
53970   } aAggs[] = {
53971     { "min",    1, 0, 1, minmaxStep,   minMaxFinalize },
53972     { "max",    1, 1, 1, minmaxStep,   minMaxFinalize },
53973     { "sum",    1, 0, 0, sumStep,      sumFinalize    },
53974     { "total",  1, 0, 0, sumStep,      totalFinalize    },
53975     { "avg",    1, 0, 0, sumStep,      avgFinalize    },
53976     { "count",  0, 0, 0, countStep,    countFinalize  },
53977     { "count",  1, 0, 0, countStep,    countFinalize  },
53978     { "group_concat", 1, 0, 0, groupConcatStep, groupConcatFinalize },
53979     { "group_concat", 2, 0, 0, groupConcatStep, groupConcatFinalize },
53980   };
53981   int i;
53982
53983   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
53984     void *pArg;
53985     u8 argType = aFuncs[i].argType;
53986     if( argType==0xff ){
53987       pArg = db;
53988     }else{
53989       pArg = (void*)(int)argType;
53990     }
53991     sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
53992         aFuncs[i].eTextRep, pArg, aFuncs[i].xFunc, 0, 0);
53993     if( aFuncs[i].needCollSeq ){
53994       FuncDef *pFunc = sqlite3FindFunction(db, aFuncs[i].zName, 
53995           strlen(aFuncs[i].zName), aFuncs[i].nArg, aFuncs[i].eTextRep, 0);
53996       if( pFunc && aFuncs[i].needCollSeq ){
53997         pFunc->needCollSeq = 1;
53998       }
53999     }
54000   }
54001 #ifndef SQLITE_OMIT_ALTERTABLE
54002   sqlite3AlterFunctions(db);
54003 #endif
54004 #ifndef SQLITE_OMIT_PARSER
54005   sqlite3AttachFunctions(db);
54006 #endif
54007   for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
54008     void *pArg = (void*)(int)aAggs[i].argType;
54009     sqlite3CreateFunc(db, aAggs[i].zName, aAggs[i].nArg, SQLITE_UTF8, 
54010         pArg, 0, aAggs[i].xStep, aAggs[i].xFinalize);
54011     if( aAggs[i].needCollSeq ){
54012       FuncDef *pFunc = sqlite3FindFunction( db, aAggs[i].zName,
54013           strlen(aAggs[i].zName), aAggs[i].nArg, SQLITE_UTF8, 0);
54014       if( pFunc && aAggs[i].needCollSeq ){
54015         pFunc->needCollSeq = 1;
54016       }
54017     }
54018   }
54019   sqlite3RegisterDateTimeFunctions(db);
54020   if( !db->mallocFailed ){
54021     int rc = sqlite3_overload_function(db, "MATCH", 2);
54022     assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
54023     if( rc==SQLITE_NOMEM ){
54024       db->mallocFailed = 1;
54025     }
54026   }
54027 #ifdef SQLITE_SSE
54028   (void)sqlite3SseFunctions(db);
54029 #endif
54030 #ifdef SQLITE_CASE_SENSITIVE_LIKE
54031   sqlite3RegisterLikeFunctions(db, 1);
54032 #else
54033   sqlite3RegisterLikeFunctions(db, 0);
54034 #endif
54035 }
54036
54037 /*
54038 ** Set the LIKEOPT flag on the 2-argument function with the given name.
54039 */
54040 static void setLikeOptFlag(sqlite3 *db, const char *zName, int flagVal){
54041   FuncDef *pDef;
54042   pDef = sqlite3FindFunction(db, zName, strlen(zName), 2, SQLITE_UTF8, 0);
54043   if( pDef ){
54044     pDef->flags = flagVal;
54045   }
54046 }
54047
54048 /*
54049 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
54050 ** parameter determines whether or not the LIKE operator is case
54051 ** sensitive.  GLOB is always case sensitive.
54052 */
54053 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
54054   struct compareInfo *pInfo;
54055   if( caseSensitive ){
54056     pInfo = (struct compareInfo*)&likeInfoAlt;
54057   }else{
54058     pInfo = (struct compareInfo*)&likeInfoNorm;
54059   }
54060   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
54061   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
54062   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
54063       (struct compareInfo*)&globInfo, likeFunc, 0,0);
54064   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
54065   setLikeOptFlag(db, "like", 
54066       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
54067 }
54068
54069 /*
54070 ** pExpr points to an expression which implements a function.  If
54071 ** it is appropriate to apply the LIKE optimization to that function
54072 ** then set aWc[0] through aWc[2] to the wildcard characters and
54073 ** return TRUE.  If the function is not a LIKE-style function then
54074 ** return FALSE.
54075 */
54076 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
54077   FuncDef *pDef;
54078   if( pExpr->op!=TK_FUNCTION || !pExpr->pList ){
54079     return 0;
54080   }
54081   if( pExpr->pList->nExpr!=2 ){
54082     return 0;
54083   }
54084   pDef = sqlite3FindFunction(db, (char*)pExpr->token.z, pExpr->token.n, 2,
54085                              SQLITE_UTF8, 0);
54086   if( pDef==0 || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
54087     return 0;
54088   }
54089
54090   /* The memcpy() statement assumes that the wildcard characters are
54091   ** the first three statements in the compareInfo structure.  The
54092   ** asserts() that follow verify that assumption
54093   */
54094   memcpy(aWc, pDef->pUserData, 3);
54095   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
54096   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
54097   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
54098   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
54099   return 1;
54100 }
54101
54102 /************** End of func.c ************************************************/
54103 /************** Begin file insert.c ******************************************/
54104 /*
54105 ** 2001 September 15
54106 **
54107 ** The author disclaims copyright to this source code.  In place of
54108 ** a legal notice, here is a blessing:
54109 **
54110 **    May you do good and not evil.
54111 **    May you find forgiveness for yourself and forgive others.
54112 **    May you share freely, never taking more than you give.
54113 **
54114 *************************************************************************
54115 ** This file contains C code routines that are called by the parser
54116 ** to handle INSERT statements in SQLite.
54117 **
54118 ** $Id: insert.c,v 1.197 2007/12/14 16:11:09 drh Exp $
54119 */
54120
54121 /*
54122 ** Set P3 of the most recently inserted opcode to a column affinity
54123 ** string for index pIdx. A column affinity string has one character
54124 ** for each column in the table, according to the affinity of the column:
54125 **
54126 **  Character      Column affinity
54127 **  ------------------------------
54128 **  'a'            TEXT
54129 **  'b'            NONE
54130 **  'c'            NUMERIC
54131 **  'd'            INTEGER
54132 **  'e'            REAL
54133 */
54134 SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
54135   if( !pIdx->zColAff ){
54136     /* The first time a column affinity string for a particular index is
54137     ** required, it is allocated and populated here. It is then stored as
54138     ** a member of the Index structure for subsequent use.
54139     **
54140     ** The column affinity string will eventually be deleted by
54141     ** sqliteDeleteIndex() when the Index structure itself is cleaned
54142     ** up.
54143     */
54144     int n;
54145     Table *pTab = pIdx->pTable;
54146     sqlite3 *db = sqlite3VdbeDb(v);
54147     pIdx->zColAff = (char *)sqlite3DbMallocZero(db, pIdx->nColumn+1);
54148     if( !pIdx->zColAff ){
54149       return;
54150     }
54151     for(n=0; n<pIdx->nColumn; n++){
54152       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
54153     }
54154     pIdx->zColAff[pIdx->nColumn] = '\0';
54155   }
54156  
54157   sqlite3VdbeChangeP3(v, -1, pIdx->zColAff, 0);
54158 }
54159
54160 /*
54161 ** Set P3 of the most recently inserted opcode to a column affinity
54162 ** string for table pTab. A column affinity string has one character
54163 ** for each column indexed by the index, according to the affinity of the
54164 ** column:
54165 **
54166 **  Character      Column affinity
54167 **  ------------------------------
54168 **  'a'            TEXT
54169 **  'b'            NONE
54170 **  'c'            NUMERIC
54171 **  'd'            INTEGER
54172 **  'e'            REAL
54173 */
54174 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
54175   /* The first time a column affinity string for a particular table
54176   ** is required, it is allocated and populated here. It is then 
54177   ** stored as a member of the Table structure for subsequent use.
54178   **
54179   ** The column affinity string will eventually be deleted by
54180   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
54181   */
54182   if( !pTab->zColAff ){
54183     char *zColAff;
54184     int i;
54185     sqlite3 *db = sqlite3VdbeDb(v);
54186
54187     zColAff = (char *)sqlite3DbMallocZero(db, pTab->nCol+1);
54188     if( !zColAff ){
54189       return;
54190     }
54191
54192     for(i=0; i<pTab->nCol; i++){
54193       zColAff[i] = pTab->aCol[i].affinity;
54194     }
54195     zColAff[pTab->nCol] = '\0';
54196
54197     pTab->zColAff = zColAff;
54198   }
54199
54200   sqlite3VdbeChangeP3(v, -1, pTab->zColAff, 0);
54201 }
54202
54203 /*
54204 ** Return non-zero if the table pTab in database iDb or any of its indices
54205 ** have been opened at any point in the VDBE program beginning at location
54206 ** iStartAddr throught the end of the program.  This is used to see if 
54207 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
54208 ** run without using temporary table for the results of the SELECT. 
54209 */
54210 static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
54211   int i;
54212   int iEnd = sqlite3VdbeCurrentAddr(v);
54213   for(i=iStartAddr; i<iEnd; i++){
54214     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
54215     assert( pOp!=0 );
54216     if( pOp->opcode==OP_OpenRead ){
54217       VdbeOp *pPrior = &pOp[-1];
54218       int tnum = pOp->p2;
54219       assert( i>iStartAddr );
54220       assert( pPrior->opcode==OP_Integer );
54221       if( pPrior->p1==iDb ){
54222         Index *pIndex;
54223         if( tnum==pTab->tnum ){
54224           return 1;
54225         }
54226         for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
54227           if( tnum==pIndex->tnum ){
54228             return 1;
54229           }
54230         }
54231       }
54232     }
54233 #ifndef SQLITE_OMIT_VIRTUALTABLE
54234     if( pOp->opcode==OP_VOpen && pOp->p3==(const char*)pTab->pVtab ){
54235       assert( pOp->p3!=0 );
54236       assert( pOp->p3type==P3_VTAB );
54237       return 1;
54238     }
54239 #endif
54240   }
54241   return 0;
54242 }
54243
54244 #ifndef SQLITE_OMIT_AUTOINCREMENT
54245 /*
54246 ** Write out code to initialize the autoincrement logic.  This code
54247 ** looks up the current autoincrement value in the sqlite_sequence
54248 ** table and stores that value in a memory cell.  Code generated by
54249 ** autoIncStep() will keep that memory cell holding the largest
54250 ** rowid value.  Code generated by autoIncEnd() will write the new
54251 ** largest value of the counter back into the sqlite_sequence table.
54252 **
54253 ** This routine returns the index of the mem[] cell that contains
54254 ** the maximum rowid counter.
54255 **
54256 ** Two memory cells are allocated.  The next memory cell after the
54257 ** one returned holds the rowid in sqlite_sequence where we will
54258 ** write back the revised maximum rowid.
54259 */
54260 static int autoIncBegin(
54261   Parse *pParse,      /* Parsing context */
54262   int iDb,            /* Index of the database holding pTab */
54263   Table *pTab         /* The table we are writing to */
54264 ){
54265   int memId = 0;
54266   if( pTab->autoInc ){
54267     Vdbe *v = pParse->pVdbe;
54268     Db *pDb = &pParse->db->aDb[iDb];
54269     int iCur = pParse->nTab;
54270     int addr;
54271     assert( v );
54272     addr = sqlite3VdbeCurrentAddr(v);
54273     memId = pParse->nMem+1;
54274     pParse->nMem += 2;
54275     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
54276     sqlite3VdbeAddOp(v, OP_Rewind, iCur, addr+13);
54277     sqlite3VdbeAddOp(v, OP_Column, iCur, 0);
54278     sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
54279     sqlite3VdbeAddOp(v, OP_Ne, 0x100, addr+12);
54280     sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
54281     sqlite3VdbeAddOp(v, OP_MemStore, memId-1, 1);
54282     sqlite3VdbeAddOp(v, OP_Column, iCur, 1);
54283     sqlite3VdbeAddOp(v, OP_MemStore, memId, 1);
54284     sqlite3VdbeAddOp(v, OP_Goto, 0, addr+13);
54285     sqlite3VdbeAddOp(v, OP_Next, iCur, addr+4);
54286     sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
54287   }
54288   return memId;
54289 }
54290
54291 /*
54292 ** Update the maximum rowid for an autoincrement calculation.
54293 **
54294 ** This routine should be called when the top of the stack holds a
54295 ** new rowid that is about to be inserted.  If that new rowid is
54296 ** larger than the maximum rowid in the memId memory cell, then the
54297 ** memory cell is updated.  The stack is unchanged.
54298 */
54299 static void autoIncStep(Parse *pParse, int memId){
54300   if( memId>0 ){
54301     sqlite3VdbeAddOp(pParse->pVdbe, OP_MemMax, memId, 0);
54302   }
54303 }
54304
54305 /*
54306 ** After doing one or more inserts, the maximum rowid is stored
54307 ** in mem[memId].  Generate code to write this value back into the
54308 ** the sqlite_sequence table.
54309 */
54310 static void autoIncEnd(
54311   Parse *pParse,     /* The parsing context */
54312   int iDb,           /* Index of the database holding pTab */
54313   Table *pTab,       /* Table we are inserting into */
54314   int memId          /* Memory cell holding the maximum rowid */
54315 ){
54316   if( pTab->autoInc ){
54317     int iCur = pParse->nTab;
54318     Vdbe *v = pParse->pVdbe;
54319     Db *pDb = &pParse->db->aDb[iDb];
54320     int addr;
54321     assert( v );
54322     addr = sqlite3VdbeCurrentAddr(v);
54323     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
54324     sqlite3VdbeAddOp(v, OP_MemLoad, memId-1, 0);
54325     sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+7);
54326     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
54327     sqlite3VdbeAddOp(v, OP_NewRowid, iCur, 0);
54328     sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
54329     sqlite3VdbeAddOp(v, OP_MemLoad, memId, 0);
54330     sqlite3VdbeAddOp(v, OP_MakeRecord, 2, 0);
54331     sqlite3VdbeAddOp(v, OP_Insert, iCur, OPFLAG_APPEND);
54332     sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
54333   }
54334 }
54335 #else
54336 /*
54337 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
54338 ** above are all no-ops
54339 */
54340 # define autoIncBegin(A,B,C) (0)
54341 # define autoIncStep(A,B)
54342 # define autoIncEnd(A,B,C,D)
54343 #endif /* SQLITE_OMIT_AUTOINCREMENT */
54344
54345
54346 /* Forward declaration */
54347 static int xferOptimization(
54348   Parse *pParse,        /* Parser context */
54349   Table *pDest,         /* The table we are inserting into */
54350   Select *pSelect,      /* A SELECT statement to use as the data source */
54351   int onError,          /* How to handle constraint errors */
54352   int iDbDest           /* The database of pDest */
54353 );
54354
54355 /*
54356 ** This routine is call to handle SQL of the following forms:
54357 **
54358 **    insert into TABLE (IDLIST) values(EXPRLIST)
54359 **    insert into TABLE (IDLIST) select
54360 **
54361 ** The IDLIST following the table name is always optional.  If omitted,
54362 ** then a list of all columns for the table is substituted.  The IDLIST
54363 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
54364 **
54365 ** The pList parameter holds EXPRLIST in the first form of the INSERT
54366 ** statement above, and pSelect is NULL.  For the second form, pList is
54367 ** NULL and pSelect is a pointer to the select statement used to generate
54368 ** data for the insert.
54369 **
54370 ** The code generated follows one of four templates.  For a simple
54371 ** select with data coming from a VALUES clause, the code executes
54372 ** once straight down through.  The template looks like this:
54373 **
54374 **         open write cursor to <table> and its indices
54375 **         puts VALUES clause expressions onto the stack
54376 **         write the resulting record into <table>
54377 **         cleanup
54378 **
54379 ** The three remaining templates assume the statement is of the form
54380 **
54381 **   INSERT INTO <table> SELECT ...
54382 **
54383 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
54384 ** in other words if the SELECT pulls all columns from a single table
54385 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
54386 ** if <table2> and <table1> are distinct tables but have identical
54387 ** schemas, including all the same indices, then a special optimization
54388 ** is invoked that copies raw records from <table2> over to <table1>.
54389 ** See the xferOptimization() function for the implementation of this
54390 ** template.  This is the second template.
54391 **
54392 **         open a write cursor to <table>
54393 **         open read cursor on <table2>
54394 **         transfer all records in <table2> over to <table>
54395 **         close cursors
54396 **         foreach index on <table>
54397 **           open a write cursor on the <table> index
54398 **           open a read cursor on the corresponding <table2> index
54399 **           transfer all records from the read to the write cursors
54400 **           close cursors
54401 **         end foreach
54402 **
54403 ** The third template is for when the second template does not apply
54404 ** and the SELECT clause does not read from <table> at any time.
54405 ** The generated code follows this template:
54406 **
54407 **         goto B
54408 **      A: setup for the SELECT
54409 **         loop over the rows in the SELECT
54410 **           gosub C
54411 **         end loop
54412 **         cleanup after the SELECT
54413 **         goto D
54414 **      B: open write cursor to <table> and its indices
54415 **         goto A
54416 **      C: insert the select result into <table>
54417 **         return
54418 **      D: cleanup
54419 **
54420 ** The fourth template is used if the insert statement takes its
54421 ** values from a SELECT but the data is being inserted into a table
54422 ** that is also read as part of the SELECT.  In the third form,
54423 ** we have to use a intermediate table to store the results of
54424 ** the select.  The template is like this:
54425 **
54426 **         goto B
54427 **      A: setup for the SELECT
54428 **         loop over the tables in the SELECT
54429 **           gosub C
54430 **         end loop
54431 **         cleanup after the SELECT
54432 **         goto D
54433 **      C: insert the select result into the intermediate table
54434 **         return
54435 **      B: open a cursor to an intermediate table
54436 **         goto A
54437 **      D: open write cursor to <table> and its indices
54438 **         loop over the intermediate table
54439 **           transfer values form intermediate table into <table>
54440 **         end the loop
54441 **         cleanup
54442 */
54443 SQLITE_PRIVATE void sqlite3Insert(
54444   Parse *pParse,        /* Parser context */
54445   SrcList *pTabList,    /* Name of table into which we are inserting */
54446   ExprList *pList,      /* List of values to be inserted */
54447   Select *pSelect,      /* A SELECT statement to use as the data source */
54448   IdList *pColumn,      /* Column names corresponding to IDLIST. */
54449   int onError           /* How to handle constraint errors */
54450 ){
54451   Table *pTab;          /* The table to insert into */
54452   char *zTab;           /* Name of the table into which we are inserting */
54453   const char *zDb;      /* Name of the database holding this table */
54454   int i, j, idx;        /* Loop counters */
54455   Vdbe *v;              /* Generate code into this virtual machine */
54456   Index *pIdx;          /* For looping over indices of the table */
54457   int nColumn;          /* Number of columns in the data */
54458   int base = 0;         /* VDBE Cursor number for pTab */
54459   int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
54460   sqlite3 *db;          /* The main database structure */
54461   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
54462   int endOfLoop;        /* Label for the end of the insertion loop */
54463   int useTempTable = 0; /* Store SELECT results in intermediate table */
54464   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
54465   int iSelectLoop = 0;  /* Address of code that implements the SELECT */
54466   int iCleanup = 0;     /* Address of the cleanup code */
54467   int iInsertBlock = 0; /* Address of the subroutine used to insert data */
54468   int iCntMem = 0;      /* Memory cell used for the row counter */
54469   int newIdx = -1;      /* Cursor for the NEW table */
54470   Db *pDb;              /* The database containing table being inserted into */
54471   int counterMem = 0;   /* Memory cell holding AUTOINCREMENT counter */
54472   int appendFlag = 0;   /* True if the insert is likely to be an append */
54473   int iDb;
54474
54475   int nHidden = 0;
54476
54477 #ifndef SQLITE_OMIT_TRIGGER
54478   int isView;                 /* True if attempting to insert into a view */
54479   int triggers_exist = 0;     /* True if there are FOR EACH ROW triggers */
54480 #endif
54481
54482   db = pParse->db;
54483   if( pParse->nErr || db->mallocFailed ){
54484     goto insert_cleanup;
54485   }
54486
54487   /* Locate the table into which we will be inserting new information.
54488   */
54489   assert( pTabList->nSrc==1 );
54490   zTab = pTabList->a[0].zName;
54491   if( zTab==0 ) goto insert_cleanup;
54492   pTab = sqlite3SrcListLookup(pParse, pTabList);
54493   if( pTab==0 ){
54494     goto insert_cleanup;
54495   }
54496   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
54497   assert( iDb<db->nDb );
54498   pDb = &db->aDb[iDb];
54499   zDb = pDb->zName;
54500   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
54501     goto insert_cleanup;
54502   }
54503
54504   /* Figure out if we have any triggers and if the table being
54505   ** inserted into is a view
54506   */
54507 #ifndef SQLITE_OMIT_TRIGGER
54508   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
54509   isView = pTab->pSelect!=0;
54510 #else
54511 # define triggers_exist 0
54512 # define isView 0
54513 #endif
54514 #ifdef SQLITE_OMIT_VIEW
54515 # undef isView
54516 # define isView 0
54517 #endif
54518
54519   /* Ensure that:
54520   *  (a) the table is not read-only, 
54521   *  (b) that if it is a view then ON INSERT triggers exist
54522   */
54523   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
54524     goto insert_cleanup;
54525   }
54526   assert( pTab!=0 );
54527
54528   /* If pTab is really a view, make sure it has been initialized.
54529   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
54530   ** module table).
54531   */
54532   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
54533     goto insert_cleanup;
54534   }
54535
54536   /* Allocate a VDBE
54537   */
54538   v = sqlite3GetVdbe(pParse);
54539   if( v==0 ) goto insert_cleanup;
54540   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
54541   sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
54542
54543   /* if there are row triggers, allocate a temp table for new.* references. */
54544   if( triggers_exist ){
54545     newIdx = pParse->nTab++;
54546   }
54547
54548 #ifndef SQLITE_OMIT_XFER_OPT
54549   /* If the statement is of the form
54550   **
54551   **       INSERT INTO <table1> SELECT * FROM <table2>;
54552   **
54553   ** Then special optimizations can be applied that make the transfer
54554   ** very fast and which reduce fragmentation of indices.
54555   */
54556   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
54557     assert( !triggers_exist );
54558     assert( pList==0 );
54559     goto insert_cleanup;
54560   }
54561 #endif /* SQLITE_OMIT_XFER_OPT */
54562
54563   /* If this is an AUTOINCREMENT table, look up the sequence number in the
54564   ** sqlite_sequence table and store it in memory cell counterMem.  Also
54565   ** remember the rowid of the sqlite_sequence table entry in memory cell
54566   ** counterRowid.
54567   */
54568   counterMem = autoIncBegin(pParse, iDb, pTab);
54569
54570   /* Figure out how many columns of data are supplied.  If the data
54571   ** is coming from a SELECT statement, then this step also generates
54572   ** all the code to implement the SELECT statement and invoke a subroutine
54573   ** to process each row of the result. (Template 2.) If the SELECT
54574   ** statement uses the the table that is being inserted into, then the
54575   ** subroutine is also coded here.  That subroutine stores the SELECT
54576   ** results in a temporary table. (Template 3.)
54577   */
54578   if( pSelect ){
54579     /* Data is coming from a SELECT.  Generate code to implement that SELECT
54580     */
54581     int rc, iInitCode;
54582     iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
54583     iSelectLoop = sqlite3VdbeCurrentAddr(v);
54584     iInsertBlock = sqlite3VdbeMakeLabel(v);
54585
54586     /* Resolve the expressions in the SELECT statement and execute it. */
54587     rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0);
54588     if( rc || pParse->nErr || db->mallocFailed ){
54589       goto insert_cleanup;
54590     }
54591
54592     iCleanup = sqlite3VdbeMakeLabel(v);
54593     sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
54594     assert( pSelect->pEList );
54595     nColumn = pSelect->pEList->nExpr;
54596
54597     /* Set useTempTable to TRUE if the result of the SELECT statement
54598     ** should be written into a temporary table.  Set to FALSE if each
54599     ** row of the SELECT can be written directly into the result table.
54600     **
54601     ** A temp table must be used if the table being updated is also one
54602     ** of the tables being read by the SELECT statement.  Also use a 
54603     ** temp table in the case of row triggers.
54604     */
54605     if( triggers_exist || readsTable(v, iSelectLoop, iDb, pTab) ){
54606       useTempTable = 1;
54607     }
54608
54609     if( useTempTable ){
54610       /* Generate the subroutine that SELECT calls to process each row of
54611       ** the result.  Store the result in a temporary table
54612       */
54613       srcTab = pParse->nTab++;
54614       sqlite3VdbeResolveLabel(v, iInsertBlock);
54615       sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0);
54616       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
54617       sqlite3VdbeAddOp(v, OP_NewRowid, srcTab, 0);
54618       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
54619       sqlite3VdbeAddOp(v, OP_Insert, srcTab, OPFLAG_APPEND);
54620       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
54621
54622       /* The following code runs first because the GOTO at the very top
54623       ** of the program jumps to it.  Create the temporary table, then jump
54624       ** back up and execute the SELECT code above.
54625       */
54626       sqlite3VdbeJumpHere(v, iInitCode);
54627       sqlite3VdbeAddOp(v, OP_OpenEphemeral, srcTab, 0);
54628       sqlite3VdbeAddOp(v, OP_SetNumColumns, srcTab, nColumn);
54629       sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
54630       sqlite3VdbeResolveLabel(v, iCleanup);
54631     }else{
54632       sqlite3VdbeJumpHere(v, iInitCode);
54633     }
54634   }else{
54635     /* This is the case if the data for the INSERT is coming from a VALUES
54636     ** clause
54637     */
54638     NameContext sNC;
54639     memset(&sNC, 0, sizeof(sNC));
54640     sNC.pParse = pParse;
54641     srcTab = -1;
54642     assert( useTempTable==0 );
54643     nColumn = pList ? pList->nExpr : 0;
54644     for(i=0; i<nColumn; i++){
54645       if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
54646         goto insert_cleanup;
54647       }
54648     }
54649   }
54650
54651   /* Make sure the number of columns in the source data matches the number
54652   ** of columns to be inserted into the table.
54653   */
54654   if( IsVirtual(pTab) ){
54655     for(i=0; i<pTab->nCol; i++){
54656       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
54657     }
54658   }
54659   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
54660     sqlite3ErrorMsg(pParse, 
54661        "table %S has %d columns but %d values were supplied",
54662        pTabList, 0, pTab->nCol, nColumn);
54663     goto insert_cleanup;
54664   }
54665   if( pColumn!=0 && nColumn!=pColumn->nId ){
54666     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
54667     goto insert_cleanup;
54668   }
54669
54670   /* If the INSERT statement included an IDLIST term, then make sure
54671   ** all elements of the IDLIST really are columns of the table and 
54672   ** remember the column indices.
54673   **
54674   ** If the table has an INTEGER PRIMARY KEY column and that column
54675   ** is named in the IDLIST, then record in the keyColumn variable
54676   ** the index into IDLIST of the primary key column.  keyColumn is
54677   ** the index of the primary key as it appears in IDLIST, not as
54678   ** is appears in the original table.  (The index of the primary
54679   ** key in the original table is pTab->iPKey.)
54680   */
54681   if( pColumn ){
54682     for(i=0; i<pColumn->nId; i++){
54683       pColumn->a[i].idx = -1;
54684     }
54685     for(i=0; i<pColumn->nId; i++){
54686       for(j=0; j<pTab->nCol; j++){
54687         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
54688           pColumn->a[i].idx = j;
54689           if( j==pTab->iPKey ){
54690             keyColumn = i;
54691           }
54692           break;
54693         }
54694       }
54695       if( j>=pTab->nCol ){
54696         if( sqlite3IsRowid(pColumn->a[i].zName) ){
54697           keyColumn = i;
54698         }else{
54699           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
54700               pTabList, 0, pColumn->a[i].zName);
54701           pParse->nErr++;
54702           goto insert_cleanup;
54703         }
54704       }
54705     }
54706   }
54707
54708   /* If there is no IDLIST term but the table has an integer primary
54709   ** key, the set the keyColumn variable to the primary key column index
54710   ** in the original table definition.
54711   */
54712   if( pColumn==0 && nColumn>0 ){
54713     keyColumn = pTab->iPKey;
54714   }
54715
54716   /* Open the temp table for FOR EACH ROW triggers
54717   */
54718   if( triggers_exist ){
54719     sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
54720     sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
54721   }
54722     
54723   /* Initialize the count of rows to be inserted
54724   */
54725   if( db->flags & SQLITE_CountRows ){
54726     iCntMem = pParse->nMem++;
54727     sqlite3VdbeAddOp(v, OP_MemInt, 0, iCntMem);
54728   }
54729
54730   /* Open tables and indices if there are no row triggers */
54731   if( !triggers_exist ){
54732     base = pParse->nTab;
54733     sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
54734   }
54735
54736   /* If the data source is a temporary table, then we have to create
54737   ** a loop because there might be multiple rows of data.  If the data
54738   ** source is a subroutine call from the SELECT statement, then we need
54739   ** to launch the SELECT statement processing.
54740   */
54741   if( useTempTable ){
54742     iBreak = sqlite3VdbeMakeLabel(v);
54743     sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak);
54744     iCont = sqlite3VdbeCurrentAddr(v);
54745   }else if( pSelect ){
54746     sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
54747     sqlite3VdbeResolveLabel(v, iInsertBlock);
54748     sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0);
54749   }
54750
54751   /* Run the BEFORE and INSTEAD OF triggers, if there are any
54752   */
54753   endOfLoop = sqlite3VdbeMakeLabel(v);
54754   if( triggers_exist & TRIGGER_BEFORE ){
54755
54756     /* build the NEW.* reference row.  Note that if there is an INTEGER
54757     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
54758     ** translated into a unique ID for the row.  But on a BEFORE trigger,
54759     ** we do not know what the unique ID will be (because the insert has
54760     ** not happened yet) so we substitute a rowid of -1
54761     */
54762     if( keyColumn<0 ){
54763       sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
54764     }else if( useTempTable ){
54765       sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
54766     }else{
54767       assert( pSelect==0 );  /* Otherwise useTempTable is true */
54768       sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
54769       sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
54770       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
54771       sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
54772       sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
54773     }
54774
54775     /* Cannot have triggers on a virtual table. If it were possible,
54776     ** this block would have to account for hidden column.
54777     */
54778     assert(!IsVirtual(pTab));
54779
54780     /* Create the new column data
54781     */
54782     for(i=0; i<pTab->nCol; i++){
54783       if( pColumn==0 ){
54784         j = i;
54785       }else{
54786         for(j=0; j<pColumn->nId; j++){
54787           if( pColumn->a[j].idx==i ) break;
54788         }
54789       }
54790       if( pColumn && j>=pColumn->nId ){
54791         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
54792       }else if( useTempTable ){
54793         sqlite3VdbeAddOp(v, OP_Column, srcTab, j); 
54794       }else{
54795         assert( pSelect==0 ); /* Otherwise useTempTable is true */
54796         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
54797       }
54798     }
54799     sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
54800
54801     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
54802     ** do not attempt any conversions before assembling the record.
54803     ** If this is a real table, attempt conversions as required by the
54804     ** table column affinities.
54805     */
54806     if( !isView ){
54807       sqlite3TableAffinityStr(v, pTab);
54808     }
54809     sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
54810
54811     /* Fire BEFORE or INSTEAD OF triggers */
54812     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab, 
54813         newIdx, -1, onError, endOfLoop) ){
54814       goto insert_cleanup;
54815     }
54816   }
54817
54818   /* If any triggers exists, the opening of tables and indices is deferred
54819   ** until now.
54820   */
54821   if( triggers_exist && !isView ){
54822     base = pParse->nTab;
54823     sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
54824   }
54825
54826   /* Push the record number for the new entry onto the stack.  The
54827   ** record number is a randomly generate integer created by NewRowid
54828   ** except when the table has an INTEGER PRIMARY KEY column, in which
54829   ** case the record number is the same as that column. 
54830   */
54831   if( !isView ){
54832     if( IsVirtual(pTab) ){
54833       /* The row that the VUpdate opcode will delete:  none */
54834       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
54835     }
54836     if( keyColumn>=0 ){
54837       if( useTempTable ){
54838         sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
54839       }else if( pSelect ){
54840         sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
54841       }else{
54842         VdbeOp *pOp;
54843         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
54844         pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
54845         if( pOp && pOp->opcode==OP_Null ){
54846           appendFlag = 1;
54847           pOp->opcode = OP_NewRowid;
54848           pOp->p1 = base;
54849           pOp->p2 = counterMem;
54850         }
54851       }
54852       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
54853       ** to generate a unique primary key value.
54854       */
54855       if( !appendFlag ){
54856         sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
54857         sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
54858         sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
54859         sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
54860       }
54861     }else if( IsVirtual(pTab) ){
54862       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
54863     }else{
54864       sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
54865       appendFlag = 1;
54866     }
54867     autoIncStep(pParse, counterMem);
54868
54869     /* Push onto the stack, data for all columns of the new entry, beginning
54870     ** with the first column.
54871     */
54872     nHidden = 0;
54873     for(i=0; i<pTab->nCol; i++){
54874       if( i==pTab->iPKey ){
54875         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
54876         ** Whenever this column is read, the record number will be substituted
54877         ** in its place.  So will fill this column with a NULL to avoid
54878         ** taking up data space with information that will never be used. */
54879         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
54880         continue;
54881       }
54882       if( pColumn==0 ){
54883         if( IsHiddenColumn(&pTab->aCol[i]) ){
54884           assert( IsVirtual(pTab) );
54885           j = -1;
54886           nHidden++;
54887         }else{
54888           j = i - nHidden;
54889         }
54890       }else{
54891         for(j=0; j<pColumn->nId; j++){
54892           if( pColumn->a[j].idx==i ) break;
54893         }
54894       }
54895       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
54896         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
54897       }else if( useTempTable ){
54898         sqlite3VdbeAddOp(v, OP_Column, srcTab, j); 
54899       }else if( pSelect ){
54900         sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j+IsVirtual(pTab), 1);
54901       }else{
54902         sqlite3ExprCode(pParse, pList->a[j].pExpr);
54903       }
54904     }
54905
54906     /* Generate code to check constraints and generate index keys and
54907     ** do the insertion.
54908     */
54909 #ifndef SQLITE_OMIT_VIRTUALTABLE
54910     if( IsVirtual(pTab) ){
54911       pParse->pVirtualLock = pTab;
54912       sqlite3VdbeOp3(v, OP_VUpdate, 1, pTab->nCol+2,
54913                      (const char*)pTab->pVtab, P3_VTAB);
54914     }else
54915 #endif
54916     {
54917       sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
54918                                      0, onError, endOfLoop);
54919       sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
54920                             (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
54921                             appendFlag);
54922     }
54923   }
54924
54925   /* Update the count of rows that are inserted
54926   */
54927   if( (db->flags & SQLITE_CountRows)!=0 ){
54928     sqlite3VdbeAddOp(v, OP_MemIncr, 1, iCntMem);
54929   }
54930
54931   if( triggers_exist ){
54932     /* Close all tables opened */
54933     if( !isView ){
54934       sqlite3VdbeAddOp(v, OP_Close, base, 0);
54935       for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
54936         sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
54937       }
54938     }
54939
54940     /* Code AFTER triggers */
54941     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
54942           newIdx, -1, onError, endOfLoop) ){
54943       goto insert_cleanup;
54944     }
54945   }
54946
54947   /* The bottom of the loop, if the data source is a SELECT statement
54948   */
54949   sqlite3VdbeResolveLabel(v, endOfLoop);
54950   if( useTempTable ){
54951     sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont);
54952     sqlite3VdbeResolveLabel(v, iBreak);
54953     sqlite3VdbeAddOp(v, OP_Close, srcTab, 0);
54954   }else if( pSelect ){
54955     sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
54956     sqlite3VdbeAddOp(v, OP_Return, 0, 0);
54957     sqlite3VdbeResolveLabel(v, iCleanup);
54958   }
54959
54960   if( !triggers_exist && !IsVirtual(pTab) ){
54961     /* Close all tables opened */
54962     sqlite3VdbeAddOp(v, OP_Close, base, 0);
54963     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
54964       sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
54965     }
54966   }
54967
54968   /* Update the sqlite_sequence table by storing the content of the
54969   ** counter value in memory counterMem back into the sqlite_sequence
54970   ** table.
54971   */
54972   autoIncEnd(pParse, iDb, pTab, counterMem);
54973
54974   /*
54975   ** Return the number of rows inserted. If this routine is 
54976   ** generating code because of a call to sqlite3NestedParse(), do not
54977   ** invoke the callback function.
54978   */
54979   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
54980     sqlite3VdbeAddOp(v, OP_MemLoad, iCntMem, 0);
54981     sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
54982     sqlite3VdbeSetNumCols(v, 1);
54983     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P3_STATIC);
54984   }
54985
54986 insert_cleanup:
54987   sqlite3SrcListDelete(pTabList);
54988   sqlite3ExprListDelete(pList);
54989   sqlite3SelectDelete(pSelect);
54990   sqlite3IdListDelete(pColumn);
54991 }
54992
54993 /*
54994 ** Generate code to do a constraint check prior to an INSERT or an UPDATE.
54995 **
54996 ** When this routine is called, the stack contains (from bottom to top)
54997 ** the following values:
54998 **
54999 **    1.  The rowid of the row to be updated before the update.  This
55000 **        value is omitted unless we are doing an UPDATE that involves a
55001 **        change to the record number.
55002 **
55003 **    2.  The rowid of the row after the update.
55004 **
55005 **    3.  The data in the first column of the entry after the update.
55006 **
55007 **    i.  Data from middle columns...
55008 **
55009 **    N.  The data in the last column of the entry after the update.
55010 **
55011 ** The old rowid shown as entry (1) above is omitted unless both isUpdate
55012 ** and rowidChng are 1.  isUpdate is true for UPDATEs and false for
55013 ** INSERTs and rowidChng is true if the record number is being changed.
55014 **
55015 ** The code generated by this routine pushes additional entries onto
55016 ** the stack which are the keys for new index entries for the new record.
55017 ** The order of index keys is the same as the order of the indices on
55018 ** the pTable->pIndex list.  A key is only created for index i if 
55019 ** aIdxUsed!=0 and aIdxUsed[i]!=0.
55020 **
55021 ** This routine also generates code to check constraints.  NOT NULL,
55022 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
55023 ** then the appropriate action is performed.  There are five possible
55024 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
55025 **
55026 **  Constraint type  Action       What Happens
55027 **  ---------------  ----------   ----------------------------------------
55028 **  any              ROLLBACK     The current transaction is rolled back and
55029 **                                sqlite3_exec() returns immediately with a
55030 **                                return code of SQLITE_CONSTRAINT.
55031 **
55032 **  any              ABORT        Back out changes from the current command
55033 **                                only (do not do a complete rollback) then
55034 **                                cause sqlite3_exec() to return immediately
55035 **                                with SQLITE_CONSTRAINT.
55036 **
55037 **  any              FAIL         Sqlite_exec() returns immediately with a
55038 **                                return code of SQLITE_CONSTRAINT.  The
55039 **                                transaction is not rolled back and any
55040 **                                prior changes are retained.
55041 **
55042 **  any              IGNORE       The record number and data is popped from
55043 **                                the stack and there is an immediate jump
55044 **                                to label ignoreDest.
55045 **
55046 **  NOT NULL         REPLACE      The NULL value is replace by the default
55047 **                                value for that column.  If the default value
55048 **                                is NULL, the action is the same as ABORT.
55049 **
55050 **  UNIQUE           REPLACE      The other row that conflicts with the row
55051 **                                being inserted is removed.
55052 **
55053 **  CHECK            REPLACE      Illegal.  The results in an exception.
55054 **
55055 ** Which action to take is determined by the overrideError parameter.
55056 ** Or if overrideError==OE_Default, then the pParse->onError parameter
55057 ** is used.  Or if pParse->onError==OE_Default then the onError value
55058 ** for the constraint is used.
55059 **
55060 ** The calling routine must open a read/write cursor for pTab with
55061 ** cursor number "base".  All indices of pTab must also have open
55062 ** read/write cursors with cursor number base+i for the i-th cursor.
55063 ** Except, if there is no possibility of a REPLACE action then
55064 ** cursors do not need to be open for indices where aIdxUsed[i]==0.
55065 **
55066 ** If the isUpdate flag is true, it means that the "base" cursor is
55067 ** initially pointing to an entry that is being updated.  The isUpdate
55068 ** flag causes extra code to be generated so that the "base" cursor
55069 ** is still pointing at the same entry after the routine returns.
55070 ** Without the isUpdate flag, the "base" cursor might be moved.
55071 */
55072 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
55073   Parse *pParse,      /* The parser context */
55074   Table *pTab,        /* the table into which we are inserting */
55075   int base,           /* Index of a read/write cursor pointing at pTab */
55076   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
55077   int rowidChng,      /* True if the record number will change */
55078   int isUpdate,       /* True for UPDATE, False for INSERT */
55079   int overrideError,  /* Override onError to this if not OE_Default */
55080   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
55081 ){
55082   int i;
55083   Vdbe *v;
55084   int nCol;
55085   int onError;
55086   int addr;
55087   int extra;
55088   int iCur;
55089   Index *pIdx;
55090   int seenReplace = 0;
55091   int jumpInst1=0, jumpInst2;
55092   int hasTwoRowids = (isUpdate && rowidChng);
55093
55094   v = sqlite3GetVdbe(pParse);
55095   assert( v!=0 );
55096   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
55097   nCol = pTab->nCol;
55098
55099   /* Test all NOT NULL constraints.
55100   */
55101   for(i=0; i<nCol; i++){
55102     if( i==pTab->iPKey ){
55103       continue;
55104     }
55105     onError = pTab->aCol[i].notNull;
55106     if( onError==OE_None ) continue;
55107     if( overrideError!=OE_Default ){
55108       onError = overrideError;
55109     }else if( onError==OE_Default ){
55110       onError = OE_Abort;
55111     }
55112     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
55113       onError = OE_Abort;
55114     }
55115     sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1);
55116     addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0);
55117     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
55118         || onError==OE_Ignore || onError==OE_Replace );
55119     switch( onError ){
55120       case OE_Rollback:
55121       case OE_Abort:
55122       case OE_Fail: {
55123         char *zMsg = 0;
55124         sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
55125         sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
55126                         " may not be NULL", (char*)0);
55127         sqlite3VdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
55128         break;
55129       }
55130       case OE_Ignore: {
55131         sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
55132         sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
55133         break;
55134       }
55135       case OE_Replace: {
55136         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
55137         sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0);
55138         break;
55139       }
55140     }
55141     sqlite3VdbeJumpHere(v, addr);
55142   }
55143
55144   /* Test all CHECK constraints
55145   */
55146 #ifndef SQLITE_OMIT_CHECK
55147   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
55148     int allOk = sqlite3VdbeMakeLabel(v);
55149     assert( pParse->ckOffset==0 );
55150     pParse->ckOffset = nCol;
55151     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
55152     assert( pParse->ckOffset==nCol );
55153     pParse->ckOffset = 0;
55154     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
55155     if( onError==OE_Ignore ){
55156       sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
55157       sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
55158     }else{
55159       sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
55160     }
55161     sqlite3VdbeResolveLabel(v, allOk);
55162   }
55163 #endif /* !defined(SQLITE_OMIT_CHECK) */
55164
55165   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
55166   ** of the new record does not previously exist.  Except, if this
55167   ** is an UPDATE and the primary key is not changing, that is OK.
55168   */
55169   if( rowidChng ){
55170     onError = pTab->keyConf;
55171     if( overrideError!=OE_Default ){
55172       onError = overrideError;
55173     }else if( onError==OE_Default ){
55174       onError = OE_Abort;
55175     }
55176     
55177     if( isUpdate ){
55178       sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
55179       sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
55180       jumpInst1 = sqlite3VdbeAddOp(v, OP_Eq, 0, 0);
55181     }
55182     sqlite3VdbeAddOp(v, OP_Dup, nCol, 1);
55183     jumpInst2 = sqlite3VdbeAddOp(v, OP_NotExists, base, 0);
55184     switch( onError ){
55185       default: {
55186         onError = OE_Abort;
55187         /* Fall thru into the next case */
55188       }
55189       case OE_Rollback:
55190       case OE_Abort:
55191       case OE_Fail: {
55192         sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
55193                          "PRIMARY KEY must be unique", P3_STATIC);
55194         break;
55195       }
55196       case OE_Replace: {
55197         sqlite3GenerateRowIndexDelete(v, pTab, base, 0);
55198         if( isUpdate ){
55199           sqlite3VdbeAddOp(v, OP_Dup, nCol+hasTwoRowids, 1);
55200           sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
55201         }
55202         seenReplace = 1;
55203         break;
55204       }
55205       case OE_Ignore: {
55206         assert( seenReplace==0 );
55207         sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
55208         sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
55209         break;
55210       }
55211     }
55212     sqlite3VdbeJumpHere(v, jumpInst2);
55213     if( isUpdate ){
55214       sqlite3VdbeJumpHere(v, jumpInst1);
55215       sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
55216       sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
55217     }
55218   }
55219
55220   /* Test all UNIQUE constraints by creating entries for each UNIQUE
55221   ** index and making sure that duplicate entries do not already exist.
55222   ** Add the new records to the indices as we go.
55223   */
55224   extra = -1;
55225   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
55226     if( aIdxUsed && aIdxUsed[iCur]==0 ) continue;  /* Skip unused indices */
55227     extra++;
55228
55229     /* Create a key for accessing the index entry */
55230     sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1);
55231     for(i=0; i<pIdx->nColumn; i++){
55232       int idx = pIdx->aiColumn[i];
55233       if( idx==pTab->iPKey ){
55234         sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
55235       }else{
55236         sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
55237       }
55238     }
55239     jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
55240     sqlite3IndexAffinityStr(v, pIdx);
55241
55242     /* Find out what action to take in case there is an indexing conflict */
55243     onError = pIdx->onError;
55244     if( onError==OE_None ) continue;  /* pIdx is not a UNIQUE index */
55245     if( overrideError!=OE_Default ){
55246       onError = overrideError;
55247     }else if( onError==OE_Default ){
55248       onError = OE_Abort;
55249     }
55250     if( seenReplace ){
55251       if( onError==OE_Ignore ) onError = OE_Replace;
55252       else if( onError==OE_Fail ) onError = OE_Abort;
55253     }
55254     
55255
55256     /* Check to see if the new index entry will be unique */
55257     sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1);
55258     jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
55259
55260     /* Generate code that executes if the new index entry is not unique */
55261     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
55262         || onError==OE_Ignore || onError==OE_Replace );
55263     switch( onError ){
55264       case OE_Rollback:
55265       case OE_Abort:
55266       case OE_Fail: {
55267         int j, n1, n2;
55268         char zErrMsg[200];
55269         sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
55270                          pIdx->nColumn>1 ? "columns " : "column ");
55271         n1 = strlen(zErrMsg);
55272         for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
55273           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
55274           n2 = strlen(zCol);
55275           if( j>0 ){
55276             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
55277             n1 += 2;
55278           }
55279           if( n1+n2>sizeof(zErrMsg)-30 ){
55280             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
55281             n1 += 3;
55282             break;
55283           }else{
55284             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
55285             n1 += n2;
55286           }
55287         }
55288         sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], 
55289             pIdx->nColumn>1 ? " are not unique" : " is not unique");
55290         sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
55291         break;
55292       }
55293       case OE_Ignore: {
55294         assert( seenReplace==0 );
55295         sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0);
55296         sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
55297         break;
55298       }
55299       case OE_Replace: {
55300         sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0);
55301         if( isUpdate ){
55302           sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1);
55303           sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
55304         }
55305         seenReplace = 1;
55306         break;
55307       }
55308     }
55309 #if NULL_DISTINCT_FOR_UNIQUE
55310     sqlite3VdbeJumpHere(v, jumpInst1);
55311 #endif
55312     sqlite3VdbeJumpHere(v, jumpInst2);
55313   }
55314 }
55315
55316 /*
55317 ** This routine generates code to finish the INSERT or UPDATE operation
55318 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
55319 ** The stack must contain keys for all active indices followed by data
55320 ** and the rowid for the new entry.  This routine creates the new
55321 ** entries in all indices and in the main table.
55322 **
55323 ** The arguments to this routine should be the same as the first six
55324 ** arguments to sqlite3GenerateConstraintChecks.
55325 */
55326 SQLITE_PRIVATE void sqlite3CompleteInsertion(
55327   Parse *pParse,      /* The parser context */
55328   Table *pTab,        /* the table into which we are inserting */
55329   int base,           /* Index of a read/write cursor pointing at pTab */
55330   char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
55331   int rowidChng,      /* True if the record number will change */
55332   int isUpdate,       /* True for UPDATE, False for INSERT */
55333   int newIdx,         /* Index of NEW table for triggers.  -1 if none */
55334   int appendBias      /* True if this is likely to be an append */
55335 ){
55336   int i;
55337   Vdbe *v;
55338   int nIdx;
55339   Index *pIdx;
55340   int pik_flags;
55341
55342   v = sqlite3GetVdbe(pParse);
55343   assert( v!=0 );
55344   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
55345   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
55346   for(i=nIdx-1; i>=0; i--){
55347     if( aIdxUsed && aIdxUsed[i]==0 ) continue;
55348     sqlite3VdbeAddOp(v, OP_IdxInsert, base+i+1, 0);
55349   }
55350   sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
55351   sqlite3TableAffinityStr(v, pTab);
55352 #ifndef SQLITE_OMIT_TRIGGER
55353   if( newIdx>=0 ){
55354     sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
55355     sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
55356     sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
55357   }
55358 #endif
55359   if( pParse->nested ){
55360     pik_flags = 0;
55361   }else{
55362     pik_flags = OPFLAG_NCHANGE;
55363     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
55364   }
55365   if( appendBias ){
55366     pik_flags |= OPFLAG_APPEND;
55367   }
55368   sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags);
55369   if( !pParse->nested ){
55370     sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
55371   }
55372   
55373   if( isUpdate && rowidChng ){
55374     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
55375   }
55376 }
55377
55378 /*
55379 ** Generate code that will open cursors for a table and for all
55380 ** indices of that table.  The "base" parameter is the cursor number used
55381 ** for the table.  Indices are opened on subsequent cursors.
55382 */
55383 SQLITE_PRIVATE void sqlite3OpenTableAndIndices(
55384   Parse *pParse,   /* Parsing context */
55385   Table *pTab,     /* Table to be opened */
55386   int base,        /* Cursor number assigned to the table */
55387   int op           /* OP_OpenRead or OP_OpenWrite */
55388 ){
55389   int i;
55390   int iDb;
55391   Index *pIdx;
55392   Vdbe *v;
55393
55394   if( IsVirtual(pTab) ) return;
55395   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
55396   v = sqlite3GetVdbe(pParse);
55397   assert( v!=0 );
55398   sqlite3OpenTable(pParse, base, iDb, pTab, op);
55399   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
55400     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
55401     assert( pIdx->pSchema==pTab->pSchema );
55402     sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
55403     VdbeComment((v, "# %s", pIdx->zName));
55404     sqlite3VdbeOp3(v, op, i+base, pIdx->tnum, (char*)pKey, P3_KEYINFO_HANDOFF);
55405   }
55406   if( pParse->nTab<=base+i ){
55407     pParse->nTab = base+i;
55408   }
55409 }
55410
55411
55412 #ifdef SQLITE_TEST
55413 /*
55414 ** The following global variable is incremented whenever the
55415 ** transfer optimization is used.  This is used for testing
55416 ** purposes only - to make sure the transfer optimization really
55417 ** is happening when it is suppose to.
55418 */
55419 SQLITE_API int sqlite3_xferopt_count;
55420 #endif /* SQLITE_TEST */
55421
55422
55423 #ifndef SQLITE_OMIT_XFER_OPT
55424 /*
55425 ** Check to collation names to see if they are compatible.
55426 */
55427 static int xferCompatibleCollation(const char *z1, const char *z2){
55428   if( z1==0 ){
55429     return z2==0;
55430   }
55431   if( z2==0 ){
55432     return 0;
55433   }
55434   return sqlite3StrICmp(z1, z2)==0;
55435 }
55436
55437
55438 /*
55439 ** Check to see if index pSrc is compatible as a source of data
55440 ** for index pDest in an insert transfer optimization.  The rules
55441 ** for a compatible index:
55442 **
55443 **    *   The index is over the same set of columns
55444 **    *   The same DESC and ASC markings occurs on all columns
55445 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
55446 **    *   The same collating sequence on each column
55447 */
55448 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
55449   int i;
55450   assert( pDest && pSrc );
55451   assert( pDest->pTable!=pSrc->pTable );
55452   if( pDest->nColumn!=pSrc->nColumn ){
55453     return 0;   /* Different number of columns */
55454   }
55455   if( pDest->onError!=pSrc->onError ){
55456     return 0;   /* Different conflict resolution strategies */
55457   }
55458   for(i=0; i<pSrc->nColumn; i++){
55459     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
55460       return 0;   /* Different columns indexed */
55461     }
55462     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
55463       return 0;   /* Different sort orders */
55464     }
55465     if( pSrc->azColl[i]!=pDest->azColl[i] ){
55466       return 0;   /* Different sort orders */
55467     }
55468   }
55469
55470   /* If no test above fails then the indices must be compatible */
55471   return 1;
55472 }
55473
55474 /*
55475 ** Attempt the transfer optimization on INSERTs of the form
55476 **
55477 **     INSERT INTO tab1 SELECT * FROM tab2;
55478 **
55479 ** This optimization is only attempted if
55480 **
55481 **    (1)  tab1 and tab2 have identical schemas including all the
55482 **         same indices and constraints
55483 **
55484 **    (2)  tab1 and tab2 are different tables
55485 **
55486 **    (3)  There must be no triggers on tab1
55487 **
55488 **    (4)  The result set of the SELECT statement is "*"
55489 **
55490 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
55491 **         or LIMIT clause.
55492 **
55493 **    (6)  The SELECT statement is a simple (not a compound) select that
55494 **         contains only tab2 in its FROM clause
55495 **
55496 ** This method for implementing the INSERT transfers raw records from
55497 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
55498 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
55499 ** the resulting tab1 has much less fragmentation.
55500 **
55501 ** This routine returns TRUE if the optimization is attempted.  If any
55502 ** of the conditions above fail so that the optimization should not
55503 ** be attempted, then this routine returns FALSE.
55504 */
55505 static int xferOptimization(
55506   Parse *pParse,        /* Parser context */
55507   Table *pDest,         /* The table we are inserting into */
55508   Select *pSelect,      /* A SELECT statement to use as the data source */
55509   int onError,          /* How to handle constraint errors */
55510   int iDbDest           /* The database of pDest */
55511 ){
55512   ExprList *pEList;                /* The result set of the SELECT */
55513   Table *pSrc;                     /* The table in the FROM clause of SELECT */
55514   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
55515   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
55516   int i;                           /* Loop counter */
55517   int iDbSrc;                      /* The database of pSrc */
55518   int iSrc, iDest;                 /* Cursors from source and destination */
55519   int addr1, addr2;                /* Loop addresses */
55520   int emptyDestTest;               /* Address of test for empty pDest */
55521   int emptySrcTest;                /* Address of test for empty pSrc */
55522   Vdbe *v;                         /* The VDBE we are building */
55523   KeyInfo *pKey;                   /* Key information for an index */
55524   int counterMem;                  /* Memory register used by AUTOINC */
55525   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
55526
55527   if( pSelect==0 ){
55528     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
55529   }
55530   if( pDest->pTrigger ){
55531     return 0;   /* tab1 must not have triggers */
55532   }
55533 #ifndef SQLITE_OMIT_VIRTUALTABLE
55534   if( pDest->isVirtual ){
55535     return 0;   /* tab1 must not be a virtual table */
55536   }
55537 #endif
55538   if( onError==OE_Default ){
55539     onError = OE_Abort;
55540   }
55541   if( onError!=OE_Abort && onError!=OE_Rollback ){
55542     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
55543   }
55544   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
55545   if( pSelect->pSrc->nSrc!=1 ){
55546     return 0;   /* FROM clause must have exactly one term */
55547   }
55548   if( pSelect->pSrc->a[0].pSelect ){
55549     return 0;   /* FROM clause cannot contain a subquery */
55550   }
55551   if( pSelect->pWhere ){
55552     return 0;   /* SELECT may not have a WHERE clause */
55553   }
55554   if( pSelect->pOrderBy ){
55555     return 0;   /* SELECT may not have an ORDER BY clause */
55556   }
55557   /* Do not need to test for a HAVING clause.  If HAVING is present but
55558   ** there is no ORDER BY, we will get an error. */
55559   if( pSelect->pGroupBy ){
55560     return 0;   /* SELECT may not have a GROUP BY clause */
55561   }
55562   if( pSelect->pLimit ){
55563     return 0;   /* SELECT may not have a LIMIT clause */
55564   }
55565   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
55566   if( pSelect->pPrior ){
55567     return 0;   /* SELECT may not be a compound query */
55568   }
55569   if( pSelect->isDistinct ){
55570     return 0;   /* SELECT may not be DISTINCT */
55571   }
55572   pEList = pSelect->pEList;
55573   assert( pEList!=0 );
55574   if( pEList->nExpr!=1 ){
55575     return 0;   /* The result set must have exactly one column */
55576   }
55577   assert( pEList->a[0].pExpr );
55578   if( pEList->a[0].pExpr->op!=TK_ALL ){
55579     return 0;   /* The result set must be the special operator "*" */
55580   }
55581
55582   /* At this point we have established that the statement is of the
55583   ** correct syntactic form to participate in this optimization.  Now
55584   ** we have to check the semantics.
55585   */
55586   pItem = pSelect->pSrc->a;
55587   pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
55588   if( pSrc==0 ){
55589     return 0;   /* FROM clause does not contain a real table */
55590   }
55591   if( pSrc==pDest ){
55592     return 0;   /* tab1 and tab2 may not be the same table */
55593   }
55594 #ifndef SQLITE_OMIT_VIRTUALTABLE
55595   if( pSrc->isVirtual ){
55596     return 0;   /* tab2 must not be a virtual table */
55597   }
55598 #endif
55599   if( pSrc->pSelect ){
55600     return 0;   /* tab2 may not be a view */
55601   }
55602   if( pDest->nCol!=pSrc->nCol ){
55603     return 0;   /* Number of columns must be the same in tab1 and tab2 */
55604   }
55605   if( pDest->iPKey!=pSrc->iPKey ){
55606     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
55607   }
55608   for(i=0; i<pDest->nCol; i++){
55609     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
55610       return 0;    /* Affinity must be the same on all columns */
55611     }
55612     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
55613       return 0;    /* Collating sequence must be the same on all columns */
55614     }
55615     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
55616       return 0;    /* tab2 must be NOT NULL if tab1 is */
55617     }
55618   }
55619   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
55620     if( pDestIdx->onError!=OE_None ){
55621       destHasUniqueIdx = 1;
55622     }
55623     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
55624       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
55625     }
55626     if( pSrcIdx==0 ){
55627       return 0;    /* pDestIdx has no corresponding index in pSrc */
55628     }
55629   }
55630 #ifndef SQLITE_OMIT_CHECK
55631   if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
55632     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
55633   }
55634 #endif
55635
55636   /* If we get this far, it means either:
55637   **
55638   **    *   We can always do the transfer if the table contains an
55639   **        an integer primary key
55640   **
55641   **    *   We can conditionally do the transfer if the destination
55642   **        table is empty.
55643   */
55644 #ifdef SQLITE_TEST
55645   sqlite3_xferopt_count++;
55646 #endif
55647   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
55648   v = sqlite3GetVdbe(pParse);
55649   sqlite3CodeVerifySchema(pParse, iDbSrc);
55650   iSrc = pParse->nTab++;
55651   iDest = pParse->nTab++;
55652   counterMem = autoIncBegin(pParse, iDbDest, pDest);
55653   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
55654   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
55655     /* If tables do not have an INTEGER PRIMARY KEY and there
55656     ** are indices to be copied and the destination is not empty,
55657     ** we have to disallow the transfer optimization because the
55658     ** the rowids might change which will mess up indexing.
55659     **
55660     ** Or if the destination has a UNIQUE index and is not empty,
55661     ** we also disallow the transfer optimization because we cannot
55662     ** insure that all entries in the union of DEST and SRC will be
55663     ** unique.
55664     */
55665     addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iDest, 0);
55666     emptyDestTest = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
55667     sqlite3VdbeJumpHere(v, addr1);
55668   }else{
55669     emptyDestTest = 0;
55670   }
55671   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
55672   emptySrcTest = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
55673   if( pDest->iPKey>=0 ){
55674     addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
55675     sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
55676     addr2 = sqlite3VdbeAddOp(v, OP_NotExists, iDest, 0);
55677     sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, 
55678                       "PRIMARY KEY must be unique", P3_STATIC);
55679     sqlite3VdbeJumpHere(v, addr2);
55680     autoIncStep(pParse, counterMem);
55681   }else if( pDest->pIndex==0 ){
55682     addr1 = sqlite3VdbeAddOp(v, OP_NewRowid, iDest, 0);
55683   }else{
55684     addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
55685     assert( pDest->autoInc==0 );
55686   }
55687   sqlite3VdbeAddOp(v, OP_RowData, iSrc, 0);
55688   sqlite3VdbeOp3(v, OP_Insert, iDest,
55689                     OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND,
55690                     pDest->zName, 0);
55691   sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1);
55692   autoIncEnd(pParse, iDbDest, pDest, counterMem);
55693   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
55694     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
55695       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
55696     }
55697     assert( pSrcIdx );
55698     sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
55699     sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
55700     sqlite3VdbeAddOp(v, OP_Integer, iDbSrc, 0);
55701     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
55702     VdbeComment((v, "# %s", pSrcIdx->zName));
55703     sqlite3VdbeOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, 
55704                    (char*)pKey, P3_KEYINFO_HANDOFF);
55705     sqlite3VdbeAddOp(v, OP_Integer, iDbDest, 0);
55706     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
55707     VdbeComment((v, "# %s", pDestIdx->zName));
55708     sqlite3VdbeOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, 
55709                    (char*)pKey, P3_KEYINFO_HANDOFF);
55710     addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
55711     sqlite3VdbeAddOp(v, OP_RowKey, iSrc, 0);
55712     sqlite3VdbeAddOp(v, OP_IdxInsert, iDest, 1);
55713     sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1+1);
55714     sqlite3VdbeJumpHere(v, addr1);
55715   }
55716   sqlite3VdbeJumpHere(v, emptySrcTest);
55717   sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
55718   sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
55719   if( emptyDestTest ){
55720     sqlite3VdbeAddOp(v, OP_Halt, SQLITE_OK, 0);
55721     sqlite3VdbeJumpHere(v, emptyDestTest);
55722     sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
55723     return 0;
55724   }else{
55725     return 1;
55726   }
55727 }
55728 #endif /* SQLITE_OMIT_XFER_OPT */
55729
55730 /************** End of insert.c **********************************************/
55731 /************** Begin file legacy.c ******************************************/
55732 /*
55733 ** 2001 September 15
55734 **
55735 ** The author disclaims copyright to this source code.  In place of
55736 ** a legal notice, here is a blessing:
55737 **
55738 **    May you do good and not evil.
55739 **    May you find forgiveness for yourself and forgive others.
55740 **    May you share freely, never taking more than you give.
55741 **
55742 *************************************************************************
55743 ** Main file for the SQLite library.  The routines in this file
55744 ** implement the programmer interface to the library.  Routines in
55745 ** other files are for internal use by SQLite and should not be
55746 ** accessed by users of the library.
55747 **
55748 ** $Id: legacy.c,v 1.22 2007/08/29 12:31:26 danielk1977 Exp $
55749 */
55750
55751
55752 /*
55753 ** Execute SQL code.  Return one of the SQLITE_ success/failure
55754 ** codes.  Also write an error message into memory obtained from
55755 ** malloc() and make *pzErrMsg point to that message.
55756 **
55757 ** If the SQL is a query, then for each row in the query result
55758 ** the xCallback() function is called.  pArg becomes the first
55759 ** argument to xCallback().  If xCallback=NULL then no callback
55760 ** is invoked, even for queries.
55761 */
55762 SQLITE_API int sqlite3_exec(
55763   sqlite3 *db,                /* The database on which the SQL executes */
55764   const char *zSql,           /* The SQL to be executed */
55765   sqlite3_callback xCallback, /* Invoke this callback routine */
55766   void *pArg,                 /* First argument to xCallback() */
55767   char **pzErrMsg             /* Write error messages here */
55768 ){
55769   int rc = SQLITE_OK;
55770   const char *zLeftover;
55771   sqlite3_stmt *pStmt = 0;
55772   char **azCols = 0;
55773
55774   int nRetry = 0;
55775   int nCallback;
55776
55777   if( zSql==0 ) return SQLITE_OK;
55778
55779   sqlite3_mutex_enter(db->mutex);
55780   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
55781     int nCol;
55782     char **azVals = 0;
55783
55784     pStmt = 0;
55785     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
55786     assert( rc==SQLITE_OK || pStmt==0 );
55787     if( rc!=SQLITE_OK ){
55788       continue;
55789     }
55790     if( !pStmt ){
55791       /* this happens for a comment or white-space */
55792       zSql = zLeftover;
55793       continue;
55794     }
55795
55796     nCallback = 0;
55797
55798     nCol = sqlite3_column_count(pStmt);
55799     azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char *) + 1);
55800     if( azCols==0 ){
55801       goto exec_out;
55802     }
55803
55804     while( 1 ){
55805       int i;
55806       rc = sqlite3_step(pStmt);
55807
55808       /* Invoke the callback function if required */
55809       if( xCallback && (SQLITE_ROW==rc || 
55810           (SQLITE_DONE==rc && !nCallback && db->flags&SQLITE_NullCallback)) ){
55811         if( 0==nCallback ){
55812           for(i=0; i<nCol; i++){
55813             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
55814           }
55815           nCallback++;
55816         }
55817         if( rc==SQLITE_ROW ){
55818           azVals = &azCols[nCol];
55819           for(i=0; i<nCol; i++){
55820             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
55821           }
55822         }
55823         if( xCallback(pArg, nCol, azVals, azCols) ){
55824           rc = SQLITE_ABORT;
55825           goto exec_out;
55826         }
55827       }
55828
55829       if( rc!=SQLITE_ROW ){
55830         rc = sqlite3_finalize(pStmt);
55831         pStmt = 0;
55832         if( rc!=SQLITE_SCHEMA ){
55833           nRetry = 0;
55834           zSql = zLeftover;
55835           while( isspace((unsigned char)zSql[0]) ) zSql++;
55836         }
55837         break;
55838       }
55839     }
55840
55841     sqlite3_free(azCols);
55842     azCols = 0;
55843   }
55844
55845 exec_out:
55846   if( pStmt ) sqlite3_finalize(pStmt);
55847   if( azCols ) sqlite3_free(azCols);
55848
55849   rc = sqlite3ApiExit(db, rc);
55850   if( rc!=SQLITE_OK && rc==sqlite3_errcode(db) && pzErrMsg ){
55851     int nErrMsg = 1 + strlen(sqlite3_errmsg(db));
55852     *pzErrMsg = sqlite3_malloc(nErrMsg);
55853     if( *pzErrMsg ){
55854       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
55855     }
55856   }else if( pzErrMsg ){
55857     *pzErrMsg = 0;
55858   }
55859
55860   assert( (rc&db->errMask)==rc );
55861   sqlite3_mutex_leave(db->mutex);
55862   return rc;
55863 }
55864
55865 /************** End of legacy.c **********************************************/
55866 /************** Begin file loadext.c *****************************************/
55867 /*
55868 ** 2006 June 7
55869 **
55870 ** The author disclaims copyright to this source code.  In place of
55871 ** a legal notice, here is a blessing:
55872 **
55873 **    May you do good and not evil.
55874 **    May you find forgiveness for yourself and forgive others.
55875 **    May you share freely, never taking more than you give.
55876 **
55877 *************************************************************************
55878 ** This file contains code used to dynamically load extensions into
55879 ** the SQLite library.
55880 */
55881 #ifndef SQLITE_OMIT_LOAD_EXTENSION
55882
55883 #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
55884 /************** Include sqlite3ext.h in the middle of loadext.c **************/
55885 /************** Begin file sqlite3ext.h **************************************/
55886 /*
55887 ** 2006 June 7
55888 **
55889 ** The author disclaims copyright to this source code.  In place of
55890 ** a legal notice, here is a blessing:
55891 **
55892 **    May you do good and not evil.
55893 **    May you find forgiveness for yourself and forgive others.
55894 **    May you share freely, never taking more than you give.
55895 **
55896 *************************************************************************
55897 ** This header file defines the SQLite interface for use by
55898 ** shared libraries that want to be imported as extensions into
55899 ** an SQLite instance.  Shared libraries that intend to be loaded
55900 ** as extensions by SQLite should #include this file instead of 
55901 ** sqlite3.h.
55902 **
55903 ** @(#) $Id: sqlite3ext.h,v 1.17 2007/08/31 16:11:36 drh Exp $
55904 */
55905 #ifndef _SQLITE3EXT_H_
55906 #define _SQLITE3EXT_H_
55907
55908 typedef struct sqlite3_api_routines sqlite3_api_routines;
55909
55910 /*
55911 ** The following structure hold pointers to all of the SQLite API
55912 ** routines.
55913 **
55914 ** WARNING:  In order to maintain backwards compatibility, add new
55915 ** interfaces to the end of this structure only.  If you insert new
55916 ** interfaces in the middle of this structure, then older different
55917 ** versions of SQLite will not be able to load each others shared
55918 ** libraries!
55919 */
55920 struct sqlite3_api_routines {
55921   void * (*aggregate_context)(sqlite3_context*,int nBytes);
55922   int  (*aggregate_count)(sqlite3_context*);
55923   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
55924   int  (*bind_double)(sqlite3_stmt*,int,double);
55925   int  (*bind_int)(sqlite3_stmt*,int,int);
55926   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
55927   int  (*bind_null)(sqlite3_stmt*,int);
55928   int  (*bind_parameter_count)(sqlite3_stmt*);
55929   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
55930   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
55931   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
55932   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
55933   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
55934   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
55935   int  (*busy_timeout)(sqlite3*,int ms);
55936   int  (*changes)(sqlite3*);
55937   int  (*close)(sqlite3*);
55938   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
55939   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
55940   const void * (*column_blob)(sqlite3_stmt*,int iCol);
55941   int  (*column_bytes)(sqlite3_stmt*,int iCol);
55942   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
55943   int  (*column_count)(sqlite3_stmt*pStmt);
55944   const char * (*column_database_name)(sqlite3_stmt*,int);
55945   const void * (*column_database_name16)(sqlite3_stmt*,int);
55946   const char * (*column_decltype)(sqlite3_stmt*,int i);
55947   const void * (*column_decltype16)(sqlite3_stmt*,int);
55948   double  (*column_double)(sqlite3_stmt*,int iCol);
55949   int  (*column_int)(sqlite3_stmt*,int iCol);
55950   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
55951   const char * (*column_name)(sqlite3_stmt*,int);
55952   const void * (*column_name16)(sqlite3_stmt*,int);
55953   const char * (*column_origin_name)(sqlite3_stmt*,int);
55954   const void * (*column_origin_name16)(sqlite3_stmt*,int);
55955   const char * (*column_table_name)(sqlite3_stmt*,int);
55956   const void * (*column_table_name16)(sqlite3_stmt*,int);
55957   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
55958   const void * (*column_text16)(sqlite3_stmt*,int iCol);
55959   int  (*column_type)(sqlite3_stmt*,int iCol);
55960   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
55961   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
55962   int  (*complete)(const char*sql);
55963   int  (*complete16)(const void*sql);
55964   int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
55965   int  (*create_collation16)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
55966   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*));
55967   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*));
55968   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
55969   int  (*data_count)(sqlite3_stmt*pStmt);
55970   sqlite3 * (*db_handle)(sqlite3_stmt*);
55971   int (*declare_vtab)(sqlite3*,const char*);
55972   int  (*enable_shared_cache)(int);
55973   int  (*errcode)(sqlite3*db);
55974   const char * (*errmsg)(sqlite3*);
55975   const void * (*errmsg16)(sqlite3*);
55976   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
55977   int  (*expired)(sqlite3_stmt*);
55978   int  (*finalize)(sqlite3_stmt*pStmt);
55979   void  (*free)(void*);
55980   void  (*free_table)(char**result);
55981   int  (*get_autocommit)(sqlite3*);
55982   void * (*get_auxdata)(sqlite3_context*,int);
55983   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
55984   int  (*global_recover)(void);
55985   void  (*interruptx)(sqlite3*);
55986   sqlite_int64  (*last_insert_rowid)(sqlite3*);
55987   const char * (*libversion)(void);
55988   int  (*libversion_number)(void);
55989   void *(*malloc)(int);
55990   char * (*mprintf)(const char*,...);
55991   int  (*open)(const char*,sqlite3**);
55992   int  (*open16)(const void*,sqlite3**);
55993   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
55994   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
55995   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
55996   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
55997   void *(*realloc)(void*,int);
55998   int  (*reset)(sqlite3_stmt*pStmt);
55999   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
56000   void  (*result_double)(sqlite3_context*,double);
56001   void  (*result_error)(sqlite3_context*,const char*,int);
56002   void  (*result_error16)(sqlite3_context*,const void*,int);
56003   void  (*result_int)(sqlite3_context*,int);
56004   void  (*result_int64)(sqlite3_context*,sqlite_int64);
56005   void  (*result_null)(sqlite3_context*);
56006   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
56007   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
56008   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
56009   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
56010   void  (*result_value)(sqlite3_context*,sqlite3_value*);
56011   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
56012   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
56013   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
56014   char * (*snprintf)(int,char*,const char*,...);
56015   int  (*step)(sqlite3_stmt*);
56016   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
56017   void  (*thread_cleanup)(void);
56018   int  (*total_changes)(sqlite3*);
56019   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
56020   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
56021   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
56022   void * (*user_data)(sqlite3_context*);
56023   const void * (*value_blob)(sqlite3_value*);
56024   int  (*value_bytes)(sqlite3_value*);
56025   int  (*value_bytes16)(sqlite3_value*);
56026   double  (*value_double)(sqlite3_value*);
56027   int  (*value_int)(sqlite3_value*);
56028   sqlite_int64  (*value_int64)(sqlite3_value*);
56029   int  (*value_numeric_type)(sqlite3_value*);
56030   const unsigned char * (*value_text)(sqlite3_value*);
56031   const void * (*value_text16)(sqlite3_value*);
56032   const void * (*value_text16be)(sqlite3_value*);
56033   const void * (*value_text16le)(sqlite3_value*);
56034   int  (*value_type)(sqlite3_value*);
56035   char *(*vmprintf)(const char*,va_list);
56036   /* Added ??? */
56037   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
56038   /* Added by 3.3.13 */
56039   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
56040   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
56041   int (*clear_bindings)(sqlite3_stmt*);
56042   /* Added by 3.4.1 */
56043   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
56044   /* Added by 3.5.0 */
56045   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
56046   int (*blob_bytes)(sqlite3_blob*);
56047   int (*blob_close)(sqlite3_blob*);
56048   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
56049   int (*blob_read)(sqlite3_blob*,void*,int,int);
56050   int (*blob_write)(sqlite3_blob*,const void*,int,int);
56051   int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
56052   int (*file_control)(sqlite3*,const char*,int,void*);
56053   sqlite3_int64 (*memory_highwater)(int);
56054   sqlite3_int64 (*memory_used)(void);
56055   sqlite3_mutex *(*mutex_alloc)(int);
56056   void (*mutex_enter)(sqlite3_mutex*);
56057   void (*mutex_free)(sqlite3_mutex*);
56058   void (*mutex_leave)(sqlite3_mutex*);
56059   int (*mutex_try)(sqlite3_mutex*);
56060   int (*open_v2)(const char*,sqlite3**,int,const char*);
56061   int (*release_memory)(int);
56062   void (*result_error_nomem)(sqlite3_context*);
56063   void (*result_error_toobig)(sqlite3_context*);
56064   int (*sleep)(int);
56065   void (*soft_heap_limit)(int);
56066   sqlite3_vfs *(*vfs_find)(const char*);
56067   int (*vfs_register)(sqlite3_vfs*,int);
56068   int (*vfs_unregister)(sqlite3_vfs*);
56069 };
56070
56071 /*
56072 ** The following macros redefine the API routines so that they are
56073 ** redirected throught the global sqlite3_api structure.
56074 **
56075 ** This header file is also used by the loadext.c source file
56076 ** (part of the main SQLite library - not an extension) so that
56077 ** it can get access to the sqlite3_api_routines structure
56078 ** definition.  But the main library does not want to redefine
56079 ** the API.  So the redefinition macros are only valid if the
56080 ** SQLITE_CORE macros is undefined.
56081 */
56082 #ifndef SQLITE_CORE
56083 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
56084 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
56085 #define sqlite3_bind_blob              sqlite3_api->bind_blob
56086 #define sqlite3_bind_double            sqlite3_api->bind_double
56087 #define sqlite3_bind_int               sqlite3_api->bind_int
56088 #define sqlite3_bind_int64             sqlite3_api->bind_int64
56089 #define sqlite3_bind_null              sqlite3_api->bind_null
56090 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
56091 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
56092 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
56093 #define sqlite3_bind_text              sqlite3_api->bind_text
56094 #define sqlite3_bind_text16            sqlite3_api->bind_text16
56095 #define sqlite3_bind_value             sqlite3_api->bind_value
56096 #define sqlite3_busy_handler           sqlite3_api->busy_handler
56097 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
56098 #define sqlite3_changes                sqlite3_api->changes
56099 #define sqlite3_close                  sqlite3_api->close
56100 #define sqlite3_collation_needed       sqlite3_api->collation_needed
56101 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
56102 #define sqlite3_column_blob            sqlite3_api->column_blob
56103 #define sqlite3_column_bytes           sqlite3_api->column_bytes
56104 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
56105 #define sqlite3_column_count           sqlite3_api->column_count
56106 #define sqlite3_column_database_name   sqlite3_api->column_database_name
56107 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
56108 #define sqlite3_column_decltype        sqlite3_api->column_decltype
56109 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
56110 #define sqlite3_column_double          sqlite3_api->column_double
56111 #define sqlite3_column_int             sqlite3_api->column_int
56112 #define sqlite3_column_int64           sqlite3_api->column_int64
56113 #define sqlite3_column_name            sqlite3_api->column_name
56114 #define sqlite3_column_name16          sqlite3_api->column_name16
56115 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
56116 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
56117 #define sqlite3_column_table_name      sqlite3_api->column_table_name
56118 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
56119 #define sqlite3_column_text            sqlite3_api->column_text
56120 #define sqlite3_column_text16          sqlite3_api->column_text16
56121 #define sqlite3_column_type            sqlite3_api->column_type
56122 #define sqlite3_column_value           sqlite3_api->column_value
56123 #define sqlite3_commit_hook            sqlite3_api->commit_hook
56124 #define sqlite3_complete               sqlite3_api->complete
56125 #define sqlite3_complete16             sqlite3_api->complete16
56126 #define sqlite3_create_collation       sqlite3_api->create_collation
56127 #define sqlite3_create_collation16     sqlite3_api->create_collation16
56128 #define sqlite3_create_function        sqlite3_api->create_function
56129 #define sqlite3_create_function16      sqlite3_api->create_function16
56130 #define sqlite3_create_module          sqlite3_api->create_module
56131 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
56132 #define sqlite3_data_count             sqlite3_api->data_count
56133 #define sqlite3_db_handle              sqlite3_api->db_handle
56134 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
56135 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
56136 #define sqlite3_errcode                sqlite3_api->errcode
56137 #define sqlite3_errmsg                 sqlite3_api->errmsg
56138 #define sqlite3_errmsg16               sqlite3_api->errmsg16
56139 #define sqlite3_exec                   sqlite3_api->exec
56140 #define sqlite3_expired                sqlite3_api->expired
56141 #define sqlite3_finalize               sqlite3_api->finalize
56142 #define sqlite3_free                   sqlite3_api->free
56143 #define sqlite3_free_table             sqlite3_api->free_table
56144 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
56145 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
56146 #define sqlite3_get_table              sqlite3_api->get_table
56147 #define sqlite3_global_recover         sqlite3_api->global_recover
56148 #define sqlite3_interrupt              sqlite3_api->interruptx
56149 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
56150 #define sqlite3_libversion             sqlite3_api->libversion
56151 #define sqlite3_libversion_number      sqlite3_api->libversion_number
56152 #define sqlite3_malloc                 sqlite3_api->malloc
56153 #define sqlite3_mprintf                sqlite3_api->mprintf
56154 #define sqlite3_open                   sqlite3_api->open
56155 #define sqlite3_open16                 sqlite3_api->open16
56156 #define sqlite3_prepare                sqlite3_api->prepare
56157 #define sqlite3_prepare16              sqlite3_api->prepare16
56158 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
56159 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
56160 #define sqlite3_profile                sqlite3_api->profile
56161 #define sqlite3_progress_handler       sqlite3_api->progress_handler
56162 #define sqlite3_realloc                sqlite3_api->realloc
56163 #define sqlite3_reset                  sqlite3_api->reset
56164 #define sqlite3_result_blob            sqlite3_api->result_blob
56165 #define sqlite3_result_double          sqlite3_api->result_double
56166 #define sqlite3_result_error           sqlite3_api->result_error
56167 #define sqlite3_result_error16         sqlite3_api->result_error16
56168 #define sqlite3_result_int             sqlite3_api->result_int
56169 #define sqlite3_result_int64           sqlite3_api->result_int64
56170 #define sqlite3_result_null            sqlite3_api->result_null
56171 #define sqlite3_result_text            sqlite3_api->result_text
56172 #define sqlite3_result_text16          sqlite3_api->result_text16
56173 #define sqlite3_result_text16be        sqlite3_api->result_text16be
56174 #define sqlite3_result_text16le        sqlite3_api->result_text16le
56175 #define sqlite3_result_value           sqlite3_api->result_value
56176 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
56177 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
56178 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
56179 #define sqlite3_snprintf               sqlite3_api->snprintf
56180 #define sqlite3_step                   sqlite3_api->step
56181 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
56182 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
56183 #define sqlite3_total_changes          sqlite3_api->total_changes
56184 #define sqlite3_trace                  sqlite3_api->trace
56185 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
56186 #define sqlite3_update_hook            sqlite3_api->update_hook
56187 #define sqlite3_user_data              sqlite3_api->user_data
56188 #define sqlite3_value_blob             sqlite3_api->value_blob
56189 #define sqlite3_value_bytes            sqlite3_api->value_bytes
56190 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
56191 #define sqlite3_value_double           sqlite3_api->value_double
56192 #define sqlite3_value_int              sqlite3_api->value_int
56193 #define sqlite3_value_int64            sqlite3_api->value_int64
56194 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
56195 #define sqlite3_value_text             sqlite3_api->value_text
56196 #define sqlite3_value_text16           sqlite3_api->value_text16
56197 #define sqlite3_value_text16be         sqlite3_api->value_text16be
56198 #define sqlite3_value_text16le         sqlite3_api->value_text16le
56199 #define sqlite3_value_type             sqlite3_api->value_type
56200 #define sqlite3_vmprintf               sqlite3_api->vmprintf
56201 #define sqlite3_overload_function      sqlite3_api->overload_function
56202 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
56203 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
56204 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
56205 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
56206 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
56207 #define sqlite3_blob_close             sqlite3_api->blob_close
56208 #define sqlite3_blob_open              sqlite3_api->blob_open
56209 #define sqlite3_blob_read              sqlite3_api->blob_read
56210 #define sqlite3_blob_write             sqlite3_api->blob_write
56211 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
56212 #define sqlite3_file_control           sqlite3_api->file_control
56213 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
56214 #define sqlite3_memory_used            sqlite3_api->memory_used
56215 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
56216 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
56217 #define sqlite3_mutex_free             sqlite3_api->mutex_free
56218 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
56219 #define sqlite3_mutex_try              sqlite3_api->mutex_try
56220 #define sqlite3_open_v2                sqlite3_api->open_v2
56221 #define sqlite3_release_memory         sqlite3_api->release_memory
56222 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
56223 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
56224 #define sqlite3_sleep                  sqlite3_api->sleep
56225 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
56226 #define sqlite3_vfs_find               sqlite3_api->vfs_find
56227 #define sqlite3_vfs_register           sqlite3_api->vfs_register
56228 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
56229 #endif /* SQLITE_CORE */
56230
56231 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api;
56232 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
56233
56234 #endif /* _SQLITE3EXT_H_ */
56235
56236 /************** End of sqlite3ext.h ******************************************/
56237 /************** Continuing where we left off in loadext.c ********************/
56238
56239 /*
56240 ** Some API routines are omitted when various features are
56241 ** excluded from a build of SQLite.  Substitute a NULL pointer
56242 ** for any missing APIs.
56243 */
56244 #ifndef SQLITE_ENABLE_COLUMN_METADATA
56245 # define sqlite3_column_database_name   0
56246 # define sqlite3_column_database_name16 0
56247 # define sqlite3_column_table_name      0
56248 # define sqlite3_column_table_name16    0
56249 # define sqlite3_column_origin_name     0
56250 # define sqlite3_column_origin_name16   0
56251 # define sqlite3_table_column_metadata  0
56252 #endif
56253
56254 #ifdef SQLITE_OMIT_AUTHORIZATION
56255 # define sqlite3_set_authorizer         0
56256 #endif
56257
56258 #ifdef SQLITE_OMIT_UTF16
56259 # define sqlite3_bind_text16            0
56260 # define sqlite3_collation_needed16     0
56261 # define sqlite3_column_decltype16      0
56262 # define sqlite3_column_name16          0
56263 # define sqlite3_column_text16          0
56264 # define sqlite3_complete16             0
56265 # define sqlite3_create_collation16     0
56266 # define sqlite3_create_function16      0
56267 # define sqlite3_errmsg16               0
56268 # define sqlite3_open16                 0
56269 # define sqlite3_prepare16              0
56270 # define sqlite3_prepare16_v2           0
56271 # define sqlite3_result_error16         0
56272 # define sqlite3_result_text16          0
56273 # define sqlite3_result_text16be        0
56274 # define sqlite3_result_text16le        0
56275 # define sqlite3_value_text16           0
56276 # define sqlite3_value_text16be         0
56277 # define sqlite3_value_text16le         0
56278 # define sqlite3_column_database_name16 0
56279 # define sqlite3_column_table_name16    0
56280 # define sqlite3_column_origin_name16   0
56281 #endif
56282
56283 #ifdef SQLITE_OMIT_COMPLETE
56284 # define sqlite3_complete 0
56285 # define sqlite3_complete16 0
56286 #endif
56287
56288 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
56289 # define sqlite3_progress_handler 0
56290 #endif
56291
56292 #ifdef SQLITE_OMIT_VIRTUALTABLE
56293 # define sqlite3_create_module 0
56294 # define sqlite3_create_module_v2 0
56295 # define sqlite3_declare_vtab 0
56296 #endif
56297
56298 #ifdef SQLITE_OMIT_SHARED_CACHE
56299 # define sqlite3_enable_shared_cache 0
56300 #endif
56301
56302 #ifdef SQLITE_OMIT_TRACE
56303 # define sqlite3_profile       0
56304 # define sqlite3_trace         0
56305 #endif
56306
56307 #ifdef SQLITE_OMIT_GET_TABLE
56308 # define sqlite3_free_table    0
56309 # define sqlite3_get_table     0
56310 #endif
56311
56312 #ifdef SQLITE_OMIT_INCRBLOB
56313 #define sqlite3_bind_zeroblob  0
56314 #define sqlite3_blob_bytes     0
56315 #define sqlite3_blob_close     0
56316 #define sqlite3_blob_open      0
56317 #define sqlite3_blob_read      0
56318 #define sqlite3_blob_write     0
56319 #endif
56320
56321 /*
56322 ** The following structure contains pointers to all SQLite API routines.
56323 ** A pointer to this structure is passed into extensions when they are
56324 ** loaded so that the extension can make calls back into the SQLite
56325 ** library.
56326 **
56327 ** When adding new APIs, add them to the bottom of this structure
56328 ** in order to preserve backwards compatibility.
56329 **
56330 ** Extensions that use newer APIs should first call the
56331 ** sqlite3_libversion_number() to make sure that the API they
56332 ** intend to use is supported by the library.  Extensions should
56333 ** also check to make sure that the pointer to the function is
56334 ** not NULL before calling it.
56335 */
56336 SQLITE_API const sqlite3_api_routines sqlite3_apis = {
56337   sqlite3_aggregate_context,
56338   sqlite3_aggregate_count,
56339   sqlite3_bind_blob,
56340   sqlite3_bind_double,
56341   sqlite3_bind_int,
56342   sqlite3_bind_int64,
56343   sqlite3_bind_null,
56344   sqlite3_bind_parameter_count,
56345   sqlite3_bind_parameter_index,
56346   sqlite3_bind_parameter_name,
56347   sqlite3_bind_text,
56348   sqlite3_bind_text16,
56349   sqlite3_bind_value,
56350   sqlite3_busy_handler,
56351   sqlite3_busy_timeout,
56352   sqlite3_changes,
56353   sqlite3_close,
56354   sqlite3_collation_needed,
56355   sqlite3_collation_needed16,
56356   sqlite3_column_blob,
56357   sqlite3_column_bytes,
56358   sqlite3_column_bytes16,
56359   sqlite3_column_count,
56360   sqlite3_column_database_name,
56361   sqlite3_column_database_name16,
56362   sqlite3_column_decltype,
56363   sqlite3_column_decltype16,
56364   sqlite3_column_double,
56365   sqlite3_column_int,
56366   sqlite3_column_int64,
56367   sqlite3_column_name,
56368   sqlite3_column_name16,
56369   sqlite3_column_origin_name,
56370   sqlite3_column_origin_name16,
56371   sqlite3_column_table_name,
56372   sqlite3_column_table_name16,
56373   sqlite3_column_text,
56374   sqlite3_column_text16,
56375   sqlite3_column_type,
56376   sqlite3_column_value,
56377   sqlite3_commit_hook,
56378   sqlite3_complete,
56379   sqlite3_complete16,
56380   sqlite3_create_collation,
56381   sqlite3_create_collation16,
56382   sqlite3_create_function,
56383   sqlite3_create_function16,
56384   sqlite3_create_module,
56385   sqlite3_data_count,
56386   sqlite3_db_handle,
56387   sqlite3_declare_vtab,
56388   sqlite3_enable_shared_cache,
56389   sqlite3_errcode,
56390   sqlite3_errmsg,
56391   sqlite3_errmsg16,
56392   sqlite3_exec,
56393   sqlite3_expired,
56394   sqlite3_finalize,
56395   sqlite3_free,
56396   sqlite3_free_table,
56397   sqlite3_get_autocommit,
56398   sqlite3_get_auxdata,
56399   sqlite3_get_table,
56400   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
56401   sqlite3_interrupt,
56402   sqlite3_last_insert_rowid,
56403   sqlite3_libversion,
56404   sqlite3_libversion_number,
56405   sqlite3_malloc,
56406   sqlite3_mprintf,
56407   sqlite3_open,
56408   sqlite3_open16,
56409   sqlite3_prepare,
56410   sqlite3_prepare16,
56411   sqlite3_profile,
56412   sqlite3_progress_handler,
56413   sqlite3_realloc,
56414   sqlite3_reset,
56415   sqlite3_result_blob,
56416   sqlite3_result_double,
56417   sqlite3_result_error,
56418   sqlite3_result_error16,
56419   sqlite3_result_int,
56420   sqlite3_result_int64,
56421   sqlite3_result_null,
56422   sqlite3_result_text,
56423   sqlite3_result_text16,
56424   sqlite3_result_text16be,
56425   sqlite3_result_text16le,
56426   sqlite3_result_value,
56427   sqlite3_rollback_hook,
56428   sqlite3_set_authorizer,
56429   sqlite3_set_auxdata,
56430   sqlite3_snprintf,
56431   sqlite3_step,
56432   sqlite3_table_column_metadata,
56433   sqlite3_thread_cleanup,
56434   sqlite3_total_changes,
56435   sqlite3_trace,
56436   sqlite3_transfer_bindings,
56437   sqlite3_update_hook,
56438   sqlite3_user_data,
56439   sqlite3_value_blob,
56440   sqlite3_value_bytes,
56441   sqlite3_value_bytes16,
56442   sqlite3_value_double,
56443   sqlite3_value_int,
56444   sqlite3_value_int64,
56445   sqlite3_value_numeric_type,
56446   sqlite3_value_text,
56447   sqlite3_value_text16,
56448   sqlite3_value_text16be,
56449   sqlite3_value_text16le,
56450   sqlite3_value_type,
56451   sqlite3_vmprintf,
56452   /*
56453   ** The original API set ends here.  All extensions can call any
56454   ** of the APIs above provided that the pointer is not NULL.  But
56455   ** before calling APIs that follow, extension should check the
56456   ** sqlite3_libversion_number() to make sure they are dealing with
56457   ** a library that is new enough to support that API.
56458   *************************************************************************
56459   */
56460   sqlite3_overload_function,
56461
56462   /*
56463   ** Added after 3.3.13
56464   */
56465   sqlite3_prepare_v2,
56466   sqlite3_prepare16_v2,
56467   sqlite3_clear_bindings,
56468
56469   /*
56470   ** Added for 3.4.1
56471   */
56472   sqlite3_create_module_v2,
56473
56474   /*
56475   ** Added for 3.5.0
56476   */
56477   sqlite3_bind_zeroblob,
56478   sqlite3_blob_bytes,
56479   sqlite3_blob_close,
56480   sqlite3_blob_open,
56481   sqlite3_blob_read,
56482   sqlite3_blob_write,
56483   sqlite3_create_collation_v2,
56484   sqlite3_file_control,
56485   sqlite3_memory_highwater,
56486   sqlite3_memory_used,
56487 #ifdef SQLITE_MUTEX_NOOP
56488   0, 
56489   0, 
56490   0,
56491   0,
56492   0,
56493 #else
56494   sqlite3_mutex_alloc,
56495   sqlite3_mutex_enter,
56496   sqlite3_mutex_free,
56497   sqlite3_mutex_leave,
56498   sqlite3_mutex_try,
56499 #endif
56500   sqlite3_open_v2,
56501   sqlite3_release_memory,
56502   sqlite3_result_error_nomem,
56503   sqlite3_result_error_toobig,
56504   sqlite3_sleep,
56505   sqlite3_soft_heap_limit,
56506   sqlite3_vfs_find,
56507   sqlite3_vfs_register,
56508   sqlite3_vfs_unregister,
56509 };
56510
56511 /*
56512 ** Attempt to load an SQLite extension library contained in the file
56513 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
56514 ** default entry point name (sqlite3_extension_init) is used.  Use
56515 ** of the default name is recommended.
56516 **
56517 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
56518 **
56519 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
56520 ** error message text.  The calling function should free this memory
56521 ** by calling sqlite3_free().
56522 */
56523 static int sqlite3LoadExtension(
56524   sqlite3 *db,          /* Load the extension into this database connection */
56525   const char *zFile,    /* Name of the shared library containing extension */
56526   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
56527   char **pzErrMsg       /* Put error message here if not 0 */
56528 ){
56529   sqlite3_vfs *pVfs = db->pVfs;
56530   void *handle;
56531   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
56532   char *zErrmsg = 0;
56533   void **aHandle;
56534
56535   /* Ticket #1863.  To avoid a creating security problems for older
56536   ** applications that relink against newer versions of SQLite, the
56537   ** ability to run load_extension is turned off by default.  One
56538   ** must call sqlite3_enable_load_extension() to turn on extension
56539   ** loading.  Otherwise you get the following error.
56540   */
56541   if( (db->flags & SQLITE_LoadExtension)==0 ){
56542     if( pzErrMsg ){
56543       *pzErrMsg = sqlite3_mprintf("not authorized");
56544     }
56545     return SQLITE_ERROR;
56546   }
56547
56548   if( zProc==0 ){
56549     zProc = "sqlite3_extension_init";
56550   }
56551
56552   handle = sqlite3OsDlOpen(pVfs, zFile);
56553   if( handle==0 ){
56554     if( pzErrMsg ){
56555       char zErr[256];
56556       zErr[sizeof(zErr)-1] = '\0';
56557       sqlite3_snprintf(sizeof(zErr)-1, zErr, 
56558           "unable to open shared library [%s]", zFile);
56559       sqlite3OsDlError(pVfs, sizeof(zErr)-1, zErr);
56560       *pzErrMsg = sqlite3DbStrDup(db, zErr);
56561     }
56562     return SQLITE_ERROR;
56563   }
56564   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
56565                    sqlite3OsDlSym(pVfs, handle, zProc);
56566   if( xInit==0 ){
56567     if( pzErrMsg ){
56568       char zErr[256];
56569       zErr[sizeof(zErr)-1] = '\0';
56570       sqlite3_snprintf(sizeof(zErr)-1, zErr,
56571           "no entry point [%s] in shared library [%s]", zProc,zFile);
56572       sqlite3OsDlError(pVfs, sizeof(zErr)-1, zErr);
56573       *pzErrMsg = sqlite3DbStrDup(db, zErr);
56574       sqlite3OsDlClose(pVfs, handle);
56575     }
56576     return SQLITE_ERROR;
56577   }else if( xInit(db, &zErrmsg, &sqlite3_apis) ){
56578     if( pzErrMsg ){
56579       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
56580     }
56581     sqlite3_free(zErrmsg);
56582     sqlite3OsDlClose(pVfs, handle);
56583     return SQLITE_ERROR;
56584   }
56585
56586   /* Append the new shared library handle to the db->aExtension array. */
56587   db->nExtension++;
56588   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*db->nExtension);
56589   if( aHandle==0 ){
56590     return SQLITE_NOMEM;
56591   }
56592   if( db->nExtension>0 ){
56593     memcpy(aHandle, db->aExtension, sizeof(handle)*(db->nExtension-1));
56594   }
56595   sqlite3_free(db->aExtension);
56596   db->aExtension = aHandle;
56597
56598   db->aExtension[db->nExtension-1] = handle;
56599   return SQLITE_OK;
56600 }
56601 SQLITE_API int sqlite3_load_extension(
56602   sqlite3 *db,          /* Load the extension into this database connection */
56603   const char *zFile,    /* Name of the shared library containing extension */
56604   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
56605   char **pzErrMsg       /* Put error message here if not 0 */
56606 ){
56607   int rc;
56608   sqlite3_mutex_enter(db->mutex);
56609   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
56610   sqlite3_mutex_leave(db->mutex);
56611   return rc;
56612 }
56613
56614 /*
56615 ** Call this routine when the database connection is closing in order
56616 ** to clean up loaded extensions
56617 */
56618 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
56619   int i;
56620   assert( sqlite3_mutex_held(db->mutex) );
56621   for(i=0; i<db->nExtension; i++){
56622     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
56623   }
56624   sqlite3_free(db->aExtension);
56625 }
56626
56627 /*
56628 ** Enable or disable extension loading.  Extension loading is disabled by
56629 ** default so as not to open security holes in older applications.
56630 */
56631 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
56632   sqlite3_mutex_enter(db->mutex);
56633   if( onoff ){
56634     db->flags |= SQLITE_LoadExtension;
56635   }else{
56636     db->flags &= ~SQLITE_LoadExtension;
56637   }
56638   sqlite3_mutex_leave(db->mutex);
56639   return SQLITE_OK;
56640 }
56641
56642 /*
56643 ** The following object holds the list of automatically loaded
56644 ** extensions.
56645 **
56646 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
56647 ** mutex must be held while accessing this list.
56648 */
56649 static struct {
56650   int nExt;        /* Number of entries in aExt[] */          
56651   void **aExt;     /* Pointers to the extension init functions */
56652 } autoext = { 0, 0 };
56653
56654
56655 /*
56656 ** Register a statically linked extension that is automatically
56657 ** loaded by every new database connection.
56658 */
56659 SQLITE_API int sqlite3_auto_extension(void *xInit){
56660   int i;
56661   int rc = SQLITE_OK;
56662   sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
56663   sqlite3_mutex_enter(mutex);
56664   for(i=0; i<autoext.nExt; i++){
56665     if( autoext.aExt[i]==xInit ) break;
56666   }
56667   if( i==autoext.nExt ){
56668     int nByte = (autoext.nExt+1)*sizeof(autoext.aExt[0]);
56669     void **aNew;
56670     aNew = sqlite3_realloc(autoext.aExt, nByte);
56671     if( aNew==0 ){
56672       rc = SQLITE_NOMEM;
56673     }else{
56674       autoext.aExt = aNew;
56675       autoext.aExt[autoext.nExt] = xInit;
56676       autoext.nExt++;
56677     }
56678   }
56679   sqlite3_mutex_leave(mutex);
56680   assert( (rc&0xff)==rc );
56681   return rc;
56682 }
56683
56684 /*
56685 ** Reset the automatic extension loading mechanism.
56686 */
56687 SQLITE_API void sqlite3_reset_auto_extension(void){
56688   sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
56689   sqlite3_mutex_enter(mutex);
56690   sqlite3_free(autoext.aExt);
56691   autoext.aExt = 0;
56692   autoext.nExt = 0;
56693   sqlite3_mutex_leave(mutex);
56694 }
56695
56696 /*
56697 ** Load all automatic extensions.
56698 */
56699 SQLITE_PRIVATE int sqlite3AutoLoadExtensions(sqlite3 *db){
56700   int i;
56701   int go = 1;
56702   int rc = SQLITE_OK;
56703   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
56704
56705   if( autoext.nExt==0 ){
56706     /* Common case: early out without every having to acquire a mutex */
56707     return SQLITE_OK;
56708   }
56709   for(i=0; go; i++){
56710     char *zErrmsg = 0;
56711     sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
56712     sqlite3_mutex_enter(mutex);
56713     if( i>=autoext.nExt ){
56714       xInit = 0;
56715       go = 0;
56716     }else{
56717       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
56718               autoext.aExt[i];
56719     }
56720     sqlite3_mutex_leave(mutex);
56721     if( xInit && xInit(db, &zErrmsg, &sqlite3_apis) ){
56722       sqlite3Error(db, SQLITE_ERROR,
56723             "automatic extension loading failed: %s", zErrmsg);
56724       go = 0;
56725       rc = SQLITE_ERROR;
56726       sqlite3_free(zErrmsg);
56727     }
56728   }
56729   return rc;
56730 }
56731
56732 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
56733
56734 /************** End of loadext.c *********************************************/
56735 /************** Begin file pragma.c ******************************************/
56736 /*
56737 ** 2003 April 6
56738 **
56739 ** The author disclaims copyright to this source code.  In place of
56740 ** a legal notice, here is a blessing:
56741 **
56742 **    May you do good and not evil.
56743 **    May you find forgiveness for yourself and forgive others.
56744 **    May you share freely, never taking more than you give.
56745 **
56746 *************************************************************************
56747 ** This file contains code used to implement the PRAGMA command.
56748 **
56749 ** $Id: pragma.c,v 1.152 2007/12/13 21:54:11 drh Exp $
56750 */
56751
56752 /* Ignore this whole file if pragmas are disabled
56753 */
56754 #if !defined(SQLITE_OMIT_PRAGMA) && !defined(SQLITE_OMIT_PARSER)
56755
56756 /*
56757 ** Interpret the given string as a safety level.  Return 0 for OFF,
56758 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
56759 ** unrecognized string argument.
56760 **
56761 ** Note that the values returned are one less that the values that
56762 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
56763 ** to support legacy SQL code.  The safety level used to be boolean
56764 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
56765 */
56766 static int getSafetyLevel(const char *z){
56767                              /* 123456789 123456789 */
56768   static const char zText[] = "onoffalseyestruefull";
56769   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
56770   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
56771   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
56772   int i, n;
56773   if( isdigit(*z) ){
56774     return atoi(z);
56775   }
56776   n = strlen(z);
56777   for(i=0; i<sizeof(iLength); i++){
56778     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
56779       return iValue[i];
56780     }
56781   }
56782   return 1;
56783 }
56784
56785 /*
56786 ** Interpret the given string as a boolean value.
56787 */
56788 static int getBoolean(const char *z){
56789   return getSafetyLevel(z)&1;
56790 }
56791
56792 /*
56793 ** Interpret the given string as a locking mode value.
56794 */
56795 static int getLockingMode(const char *z){
56796   if( z ){
56797     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
56798     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
56799   }
56800   return PAGER_LOCKINGMODE_QUERY;
56801 }
56802
56803 #ifndef SQLITE_OMIT_AUTOVACUUM
56804 /*
56805 ** Interpret the given string as an auto-vacuum mode value.
56806 **
56807 ** The following strings, "none", "full" and "incremental" are 
56808 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
56809 */
56810 static int getAutoVacuum(const char *z){
56811   int i;
56812   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
56813   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
56814   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
56815   i = atoi(z);
56816   return ((i>=0&&i<=2)?i:0);
56817 }
56818 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
56819
56820 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
56821 /*
56822 ** Interpret the given string as a temp db location. Return 1 for file
56823 ** backed temporary databases, 2 for the Red-Black tree in memory database
56824 ** and 0 to use the compile-time default.
56825 */
56826 static int getTempStore(const char *z){
56827   if( z[0]>='0' && z[0]<='2' ){
56828     return z[0] - '0';
56829   }else if( sqlite3StrICmp(z, "file")==0 ){
56830     return 1;
56831   }else if( sqlite3StrICmp(z, "memory")==0 ){
56832     return 2;
56833   }else{
56834     return 0;
56835   }
56836 }
56837 #endif /* SQLITE_PAGER_PRAGMAS */
56838
56839 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
56840 /*
56841 ** Invalidate temp storage, either when the temp storage is changed
56842 ** from default, or when 'file' and the temp_store_directory has changed
56843 */
56844 static int invalidateTempStorage(Parse *pParse){
56845   sqlite3 *db = pParse->db;
56846   if( db->aDb[1].pBt!=0 ){
56847     if( !db->autoCommit ){
56848       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
56849         "from within a transaction");
56850       return SQLITE_ERROR;
56851     }
56852     sqlite3BtreeClose(db->aDb[1].pBt);
56853     db->aDb[1].pBt = 0;
56854     sqlite3ResetInternalSchema(db, 0);
56855   }
56856   return SQLITE_OK;
56857 }
56858 #endif /* SQLITE_PAGER_PRAGMAS */
56859
56860 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
56861 /*
56862 ** If the TEMP database is open, close it and mark the database schema
56863 ** as needing reloading.  This must be done when using the TEMP_STORE
56864 ** or DEFAULT_TEMP_STORE pragmas.
56865 */
56866 static int changeTempStorage(Parse *pParse, const char *zStorageType){
56867   int ts = getTempStore(zStorageType);
56868   sqlite3 *db = pParse->db;
56869   if( db->temp_store==ts ) return SQLITE_OK;
56870   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
56871     return SQLITE_ERROR;
56872   }
56873   db->temp_store = ts;
56874   return SQLITE_OK;
56875 }
56876 #endif /* SQLITE_PAGER_PRAGMAS */
56877
56878 /*
56879 ** Generate code to return a single integer value.
56880 */
56881 static void returnSingleInt(Parse *pParse, const char *zLabel, int value){
56882   Vdbe *v = sqlite3GetVdbe(pParse);
56883   sqlite3VdbeAddOp(v, OP_Integer, value, 0);
56884   if( pParse->explain==0 ){
56885     sqlite3VdbeSetNumCols(v, 1);
56886     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, P3_STATIC);
56887   }
56888   sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
56889 }
56890
56891 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
56892 /*
56893 ** Check to see if zRight and zLeft refer to a pragma that queries
56894 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
56895 ** Also, implement the pragma.
56896 */
56897 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
56898   static const struct sPragmaType {
56899     const char *zName;  /* Name of the pragma */
56900     int mask;           /* Mask for the db->flags value */
56901   } aPragma[] = {
56902     { "full_column_names",        SQLITE_FullColNames  },
56903     { "short_column_names",       SQLITE_ShortColNames },
56904     { "count_changes",            SQLITE_CountRows     },
56905     { "empty_result_callbacks",   SQLITE_NullCallback  },
56906     { "legacy_file_format",       SQLITE_LegacyFileFmt },
56907     { "fullfsync",                SQLITE_FullFSync     },
56908 #ifdef SQLITE_DEBUG
56909     { "sql_trace",                SQLITE_SqlTrace      },
56910     { "vdbe_listing",             SQLITE_VdbeListing   },
56911     { "vdbe_trace",               SQLITE_VdbeTrace     },
56912 #endif
56913 #ifndef SQLITE_OMIT_CHECK
56914     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
56915 #endif
56916     /* The following is VERY experimental */
56917     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
56918     { "omit_readlock",            SQLITE_NoReadlock    },
56919
56920     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
56921     ** flag if there are any active statements. */
56922     { "read_uncommitted",         SQLITE_ReadUncommitted },
56923   };
56924   int i;
56925   const struct sPragmaType *p;
56926   for(i=0, p=aPragma; i<sizeof(aPragma)/sizeof(aPragma[0]); i++, p++){
56927     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
56928       sqlite3 *db = pParse->db;
56929       Vdbe *v;
56930       v = sqlite3GetVdbe(pParse);
56931       if( v ){
56932         if( zRight==0 ){
56933           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
56934         }else{
56935           if( getBoolean(zRight) ){
56936             db->flags |= p->mask;
56937           }else{
56938             db->flags &= ~p->mask;
56939           }
56940
56941           /* Many of the flag-pragmas modify the code generated by the SQL 
56942           ** compiler (eg. count_changes). So add an opcode to expire all
56943           ** compiled SQL statements after modifying a pragma value.
56944           */
56945           sqlite3VdbeAddOp(v, OP_Expire, 0, 0);
56946         }
56947       }
56948
56949       return 1;
56950     }
56951   }
56952   return 0;
56953 }
56954 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
56955
56956 /*
56957 ** Process a pragma statement.  
56958 **
56959 ** Pragmas are of this form:
56960 **
56961 **      PRAGMA [database.]id [= value]
56962 **
56963 ** The identifier might also be a string.  The value is a string, and
56964 ** identifier, or a number.  If minusFlag is true, then the value is
56965 ** a number that was preceded by a minus sign.
56966 **
56967 ** If the left side is "database.id" then pId1 is the database name
56968 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
56969 ** id and pId2 is any empty string.
56970 */
56971 SQLITE_PRIVATE void sqlite3Pragma(
56972   Parse *pParse, 
56973   Token *pId1,        /* First part of [database.]id field */
56974   Token *pId2,        /* Second part of [database.]id field, or NULL */
56975   Token *pValue,      /* Token for <value>, or NULL */
56976   int minusFlag       /* True if a '-' sign preceded <value> */
56977 ){
56978   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
56979   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
56980   const char *zDb = 0;   /* The database name */
56981   Token *pId;            /* Pointer to <id> token */
56982   int iDb;               /* Database index for <database> */
56983   sqlite3 *db = pParse->db;
56984   Db *pDb;
56985   Vdbe *v = sqlite3GetVdbe(pParse);
56986   if( v==0 ) return;
56987
56988   /* Interpret the [database.] part of the pragma statement. iDb is the
56989   ** index of the database this pragma is being applied to in db.aDb[]. */
56990   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
56991   if( iDb<0 ) return;
56992   pDb = &db->aDb[iDb];
56993
56994   /* If the temp database has been explicitly named as part of the 
56995   ** pragma, make sure it is open. 
56996   */
56997   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
56998     return;
56999   }
57000
57001   zLeft = sqlite3NameFromToken(db, pId);
57002   if( !zLeft ) return;
57003   if( minusFlag ){
57004     zRight = sqlite3MPrintf(db, "-%T", pValue);
57005   }else{
57006     zRight = sqlite3NameFromToken(db, pValue);
57007   }
57008
57009   zDb = ((iDb>0)?pDb->zName:0);
57010   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
57011     goto pragma_out;
57012   }
57013  
57014 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
57015   /*
57016   **  PRAGMA [database.]default_cache_size
57017   **  PRAGMA [database.]default_cache_size=N
57018   **
57019   ** The first form reports the current persistent setting for the
57020   ** page cache size.  The value returned is the maximum number of
57021   ** pages in the page cache.  The second form sets both the current
57022   ** page cache size value and the persistent page cache size value
57023   ** stored in the database file.
57024   **
57025   ** The default cache size is stored in meta-value 2 of page 1 of the
57026   ** database file.  The cache size is actually the absolute value of
57027   ** this memory location.  The sign of meta-value 2 determines the
57028   ** synchronous setting.  A negative value means synchronous is off
57029   ** and a positive value means synchronous is on.
57030   */
57031   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
57032     static const VdbeOpList getCacheSize[] = {
57033       { OP_ReadCookie,  0, 2,        0},  /* 0 */
57034       { OP_AbsValue,    0, 0,        0},
57035       { OP_Dup,         0, 0,        0},
57036       { OP_Integer,     0, 0,        0},
57037       { OP_Ne,          0, 6,        0},
57038       { OP_Integer,     0, 0,        0},  /* 5 */
57039       { OP_Callback,    1, 0,        0},
57040     };
57041     int addr;
57042     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
57043     sqlite3VdbeUsesBtree(v, iDb);
57044     if( !zRight ){
57045       sqlite3VdbeSetNumCols(v, 1);
57046       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", P3_STATIC);
57047       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
57048       sqlite3VdbeChangeP1(v, addr, iDb);
57049       sqlite3VdbeChangeP1(v, addr+5, SQLITE_DEFAULT_CACHE_SIZE);
57050     }else{
57051       int size = atoi(zRight);
57052       if( size<0 ) size = -size;
57053       sqlite3BeginWriteOperation(pParse, 0, iDb);
57054       sqlite3VdbeAddOp(v, OP_Integer, size, 0);
57055       sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 2);
57056       addr = sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
57057       sqlite3VdbeAddOp(v, OP_Ge, 0, addr+3);
57058       sqlite3VdbeAddOp(v, OP_Negative, 0, 0);
57059       sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 2);
57060       pDb->pSchema->cache_size = size;
57061       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
57062     }
57063   }else
57064
57065   /*
57066   **  PRAGMA [database.]page_size
57067   **  PRAGMA [database.]page_size=N
57068   **
57069   ** The first form reports the current setting for the
57070   ** database page size in bytes.  The second form sets the
57071   ** database page size value.  The value can only be set if
57072   ** the database has not yet been created.
57073   */
57074   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
57075     Btree *pBt = pDb->pBt;
57076     if( !zRight ){
57077       int size = pBt ? sqlite3BtreeGetPageSize(pBt) : 0;
57078       returnSingleInt(pParse, "page_size", size);
57079     }else{
57080       /* Malloc may fail when setting the page-size, as there is an internal
57081       ** buffer that the pager module resizes using sqlite3_realloc().
57082       */
57083       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, atoi(zRight), -1) ){
57084         db->mallocFailed = 1;
57085       }
57086     }
57087   }else
57088
57089   /*
57090   **  PRAGMA [database.]max_page_count
57091   **  PRAGMA [database.]max_page_count=N
57092   **
57093   ** The first form reports the current setting for the
57094   ** maximum number of pages in the database file.  The 
57095   ** second form attempts to change this setting.  Both
57096   ** forms return the current setting.
57097   */
57098   if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
57099     Btree *pBt = pDb->pBt;
57100     int newMax = 0;
57101     if( zRight ){
57102       newMax = atoi(zRight);
57103     }
57104     if( pBt ){
57105       newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
57106     }
57107     returnSingleInt(pParse, "max_page_count", newMax);
57108   }else
57109
57110   /*
57111   **  PRAGMA [database.]locking_mode
57112   **  PRAGMA [database.]locking_mode = (normal|exclusive)
57113   */
57114   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
57115     const char *zRet = "normal";
57116     int eMode = getLockingMode(zRight);
57117
57118     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
57119       /* Simple "PRAGMA locking_mode;" statement. This is a query for
57120       ** the current default locking mode (which may be different to
57121       ** the locking-mode of the main database).
57122       */
57123       eMode = db->dfltLockMode;
57124     }else{
57125       Pager *pPager;
57126       if( pId2->n==0 ){
57127         /* This indicates that no database name was specified as part
57128         ** of the PRAGMA command. In this case the locking-mode must be
57129         ** set on all attached databases, as well as the main db file.
57130         **
57131         ** Also, the sqlite3.dfltLockMode variable is set so that
57132         ** any subsequently attached databases also use the specified
57133         ** locking mode.
57134         */
57135         int ii;
57136         assert(pDb==&db->aDb[0]);
57137         for(ii=2; ii<db->nDb; ii++){
57138           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
57139           sqlite3PagerLockingMode(pPager, eMode);
57140         }
57141         db->dfltLockMode = eMode;
57142       }
57143       pPager = sqlite3BtreePager(pDb->pBt);
57144       eMode = sqlite3PagerLockingMode(pPager, eMode);
57145     }
57146
57147     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
57148     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
57149       zRet = "exclusive";
57150     }
57151     sqlite3VdbeSetNumCols(v, 1);
57152     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", P3_STATIC);
57153     sqlite3VdbeOp3(v, OP_String8, 0, 0, zRet, 0);
57154     sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
57155   }else
57156 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
57157
57158   /*
57159   **  PRAGMA [database.]auto_vacuum
57160   **  PRAGMA [database.]auto_vacuum=N
57161   **
57162   ** Get or set the (boolean) value of the database 'auto-vacuum' parameter.
57163   */
57164 #ifndef SQLITE_OMIT_AUTOVACUUM
57165   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
57166     Btree *pBt = pDb->pBt;
57167     if( sqlite3ReadSchema(pParse) ){
57168       goto pragma_out;
57169     }
57170     if( !zRight ){
57171       int auto_vacuum = 
57172           pBt ? sqlite3BtreeGetAutoVacuum(pBt) : SQLITE_DEFAULT_AUTOVACUUM;
57173       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
57174     }else{
57175       int eAuto = getAutoVacuum(zRight);
57176       db->nextAutovac = eAuto;
57177       if( eAuto>=0 ){
57178         /* Call SetAutoVacuum() to set initialize the internal auto and
57179         ** incr-vacuum flags. This is required in case this connection
57180         ** creates the database file. It is important that it is created
57181         ** as an auto-vacuum capable db.
57182         */
57183         int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
57184         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
57185           /* When setting the auto_vacuum mode to either "full" or 
57186           ** "incremental", write the value of meta[6] in the database
57187           ** file. Before writing to meta[6], check that meta[3] indicates
57188           ** that this really is an auto-vacuum capable database.
57189           */
57190           static const VdbeOpList setMeta6[] = {
57191             { OP_Transaction,    0,               1,        0},    /* 0 */
57192             { OP_ReadCookie,     0,               3,        0},    /* 1 */
57193             { OP_If,             0,               0,        0},    /* 2 */
57194             { OP_Halt,           SQLITE_OK,       OE_Abort, 0},    /* 3 */
57195             { OP_Integer,        0,               0,        0},    /* 4 */
57196             { OP_SetCookie,      0,               6,        0},    /* 5 */
57197           };
57198           int iAddr;
57199           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
57200           sqlite3VdbeChangeP1(v, iAddr, iDb);
57201           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
57202           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
57203           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
57204           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
57205           sqlite3VdbeUsesBtree(v, iDb);
57206         }
57207       }
57208     }
57209   }else
57210 #endif
57211
57212   /*
57213   **  PRAGMA [database.]incremental_vacuum(N)
57214   **
57215   ** Do N steps of incremental vacuuming on a database.
57216   */
57217 #ifndef SQLITE_OMIT_AUTOVACUUM
57218   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
57219     int iLimit, addr;
57220     if( sqlite3ReadSchema(pParse) ){
57221       goto pragma_out;
57222     }
57223     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
57224       iLimit = 0x7fffffff;
57225     }
57226     sqlite3BeginWriteOperation(pParse, 0, iDb);
57227     sqlite3VdbeAddOp(v, OP_MemInt, iLimit, 0);
57228     addr = sqlite3VdbeAddOp(v, OP_IncrVacuum, iDb, 0);
57229     sqlite3VdbeAddOp(v, OP_Callback, 0, 0);
57230     sqlite3VdbeAddOp(v, OP_MemIncr, -1, 0);
57231     sqlite3VdbeAddOp(v, OP_IfMemPos, 0, addr);
57232     sqlite3VdbeJumpHere(v, addr);
57233   }else
57234 #endif
57235
57236 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
57237   /*
57238   **  PRAGMA [database.]cache_size
57239   **  PRAGMA [database.]cache_size=N
57240   **
57241   ** The first form reports the current local setting for the
57242   ** page cache size.  The local setting can be different from
57243   ** the persistent cache size value that is stored in the database
57244   ** file itself.  The value returned is the maximum number of
57245   ** pages in the page cache.  The second form sets the local
57246   ** page cache size value.  It does not change the persistent
57247   ** cache size stored on the disk so the cache size will revert
57248   ** to its default value when the database is closed and reopened.
57249   ** N should be a positive integer.
57250   */
57251   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
57252     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
57253     if( !zRight ){
57254       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
57255     }else{
57256       int size = atoi(zRight);
57257       if( size<0 ) size = -size;
57258       pDb->pSchema->cache_size = size;
57259       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
57260     }
57261   }else
57262
57263   /*
57264   **   PRAGMA temp_store
57265   **   PRAGMA temp_store = "default"|"memory"|"file"
57266   **
57267   ** Return or set the local value of the temp_store flag.  Changing
57268   ** the local value does not make changes to the disk file and the default
57269   ** value will be restored the next time the database is opened.
57270   **
57271   ** Note that it is possible for the library compile-time options to
57272   ** override this setting
57273   */
57274   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
57275     if( !zRight ){
57276       returnSingleInt(pParse, "temp_store", db->temp_store);
57277     }else{
57278       changeTempStorage(pParse, zRight);
57279     }
57280   }else
57281
57282   /*
57283   **   PRAGMA temp_store_directory
57284   **   PRAGMA temp_store_directory = ""|"directory_name"
57285   **
57286   ** Return or set the local value of the temp_store_directory flag.  Changing
57287   ** the value sets a specific directory to be used for temporary files.
57288   ** Setting to a null string reverts to the default temporary directory search.
57289   ** If temporary directory is changed, then invalidateTempStorage.
57290   **
57291   */
57292   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
57293     if( !zRight ){
57294       if( sqlite3_temp_directory ){
57295         sqlite3VdbeSetNumCols(v, 1);
57296         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
57297             "temp_store_directory", P3_STATIC);
57298         sqlite3VdbeOp3(v, OP_String8, 0, 0, sqlite3_temp_directory, 0);
57299         sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
57300       }
57301     }else{
57302       if( zRight[0] 
57303        && !sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE) 
57304       ){
57305         sqlite3ErrorMsg(pParse, "not a writable directory");
57306         goto pragma_out;
57307       }
57308       if( TEMP_STORE==0
57309        || (TEMP_STORE==1 && db->temp_store<=1)
57310        || (TEMP_STORE==2 && db->temp_store==1)
57311       ){
57312         invalidateTempStorage(pParse);
57313       }
57314       sqlite3_free(sqlite3_temp_directory);
57315       if( zRight[0] ){
57316         sqlite3_temp_directory = zRight;
57317         zRight = 0;
57318       }else{
57319         sqlite3_temp_directory = 0;
57320       }
57321     }
57322   }else
57323
57324   /*
57325   **   PRAGMA [database.]synchronous
57326   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
57327   **
57328   ** Return or set the local value of the synchronous flag.  Changing
57329   ** the local value does not make changes to the disk file and the
57330   ** default value will be restored the next time the database is
57331   ** opened.
57332   */
57333   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
57334     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
57335     if( !zRight ){
57336       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
57337     }else{
57338       if( !db->autoCommit ){
57339         sqlite3ErrorMsg(pParse, 
57340             "Safety level may not be changed inside a transaction");
57341       }else{
57342         pDb->safety_level = getSafetyLevel(zRight)+1;
57343       }
57344     }
57345   }else
57346 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
57347
57348 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
57349   if( flagPragma(pParse, zLeft, zRight) ){
57350     /* The flagPragma() subroutine also generates any necessary code
57351     ** there is nothing more to do here */
57352   }else
57353 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
57354
57355 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
57356   /*
57357   **   PRAGMA table_info(<table>)
57358   **
57359   ** Return a single row for each column of the named table. The columns of
57360   ** the returned data set are:
57361   **
57362   ** cid:        Column id (numbered from left to right, starting at 0)
57363   ** name:       Column name
57364   ** type:       Column declaration type.
57365   ** notnull:    True if 'NOT NULL' is part of column declaration
57366   ** dflt_value: The default value for the column, if any.
57367   */
57368   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
57369     Table *pTab;
57370     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
57371     pTab = sqlite3FindTable(db, zRight, zDb);
57372     if( pTab ){
57373       int i;
57374       int nHidden = 0;
57375       Column *pCol;
57376       sqlite3VdbeSetNumCols(v, 6);
57377       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", P3_STATIC);
57378       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P3_STATIC);
57379       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", P3_STATIC);
57380       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", P3_STATIC);
57381       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", P3_STATIC);
57382       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", P3_STATIC);
57383       sqlite3ViewGetColumnNames(pParse, pTab);
57384       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
57385         const Token *pDflt;
57386         if( IsHiddenColumn(pCol) ){
57387           nHidden++;
57388           continue;
57389         }
57390         sqlite3VdbeAddOp(v, OP_Integer, i-nHidden, 0);
57391         sqlite3VdbeOp3(v, OP_String8, 0, 0, pCol->zName, 0);
57392         sqlite3VdbeOp3(v, OP_String8, 0, 0,
57393            pCol->zType ? pCol->zType : "", 0);
57394         sqlite3VdbeAddOp(v, OP_Integer, pCol->notNull, 0);
57395         if( pCol->pDflt && (pDflt = &pCol->pDflt->span)->z ){
57396           sqlite3VdbeOp3(v, OP_String8, 0, 0, (char*)pDflt->z, pDflt->n);
57397         }else{
57398           sqlite3VdbeAddOp(v, OP_Null, 0, 0);
57399         }
57400         sqlite3VdbeAddOp(v, OP_Integer, pCol->isPrimKey, 0);
57401         sqlite3VdbeAddOp(v, OP_Callback, 6, 0);
57402       }
57403     }
57404   }else
57405
57406   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
57407     Index *pIdx;
57408     Table *pTab;
57409     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
57410     pIdx = sqlite3FindIndex(db, zRight, zDb);
57411     if( pIdx ){
57412       int i;
57413       pTab = pIdx->pTable;
57414       sqlite3VdbeSetNumCols(v, 3);
57415       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", P3_STATIC);
57416       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", P3_STATIC);
57417       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", P3_STATIC);
57418       for(i=0; i<pIdx->nColumn; i++){
57419         int cnum = pIdx->aiColumn[i];
57420         sqlite3VdbeAddOp(v, OP_Integer, i, 0);
57421         sqlite3VdbeAddOp(v, OP_Integer, cnum, 0);
57422         assert( pTab->nCol>cnum );
57423         sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->aCol[cnum].zName, 0);
57424         sqlite3VdbeAddOp(v, OP_Callback, 3, 0);
57425       }
57426     }
57427   }else
57428
57429   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
57430     Index *pIdx;
57431     Table *pTab;
57432     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
57433     pTab = sqlite3FindTable(db, zRight, zDb);
57434     if( pTab ){
57435       v = sqlite3GetVdbe(pParse);
57436       pIdx = pTab->pIndex;
57437       if( pIdx ){
57438         int i = 0; 
57439         sqlite3VdbeSetNumCols(v, 3);
57440         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P3_STATIC);
57441         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P3_STATIC);
57442         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", P3_STATIC);
57443         while(pIdx){
57444           sqlite3VdbeAddOp(v, OP_Integer, i, 0);
57445           sqlite3VdbeOp3(v, OP_String8, 0, 0, pIdx->zName, 0);
57446           sqlite3VdbeAddOp(v, OP_Integer, pIdx->onError!=OE_None, 0);
57447           sqlite3VdbeAddOp(v, OP_Callback, 3, 0);
57448           ++i;
57449           pIdx = pIdx->pNext;
57450         }
57451       }
57452     }
57453   }else
57454
57455   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
57456     int i;
57457     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
57458     sqlite3VdbeSetNumCols(v, 3);
57459     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P3_STATIC);
57460     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P3_STATIC);
57461     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", P3_STATIC);
57462     for(i=0; i<db->nDb; i++){
57463       if( db->aDb[i].pBt==0 ) continue;
57464       assert( db->aDb[i].zName!=0 );
57465       sqlite3VdbeAddOp(v, OP_Integer, i, 0);
57466       sqlite3VdbeOp3(v, OP_String8, 0, 0, db->aDb[i].zName, 0);
57467       sqlite3VdbeOp3(v, OP_String8, 0, 0,
57468            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
57469       sqlite3VdbeAddOp(v, OP_Callback, 3, 0);
57470     }
57471   }else
57472
57473   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
57474     int i = 0;
57475     HashElem *p;
57476     sqlite3VdbeSetNumCols(v, 2);
57477     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P3_STATIC);
57478     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P3_STATIC);
57479     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
57480       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
57481       sqlite3VdbeAddOp(v, OP_Integer, i++, 0);
57482       sqlite3VdbeOp3(v, OP_String8, 0, 0, pColl->zName, 0);
57483       sqlite3VdbeAddOp(v, OP_Callback, 2, 0);
57484     }
57485   }else
57486 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
57487
57488 #ifndef SQLITE_OMIT_FOREIGN_KEY
57489   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
57490     FKey *pFK;
57491     Table *pTab;
57492     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
57493     pTab = sqlite3FindTable(db, zRight, zDb);
57494     if( pTab ){
57495       v = sqlite3GetVdbe(pParse);
57496       pFK = pTab->pFKey;
57497       if( pFK ){
57498         int i = 0; 
57499         sqlite3VdbeSetNumCols(v, 5);
57500         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", P3_STATIC);
57501         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", P3_STATIC);
57502         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", P3_STATIC);
57503         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", P3_STATIC);
57504         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", P3_STATIC);
57505         while(pFK){
57506           int j;
57507           for(j=0; j<pFK->nCol; j++){
57508             char *zCol = pFK->aCol[j].zCol;
57509             sqlite3VdbeAddOp(v, OP_Integer, i, 0);
57510             sqlite3VdbeAddOp(v, OP_Integer, j, 0);
57511             sqlite3VdbeOp3(v, OP_String8, 0, 0, pFK->zTo, 0);
57512             sqlite3VdbeOp3(v, OP_String8, 0, 0,
57513                              pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
57514             sqlite3VdbeOp3(v, zCol ? OP_String8 : OP_Null, 0, 0, zCol, 0);
57515             sqlite3VdbeAddOp(v, OP_Callback, 5, 0);
57516           }
57517           ++i;
57518           pFK = pFK->pNextFrom;
57519         }
57520       }
57521     }
57522   }else
57523 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
57524
57525 #ifndef NDEBUG
57526   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
57527     if( zRight ){
57528       if( getBoolean(zRight) ){
57529         sqlite3ParserTrace(stderr, "parser: ");
57530       }else{
57531         sqlite3ParserTrace(0, 0);
57532       }
57533     }
57534   }else
57535 #endif
57536
57537   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
57538   ** used will be case sensitive or not depending on the RHS.
57539   */
57540   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
57541     if( zRight ){
57542       sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
57543     }
57544   }else
57545
57546 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
57547 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
57548 #endif
57549
57550 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
57551   if( sqlite3StrICmp(zLeft, "integrity_check")==0 ){
57552     int i, j, addr, mxErr;
57553
57554     /* Code that appears at the end of the integrity check.  If no error
57555     ** messages have been generated, output OK.  Otherwise output the
57556     ** error message
57557     */
57558     static const VdbeOpList endCode[] = {
57559       { OP_MemLoad,     0, 0,        0},
57560       { OP_Integer,     0, 0,        0},
57561       { OP_Ne,          0, 0,        0},    /* 2 */
57562       { OP_String8,     0, 0,        "ok"},
57563       { OP_Callback,    1, 0,        0},
57564     };
57565
57566     /* Initialize the VDBE program */
57567     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
57568     sqlite3VdbeSetNumCols(v, 1);
57569     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", P3_STATIC);
57570
57571     /* Set the maximum error count */
57572     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
57573     if( zRight ){
57574       mxErr = atoi(zRight);
57575       if( mxErr<=0 ){
57576         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
57577       }
57578     }
57579     sqlite3VdbeAddOp(v, OP_MemInt, mxErr, 0);
57580
57581     /* Do an integrity check on each database file */
57582     for(i=0; i<db->nDb; i++){
57583       HashElem *x;
57584       Hash *pTbls;
57585       int cnt = 0;
57586
57587       if( OMIT_TEMPDB && i==1 ) continue;
57588
57589       sqlite3CodeVerifySchema(pParse, i);
57590       addr = sqlite3VdbeAddOp(v, OP_IfMemPos, 0, 0);
57591       sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
57592       sqlite3VdbeJumpHere(v, addr);
57593
57594       /* Do an integrity check of the B-Tree
57595       */
57596       pTbls = &db->aDb[i].pSchema->tblHash;
57597       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
57598         Table *pTab = sqliteHashData(x);
57599         Index *pIdx;
57600         sqlite3VdbeAddOp(v, OP_Integer, pTab->tnum, 0);
57601         cnt++;
57602         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
57603           sqlite3VdbeAddOp(v, OP_Integer, pIdx->tnum, 0);
57604           cnt++;
57605         }
57606       }
57607       if( cnt==0 ) continue;
57608       sqlite3VdbeAddOp(v, OP_IntegrityCk, 0, i);
57609       addr = sqlite3VdbeAddOp(v, OP_IsNull, -1, 0);
57610       sqlite3VdbeOp3(v, OP_String8, 0, 0,
57611          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
57612          P3_DYNAMIC);
57613       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
57614       sqlite3VdbeAddOp(v, OP_Concat, 0, 0);
57615       sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
57616       sqlite3VdbeJumpHere(v, addr);
57617
57618       /* Make sure all the indices are constructed correctly.
57619       */
57620       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
57621         Table *pTab = sqliteHashData(x);
57622         Index *pIdx;
57623         int loopTop;
57624
57625         if( pTab->pIndex==0 ) continue;
57626         addr = sqlite3VdbeAddOp(v, OP_IfMemPos, 0, 0);
57627         sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
57628         sqlite3VdbeJumpHere(v, addr);
57629         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
57630         sqlite3VdbeAddOp(v, OP_MemInt, 0, 1);
57631         loopTop = sqlite3VdbeAddOp(v, OP_Rewind, 1, 0);
57632         sqlite3VdbeAddOp(v, OP_MemIncr, 1, 1);
57633         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
57634           int jmp2;
57635           static const VdbeOpList idxErr[] = {
57636             { OP_MemIncr,    -1,  0,  0},
57637             { OP_String8,     0,  0,  "rowid "},
57638             { OP_Rowid,       1,  0,  0},
57639             { OP_String8,     0,  0,  " missing from index "},
57640             { OP_String8,     0,  0,  0},    /* 4 */
57641             { OP_Concat,      2,  0,  0},
57642             { OP_Callback,    1,  0,  0},
57643           };
57644           sqlite3GenerateIndexKey(v, pIdx, 1);
57645           jmp2 = sqlite3VdbeAddOp(v, OP_Found, j+2, 0);
57646           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
57647           sqlite3VdbeChangeP3(v, addr+4, pIdx->zName, P3_STATIC);
57648           sqlite3VdbeJumpHere(v, jmp2);
57649         }
57650         sqlite3VdbeAddOp(v, OP_Next, 1, loopTop+1);
57651         sqlite3VdbeJumpHere(v, loopTop);
57652         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
57653           static const VdbeOpList cntIdx[] = {
57654              { OP_MemInt,       0,  2,  0},
57655              { OP_Rewind,       0,  0,  0},  /* 1 */
57656              { OP_MemIncr,      1,  2,  0},
57657              { OP_Next,         0,  0,  0},  /* 3 */
57658              { OP_MemLoad,      1,  0,  0},
57659              { OP_MemLoad,      2,  0,  0},
57660              { OP_Eq,           0,  0,  0},  /* 6 */
57661              { OP_MemIncr,     -1,  0,  0},
57662              { OP_String8,      0,  0,  "wrong # of entries in index "},
57663              { OP_String8,      0,  0,  0},  /* 9 */
57664              { OP_Concat,       0,  0,  0},
57665              { OP_Callback,     1,  0,  0},
57666           };
57667           if( pIdx->tnum==0 ) continue;
57668           addr = sqlite3VdbeAddOp(v, OP_IfMemPos, 0, 0);
57669           sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
57670           sqlite3VdbeJumpHere(v, addr);
57671           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
57672           sqlite3VdbeChangeP1(v, addr+1, j+2);
57673           sqlite3VdbeChangeP2(v, addr+1, addr+4);
57674           sqlite3VdbeChangeP1(v, addr+3, j+2);
57675           sqlite3VdbeChangeP2(v, addr+3, addr+2);
57676           sqlite3VdbeJumpHere(v, addr+6);
57677           sqlite3VdbeChangeP3(v, addr+9, pIdx->zName, P3_STATIC);
57678         }
57679       } 
57680     }
57681     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
57682     sqlite3VdbeChangeP1(v, addr+1, mxErr);
57683     sqlite3VdbeJumpHere(v, addr+2);
57684   }else
57685 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57686
57687 #ifndef SQLITE_OMIT_UTF16
57688   /*
57689   **   PRAGMA encoding
57690   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
57691   **
57692   ** In its first form, this pragma returns the encoding of the main
57693   ** database. If the database is not initialized, it is initialized now.
57694   **
57695   ** The second form of this pragma is a no-op if the main database file
57696   ** has not already been initialized. In this case it sets the default
57697   ** encoding that will be used for the main database file if a new file
57698   ** is created. If an existing main database file is opened, then the
57699   ** default text encoding for the existing database is used.
57700   ** 
57701   ** In all cases new databases created using the ATTACH command are
57702   ** created to use the same default text encoding as the main database. If
57703   ** the main database has not been initialized and/or created when ATTACH
57704   ** is executed, this is done before the ATTACH operation.
57705   **
57706   ** In the second form this pragma sets the text encoding to be used in
57707   ** new database files created using this database handle. It is only
57708   ** useful if invoked immediately after the main database i
57709   */
57710   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
57711     static const struct EncName {
57712       char *zName;
57713       u8 enc;
57714     } encnames[] = {
57715       { "UTF-8",    SQLITE_UTF8        },
57716       { "UTF8",     SQLITE_UTF8        },
57717       { "UTF-16le", SQLITE_UTF16LE     },
57718       { "UTF16le",  SQLITE_UTF16LE     },
57719       { "UTF-16be", SQLITE_UTF16BE     },
57720       { "UTF16be",  SQLITE_UTF16BE     },
57721       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
57722       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
57723       { 0, 0 }
57724     };
57725     const struct EncName *pEnc;
57726     if( !zRight ){    /* "PRAGMA encoding" */
57727       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
57728       sqlite3VdbeSetNumCols(v, 1);
57729       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", P3_STATIC);
57730       sqlite3VdbeAddOp(v, OP_String8, 0, 0);
57731       for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
57732         if( pEnc->enc==ENC(pParse->db) ){
57733           sqlite3VdbeChangeP3(v, -1, pEnc->zName, P3_STATIC);
57734           break;
57735         }
57736       }
57737       sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
57738     }else{                        /* "PRAGMA encoding = XXX" */
57739       /* Only change the value of sqlite.enc if the database handle is not
57740       ** initialized. If the main database exists, the new sqlite.enc value
57741       ** will be overwritten when the schema is next loaded. If it does not
57742       ** already exists, it will be created to use the new encoding value.
57743       */
57744       if( 
57745         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
57746         DbHasProperty(db, 0, DB_Empty) 
57747       ){
57748         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
57749           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
57750             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
57751             break;
57752           }
57753         }
57754         if( !pEnc->zName ){
57755           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
57756         }
57757       }
57758     }
57759   }else
57760 #endif /* SQLITE_OMIT_UTF16 */
57761
57762 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
57763   /*
57764   **   PRAGMA [database.]schema_version
57765   **   PRAGMA [database.]schema_version = <integer>
57766   **
57767   **   PRAGMA [database.]user_version
57768   **   PRAGMA [database.]user_version = <integer>
57769   **
57770   ** The pragma's schema_version and user_version are used to set or get
57771   ** the value of the schema-version and user-version, respectively. Both
57772   ** the schema-version and the user-version are 32-bit signed integers
57773   ** stored in the database header.
57774   **
57775   ** The schema-cookie is usually only manipulated internally by SQLite. It
57776   ** is incremented by SQLite whenever the database schema is modified (by
57777   ** creating or dropping a table or index). The schema version is used by
57778   ** SQLite each time a query is executed to ensure that the internal cache
57779   ** of the schema used when compiling the SQL query matches the schema of
57780   ** the database against which the compiled query is actually executed.
57781   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
57782   ** the schema-version is potentially dangerous and may lead to program
57783   ** crashes or database corruption. Use with caution!
57784   **
57785   ** The user-version is not used internally by SQLite. It may be used by
57786   ** applications for any purpose.
57787   */
57788   if( sqlite3StrICmp(zLeft, "schema_version")==0 
57789    || sqlite3StrICmp(zLeft, "user_version")==0 
57790    || sqlite3StrICmp(zLeft, "freelist_count")==0 
57791   ){
57792
57793     int iCookie;   /* Cookie index. 0 for schema-cookie, 6 for user-cookie. */
57794     sqlite3VdbeUsesBtree(v, iDb);
57795     switch( zLeft[0] ){
57796       case 's': case 'S':
57797         iCookie = 0;
57798         break;
57799       case 'f': case 'F':
57800         iCookie = 1;
57801         iDb = (-1*(iDb+1));
57802         assert(iDb<=0);
57803         break;
57804       default:
57805         iCookie = 5;
57806         break;
57807     }
57808
57809     if( zRight && iDb>=0 ){
57810       /* Write the specified cookie value */
57811       static const VdbeOpList setCookie[] = {
57812         { OP_Transaction,    0,  1,  0},    /* 0 */
57813         { OP_Integer,        0,  0,  0},    /* 1 */
57814         { OP_SetCookie,      0,  0,  0},    /* 2 */
57815       };
57816       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
57817       sqlite3VdbeChangeP1(v, addr, iDb);
57818       sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
57819       sqlite3VdbeChangeP1(v, addr+2, iDb);
57820       sqlite3VdbeChangeP2(v, addr+2, iCookie);
57821     }else{
57822       /* Read the specified cookie value */
57823       static const VdbeOpList readCookie[] = {
57824         { OP_ReadCookie,      0,  0,  0},    /* 0 */
57825         { OP_Callback,        1,  0,  0}
57826       };
57827       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
57828       sqlite3VdbeChangeP1(v, addr, iDb);
57829       sqlite3VdbeChangeP2(v, addr, iCookie);
57830       sqlite3VdbeSetNumCols(v, 1);
57831       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, P3_TRANSIENT);
57832     }
57833   }else
57834 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
57835
57836 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
57837   /*
57838   ** Report the current state of file logs for all databases
57839   */
57840   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
57841     static const char *const azLockName[] = {
57842       "unlocked", "shared", "reserved", "pending", "exclusive"
57843     };
57844     int i;
57845     Vdbe *v = sqlite3GetVdbe(pParse);
57846     sqlite3VdbeSetNumCols(v, 2);
57847     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", P3_STATIC);
57848     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", P3_STATIC);
57849     for(i=0; i<db->nDb; i++){
57850       Btree *pBt;
57851       Pager *pPager;
57852       const char *zState = "unknown";
57853       int j;
57854       if( db->aDb[i].zName==0 ) continue;
57855       sqlite3VdbeOp3(v, OP_String8, 0, 0, db->aDb[i].zName, P3_STATIC);
57856       pBt = db->aDb[i].pBt;
57857       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
57858         zState = "closed";
57859       }else if( sqlite3_file_control(db, db->aDb[i].zName, 
57860                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
57861          zState = azLockName[j];
57862       }
57863       sqlite3VdbeOp3(v, OP_String8, 0, 0, zState, P3_STATIC);
57864       sqlite3VdbeAddOp(v, OP_Callback, 2, 0);
57865     }
57866   }else
57867 #endif
57868
57869 #ifdef SQLITE_SSE
57870   /*
57871   ** Check to see if the sqlite_statements table exists.  Create it
57872   ** if it does not.
57873   */
57874   if( sqlite3StrICmp(zLeft, "create_sqlite_statement_table")==0 ){
57875     extern int sqlite3CreateStatementsTable(Parse*);
57876     sqlite3CreateStatementsTable(pParse);
57877   }else
57878 #endif
57879
57880 #if SQLITE_HAS_CODEC
57881   if( sqlite3StrICmp(zLeft, "key")==0 ){
57882     sqlite3_key(db, zRight, strlen(zRight));
57883   }else
57884 #endif
57885 #if SQLITE_HAS_CODEC || defined(SQLITE_ENABLE_CEROD)
57886   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
57887 #if SQLITE_HAS_CODEC
57888     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
57889       extern void sqlite3_activate_see(const char*);
57890       sqlite3_activate_see(&zRight[4]);
57891     }
57892 #endif
57893 #ifdef SQLITE_ENABLE_CEROD
57894     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
57895       extern void sqlite3_activate_cerod(const char*);
57896       sqlite3_activate_cerod(&zRight[6]);
57897     }
57898 #endif
57899   }
57900 #endif
57901
57902   {}
57903
57904   if( v ){
57905     /* Code an OP_Expire at the end of each PRAGMA program to cause
57906     ** the VDBE implementing the pragma to expire. Most (all?) pragmas
57907     ** are only valid for a single execution.
57908     */
57909     sqlite3VdbeAddOp(v, OP_Expire, 1, 0);
57910
57911     /*
57912     ** Reset the safety level, in case the fullfsync flag or synchronous
57913     ** setting changed.
57914     */
57915 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
57916     if( db->autoCommit ){
57917       sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
57918                  (db->flags&SQLITE_FullFSync)!=0);
57919     }
57920 #endif
57921   }
57922 pragma_out:
57923   sqlite3_free(zLeft);
57924   sqlite3_free(zRight);
57925 }
57926
57927 #endif /* SQLITE_OMIT_PRAGMA || SQLITE_OMIT_PARSER */
57928
57929 /************** End of pragma.c **********************************************/
57930 /************** Begin file prepare.c *****************************************/
57931 /*
57932 ** 2005 May 25
57933 **
57934 ** The author disclaims copyright to this source code.  In place of
57935 ** a legal notice, here is a blessing:
57936 **
57937 **    May you do good and not evil.
57938 **    May you find forgiveness for yourself and forgive others.
57939 **    May you share freely, never taking more than you give.
57940 **
57941 *************************************************************************
57942 ** This file contains the implementation of the sqlite3_prepare()
57943 ** interface, and routines that contribute to loading the database schema
57944 ** from disk.
57945 **
57946 ** $Id: prepare.c,v 1.66 2007/12/13 21:54:11 drh Exp $
57947 */
57948
57949 /*
57950 ** Fill the InitData structure with an error message that indicates
57951 ** that the database is corrupt.
57952 */
57953 static void corruptSchema(InitData *pData, const char *zExtra){
57954   if( !pData->db->mallocFailed ){
57955     sqlite3SetString(pData->pzErrMsg, "malformed database schema",
57956        zExtra!=0 && zExtra[0]!=0 ? " - " : (char*)0, zExtra, (char*)0);
57957   }
57958   pData->rc = SQLITE_CORRUPT;
57959 }
57960
57961 /*
57962 ** This is the callback routine for the code that initializes the
57963 ** database.  See sqlite3Init() below for additional information.
57964 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
57965 **
57966 ** Each callback contains the following information:
57967 **
57968 **     argv[0] = name of thing being created
57969 **     argv[1] = root page number for table or index. 0 for trigger or view.
57970 **     argv[2] = SQL text for the CREATE statement.
57971 **
57972 */
57973 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **azColName){
57974   InitData *pData = (InitData*)pInit;
57975   sqlite3 *db = pData->db;
57976   int iDb = pData->iDb;
57977
57978   assert( sqlite3_mutex_held(db->mutex) );
57979   pData->rc = SQLITE_OK;
57980   DbClearProperty(db, iDb, DB_Empty);
57981   if( db->mallocFailed ){
57982     corruptSchema(pData, 0);
57983     return SQLITE_NOMEM;
57984   }
57985
57986   assert( argc==3 );
57987   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
57988   if( argv[1]==0 ){
57989     corruptSchema(pData, 0);
57990     return 1;
57991   }
57992   assert( iDb>=0 && iDb<db->nDb );
57993   if( argv[2] && argv[2][0] ){
57994     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
57995     ** But because db->init.busy is set to 1, no VDBE code is generated
57996     ** or executed.  All the parser does is build the internal data
57997     ** structures that describe the table, index, or view.
57998     */
57999     char *zErr;
58000     int rc;
58001     assert( db->init.busy );
58002     db->init.iDb = iDb;
58003     db->init.newTnum = atoi(argv[1]);
58004     rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
58005     db->init.iDb = 0;
58006     assert( rc!=SQLITE_OK || zErr==0 );
58007     if( SQLITE_OK!=rc ){
58008       pData->rc = rc;
58009       if( rc==SQLITE_NOMEM ){
58010         db->mallocFailed = 1;
58011       }else if( rc!=SQLITE_INTERRUPT ){
58012         corruptSchema(pData, zErr);
58013       }
58014       sqlite3_free(zErr);
58015       return 1;
58016     }
58017   }else{
58018     /* If the SQL column is blank it means this is an index that
58019     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
58020     ** constraint for a CREATE TABLE.  The index should have already
58021     ** been created when we processed the CREATE TABLE.  All we have
58022     ** to do here is record the root page number for that index.
58023     */
58024     Index *pIndex;
58025     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
58026     if( pIndex==0 || pIndex->tnum!=0 ){
58027       /* This can occur if there exists an index on a TEMP table which
58028       ** has the same name as another index on a permanent index.  Since
58029       ** the permanent table is hidden by the TEMP table, we can also
58030       ** safely ignore the index on the permanent table.
58031       */
58032       /* Do Nothing */;
58033     }else{
58034       pIndex->tnum = atoi(argv[1]);
58035     }
58036   }
58037   return 0;
58038 }
58039
58040 /*
58041 ** Attempt to read the database schema and initialize internal
58042 ** data structures for a single database file.  The index of the
58043 ** database file is given by iDb.  iDb==0 is used for the main
58044 ** database.  iDb==1 should never be used.  iDb>=2 is used for
58045 ** auxiliary databases.  Return one of the SQLITE_ error codes to
58046 ** indicate success or failure.
58047 */
58048 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
58049   int rc;
58050   BtCursor *curMain;
58051   int size;
58052   Table *pTab;
58053   Db *pDb;
58054   char const *azArg[4];
58055   int meta[10];
58056   InitData initData;
58057   char const *zMasterSchema;
58058   char const *zMasterName = SCHEMA_TABLE(iDb);
58059
58060   /*
58061   ** The master database table has a structure like this
58062   */
58063   static const char master_schema[] = 
58064      "CREATE TABLE sqlite_master(\n"
58065      "  type text,\n"
58066      "  name text,\n"
58067      "  tbl_name text,\n"
58068      "  rootpage integer,\n"
58069      "  sql text\n"
58070      ")"
58071   ;
58072 #ifndef SQLITE_OMIT_TEMPDB
58073   static const char temp_master_schema[] = 
58074      "CREATE TEMP TABLE sqlite_temp_master(\n"
58075      "  type text,\n"
58076      "  name text,\n"
58077      "  tbl_name text,\n"
58078      "  rootpage integer,\n"
58079      "  sql text\n"
58080      ")"
58081   ;
58082 #else
58083   #define temp_master_schema 0
58084 #endif
58085
58086   assert( iDb>=0 && iDb<db->nDb );
58087   assert( db->aDb[iDb].pSchema );
58088   assert( sqlite3_mutex_held(db->mutex) );
58089
58090   /* zMasterSchema and zInitScript are set to point at the master schema
58091   ** and initialisation script appropriate for the database being
58092   ** initialised. zMasterName is the name of the master table.
58093   */
58094   if( !OMIT_TEMPDB && iDb==1 ){
58095     zMasterSchema = temp_master_schema;
58096   }else{
58097     zMasterSchema = master_schema;
58098   }
58099   zMasterName = SCHEMA_TABLE(iDb);
58100
58101   /* Construct the schema tables.  */
58102   sqlite3SafetyOff(db);
58103   azArg[0] = zMasterName;
58104   azArg[1] = "1";
58105   azArg[2] = zMasterSchema;
58106   azArg[3] = 0;
58107   initData.db = db;
58108   initData.iDb = iDb;
58109   initData.pzErrMsg = pzErrMsg;
58110   rc = sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
58111   if( rc ){
58112     sqlite3SafetyOn(db);
58113     rc = initData.rc;
58114     goto error_out;
58115   }
58116   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
58117   if( pTab ){
58118     pTab->readOnly = 1;
58119   }
58120   sqlite3SafetyOn(db);
58121
58122   /* Create a cursor to hold the database open
58123   */
58124   pDb = &db->aDb[iDb];
58125   if( pDb->pBt==0 ){
58126     if( !OMIT_TEMPDB && iDb==1 ){
58127       DbSetProperty(db, 1, DB_SchemaLoaded);
58128     }
58129     return SQLITE_OK;
58130   }
58131   sqlite3BtreeEnter(pDb->pBt);
58132   rc = sqlite3BtreeCursor(pDb->pBt, MASTER_ROOT, 0, 0, 0, &curMain);
58133   if( rc!=SQLITE_OK && rc!=SQLITE_EMPTY ){
58134     sqlite3SetString(pzErrMsg, sqlite3ErrStr(rc), (char*)0);
58135     sqlite3BtreeLeave(pDb->pBt);
58136     goto error_out;
58137   }
58138
58139   /* Get the database meta information.
58140   **
58141   ** Meta values are as follows:
58142   **    meta[0]   Schema cookie.  Changes with each schema change.
58143   **    meta[1]   File format of schema layer.
58144   **    meta[2]   Size of the page cache.
58145   **    meta[3]   Use freelist if 0.  Autovacuum if greater than zero.
58146   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
58147   **    meta[5]   The user cookie. Used by the application.
58148   **    meta[6]   Incremental-vacuum flag.
58149   **    meta[7]
58150   **    meta[8]
58151   **    meta[9]
58152   **
58153   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
58154   ** the possible values of meta[4].
58155   */
58156   if( rc==SQLITE_OK ){
58157     int i;
58158     for(i=0; rc==SQLITE_OK && i<sizeof(meta)/sizeof(meta[0]); i++){
58159       rc = sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
58160     }
58161     if( rc ){
58162       sqlite3SetString(pzErrMsg, sqlite3ErrStr(rc), (char*)0);
58163       sqlite3BtreeCloseCursor(curMain);
58164       sqlite3BtreeLeave(pDb->pBt);
58165       goto error_out;
58166     }
58167   }else{
58168     memset(meta, 0, sizeof(meta));
58169   }
58170   pDb->pSchema->schema_cookie = meta[0];
58171
58172   /* If opening a non-empty database, check the text encoding. For the
58173   ** main database, set sqlite3.enc to the encoding of the main database.
58174   ** For an attached db, it is an error if the encoding is not the same
58175   ** as sqlite3.enc.
58176   */
58177   if( meta[4] ){  /* text encoding */
58178     if( iDb==0 ){
58179       /* If opening the main database, set ENC(db). */
58180       ENC(db) = (u8)meta[4];
58181       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
58182     }else{
58183       /* If opening an attached database, the encoding much match ENC(db) */
58184       if( meta[4]!=ENC(db) ){
58185         sqlite3BtreeCloseCursor(curMain);
58186         sqlite3SetString(pzErrMsg, "attached databases must use the same"
58187             " text encoding as main database", (char*)0);
58188         sqlite3BtreeLeave(pDb->pBt);
58189         return SQLITE_ERROR;
58190       }
58191     }
58192   }else{
58193     DbSetProperty(db, iDb, DB_Empty);
58194   }
58195   pDb->pSchema->enc = ENC(db);
58196
58197   size = meta[2];
58198   if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
58199   pDb->pSchema->cache_size = size;
58200   sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
58201
58202   /*
58203   ** file_format==1    Version 3.0.0.
58204   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
58205   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
58206   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
58207   */
58208   pDb->pSchema->file_format = meta[1];
58209   if( pDb->pSchema->file_format==0 ){
58210     pDb->pSchema->file_format = 1;
58211   }
58212   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
58213     sqlite3BtreeCloseCursor(curMain);
58214     sqlite3SetString(pzErrMsg, "unsupported file format", (char*)0);
58215     sqlite3BtreeLeave(pDb->pBt);
58216     return SQLITE_ERROR;
58217   }
58218
58219   /* Ticket #2804:  When we open a database in the newer file format,
58220   ** clear the legacy_file_format pragma flag so that a VACUUM will
58221   ** not downgrade the database and thus invalidate any descending
58222   ** indices that the user might have created.
58223   */
58224   if( iDb==0 && meta[1]>=4 ){
58225     db->flags &= ~SQLITE_LegacyFileFmt;
58226   }
58227
58228   /* Read the schema information out of the schema tables
58229   */
58230   assert( db->init.busy );
58231   if( rc==SQLITE_EMPTY ){
58232     /* For an empty database, there is nothing to read */
58233     rc = SQLITE_OK;
58234   }else{
58235     char *zSql;
58236     zSql = sqlite3MPrintf(db, 
58237         "SELECT name, rootpage, sql FROM '%q'.%s",
58238         db->aDb[iDb].zName, zMasterName);
58239     sqlite3SafetyOff(db);
58240 #ifndef SQLITE_OMIT_AUTHORIZATION
58241     {
58242       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
58243       xAuth = db->xAuth;
58244       db->xAuth = 0;
58245 #endif
58246       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
58247 #ifndef SQLITE_OMIT_AUTHORIZATION
58248       db->xAuth = xAuth;
58249     }
58250 #endif
58251     if( rc==SQLITE_ABORT ) rc = initData.rc;
58252     sqlite3SafetyOn(db);
58253     sqlite3_free(zSql);
58254 #ifndef SQLITE_OMIT_ANALYZE
58255     if( rc==SQLITE_OK ){
58256       sqlite3AnalysisLoad(db, iDb);
58257     }
58258 #endif
58259     sqlite3BtreeCloseCursor(curMain);
58260   }
58261   if( db->mallocFailed ){
58262     /* sqlite3SetString(pzErrMsg, "out of memory", (char*)0); */
58263     rc = SQLITE_NOMEM;
58264     sqlite3ResetInternalSchema(db, 0);
58265   }
58266   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
58267     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
58268     ** the schema loaded, even if errors occured. In this situation the 
58269     ** current sqlite3_prepare() operation will fail, but the following one
58270     ** will attempt to compile the supplied statement against whatever subset
58271     ** of the schema was loaded before the error occured. The primary
58272     ** purpose of this is to allow access to the sqlite_master table
58273     ** even when its contents have been corrupted.
58274     */
58275     DbSetProperty(db, iDb, DB_SchemaLoaded);
58276     rc = SQLITE_OK;
58277   }
58278   sqlite3BtreeLeave(pDb->pBt);
58279
58280 error_out:
58281   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
58282     db->mallocFailed = 1;
58283   }
58284   return rc;
58285 }
58286
58287 /*
58288 ** Initialize all database files - the main database file, the file
58289 ** used to store temporary tables, and any additional database files
58290 ** created using ATTACH statements.  Return a success code.  If an
58291 ** error occurs, write an error message into *pzErrMsg.
58292 **
58293 ** After a database is initialized, the DB_SchemaLoaded bit is set
58294 ** bit is set in the flags field of the Db structure. If the database
58295 ** file was of zero-length, then the DB_Empty flag is also set.
58296 */
58297 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
58298   int i, rc;
58299   int commit_internal = !(db->flags&SQLITE_InternChanges);
58300   
58301   assert( sqlite3_mutex_held(db->mutex) );
58302   if( db->init.busy ) return SQLITE_OK;
58303   rc = SQLITE_OK;
58304   db->init.busy = 1;
58305   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
58306     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
58307     rc = sqlite3InitOne(db, i, pzErrMsg);
58308     if( rc ){
58309       sqlite3ResetInternalSchema(db, i);
58310     }
58311   }
58312
58313   /* Once all the other databases have been initialised, load the schema
58314   ** for the TEMP database. This is loaded last, as the TEMP database
58315   ** schema may contain references to objects in other databases.
58316   */
58317 #ifndef SQLITE_OMIT_TEMPDB
58318   if( rc==SQLITE_OK && db->nDb>1 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
58319     rc = sqlite3InitOne(db, 1, pzErrMsg);
58320     if( rc ){
58321       sqlite3ResetInternalSchema(db, 1);
58322     }
58323   }
58324 #endif
58325
58326   db->init.busy = 0;
58327   if( rc==SQLITE_OK && commit_internal ){
58328     sqlite3CommitInternalChanges(db);
58329   }
58330
58331   return rc; 
58332 }
58333
58334 /*
58335 ** This routine is a no-op if the database schema is already initialised.
58336 ** Otherwise, the schema is loaded. An error code is returned.
58337 */
58338 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
58339   int rc = SQLITE_OK;
58340   sqlite3 *db = pParse->db;
58341   assert( sqlite3_mutex_held(db->mutex) );
58342   if( !db->init.busy ){
58343     rc = sqlite3Init(db, &pParse->zErrMsg);
58344   }
58345   if( rc!=SQLITE_OK ){
58346     pParse->rc = rc;
58347     pParse->nErr++;
58348   }
58349   return rc;
58350 }
58351
58352
58353 /*
58354 ** Check schema cookies in all databases.  If any cookie is out
58355 ** of date, return 0.  If all schema cookies are current, return 1.
58356 */
58357 static int schemaIsValid(sqlite3 *db){
58358   int iDb;
58359   int rc;
58360   BtCursor *curTemp;
58361   int cookie;
58362   int allOk = 1;
58363
58364   assert( sqlite3_mutex_held(db->mutex) );
58365   for(iDb=0; allOk && iDb<db->nDb; iDb++){
58366     Btree *pBt;
58367     pBt = db->aDb[iDb].pBt;
58368     if( pBt==0 ) continue;
58369     rc = sqlite3BtreeCursor(pBt, MASTER_ROOT, 0, 0, 0, &curTemp);
58370     if( rc==SQLITE_OK ){
58371       rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&cookie);
58372       if( rc==SQLITE_OK && cookie!=db->aDb[iDb].pSchema->schema_cookie ){
58373         allOk = 0;
58374       }
58375       sqlite3BtreeCloseCursor(curTemp);
58376     }
58377     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
58378       db->mallocFailed = 1;
58379     }
58380   }
58381   return allOk;
58382 }
58383
58384 /*
58385 ** Convert a schema pointer into the iDb index that indicates
58386 ** which database file in db->aDb[] the schema refers to.
58387 **
58388 ** If the same database is attached more than once, the first
58389 ** attached database is returned.
58390 */
58391 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
58392   int i = -1000000;
58393
58394   /* If pSchema is NULL, then return -1000000. This happens when code in 
58395   ** expr.c is trying to resolve a reference to a transient table (i.e. one
58396   ** created by a sub-select). In this case the return value of this 
58397   ** function should never be used.
58398   **
58399   ** We return -1000000 instead of the more usual -1 simply because using
58400   ** -1000000 as incorrectly using -1000000 index into db->aDb[] is much 
58401   ** more likely to cause a segfault than -1 (of course there are assert()
58402   ** statements too, but it never hurts to play the odds).
58403   */
58404   assert( sqlite3_mutex_held(db->mutex) );
58405   if( pSchema ){
58406     for(i=0; i<db->nDb; i++){
58407       if( db->aDb[i].pSchema==pSchema ){
58408         break;
58409       }
58410     }
58411     assert( i>=0 &&i>=0 &&  i<db->nDb );
58412   }
58413   return i;
58414 }
58415
58416 /*
58417 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
58418 */
58419 SQLITE_PRIVATE int sqlite3Prepare(
58420   sqlite3 *db,              /* Database handle. */
58421   const char *zSql,         /* UTF-8 encoded SQL statement. */
58422   int nBytes,               /* Length of zSql in bytes. */
58423   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
58424   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
58425   const char **pzTail       /* OUT: End of parsed string */
58426 ){
58427   Parse sParse;
58428   char *zErrMsg = 0;
58429   int rc = SQLITE_OK;
58430   int i;
58431
58432   assert( ppStmt );
58433   *ppStmt = 0;
58434   if( sqlite3SafetyOn(db) ){
58435     return SQLITE_MISUSE;
58436   }
58437   assert( !db->mallocFailed );
58438   assert( sqlite3_mutex_held(db->mutex) );
58439
58440   /* If any attached database schemas are locked, do not proceed with
58441   ** compilation. Instead return SQLITE_LOCKED immediately.
58442   */
58443   for(i=0; i<db->nDb; i++) {
58444     Btree *pBt = db->aDb[i].pBt;
58445     if( pBt ){
58446       int rc;
58447       rc = sqlite3BtreeSchemaLocked(pBt);
58448       if( rc ){
58449         const char *zDb = db->aDb[i].zName;
58450         sqlite3Error(db, SQLITE_LOCKED, "database schema is locked: %s", zDb);
58451         sqlite3SafetyOff(db);
58452         return SQLITE_LOCKED;
58453       }
58454     }
58455   }
58456   
58457   memset(&sParse, 0, sizeof(sParse));
58458   sParse.db = db;
58459   if( nBytes>=0 && zSql[nBytes]!=0 ){
58460     char *zSqlCopy;
58461     if( nBytes>SQLITE_MAX_SQL_LENGTH ){
58462       return SQLITE_TOOBIG;
58463     }
58464     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
58465     if( zSqlCopy ){
58466       sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
58467       sqlite3_free(zSqlCopy);
58468     }
58469     sParse.zTail = &zSql[nBytes];
58470   }else{
58471     sqlite3RunParser(&sParse, zSql, &zErrMsg);
58472   }
58473
58474   if( db->mallocFailed ){
58475     sParse.rc = SQLITE_NOMEM;
58476   }
58477   if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
58478   if( sParse.checkSchema && !schemaIsValid(db) ){
58479     sParse.rc = SQLITE_SCHEMA;
58480   }
58481   if( sParse.rc==SQLITE_SCHEMA ){
58482     sqlite3ResetInternalSchema(db, 0);
58483   }
58484   if( db->mallocFailed ){
58485     sParse.rc = SQLITE_NOMEM;
58486   }
58487   if( pzTail ){
58488     *pzTail = sParse.zTail;
58489   }
58490   rc = sParse.rc;
58491
58492 #ifndef SQLITE_OMIT_EXPLAIN
58493   if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
58494     if( sParse.explain==2 ){
58495       sqlite3VdbeSetNumCols(sParse.pVdbe, 3);
58496       sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "order", P3_STATIC);
58497       sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "from", P3_STATIC);
58498       sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "detail", P3_STATIC);
58499     }else{
58500       sqlite3VdbeSetNumCols(sParse.pVdbe, 5);
58501       sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "addr", P3_STATIC);
58502       sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "opcode", P3_STATIC);
58503       sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "p1", P3_STATIC);
58504       sqlite3VdbeSetColName(sParse.pVdbe, 3, COLNAME_NAME, "p2", P3_STATIC);
58505       sqlite3VdbeSetColName(sParse.pVdbe, 4, COLNAME_NAME, "p3", P3_STATIC);
58506     }
58507   }
58508 #endif
58509
58510   if( sqlite3SafetyOff(db) ){
58511     rc = SQLITE_MISUSE;
58512   }
58513
58514   if( saveSqlFlag ){
58515     sqlite3VdbeSetSql(sParse.pVdbe, zSql, sParse.zTail - zSql);
58516   }
58517   if( rc!=SQLITE_OK || db->mallocFailed ){
58518     sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
58519     assert(!(*ppStmt));
58520   }else{
58521     *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
58522   }
58523
58524   if( zErrMsg ){
58525     sqlite3Error(db, rc, "%s", zErrMsg);
58526     sqlite3_free(zErrMsg);
58527   }else{
58528     sqlite3Error(db, rc, 0);
58529   }
58530
58531   rc = sqlite3ApiExit(db, rc);
58532   /* sqlite3ReleaseThreadData(); */
58533   assert( (rc&db->errMask)==rc );
58534   return rc;
58535 }
58536 static int sqlite3LockAndPrepare(
58537   sqlite3 *db,              /* Database handle. */
58538   const char *zSql,         /* UTF-8 encoded SQL statement. */
58539   int nBytes,               /* Length of zSql in bytes. */
58540   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
58541   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
58542   const char **pzTail       /* OUT: End of parsed string */
58543 ){
58544   int rc;
58545   if( sqlite3SafetyCheck(db) ){
58546     return SQLITE_MISUSE;
58547   }
58548   sqlite3_mutex_enter(db->mutex);
58549   sqlite3BtreeEnterAll(db);
58550   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, ppStmt, pzTail);
58551   sqlite3BtreeLeaveAll(db);
58552   sqlite3_mutex_leave(db->mutex);
58553   return rc;
58554 }
58555
58556 /*
58557 ** Rerun the compilation of a statement after a schema change.
58558 ** Return true if the statement was recompiled successfully.
58559 ** Return false if there is an error of some kind.
58560 */
58561 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
58562   int rc;
58563   sqlite3_stmt *pNew;
58564   const char *zSql;
58565   sqlite3 *db;
58566
58567   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
58568   zSql = sqlite3_sql((sqlite3_stmt *)p);
58569   if( zSql==0 ){
58570     return 0;
58571   }
58572   db = sqlite3VdbeDb(p);
58573   assert( sqlite3_mutex_held(db->mutex) );
58574   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, &pNew, 0);
58575   if( rc ){
58576     if( rc==SQLITE_NOMEM ){
58577       db->mallocFailed = 1;
58578     }
58579     assert( pNew==0 );
58580     return 0;
58581   }else{
58582     assert( pNew!=0 );
58583   }
58584   sqlite3VdbeSwap((Vdbe*)pNew, p);
58585   sqlite3_transfer_bindings(pNew, (sqlite3_stmt*)p);
58586   sqlite3VdbeResetStepResult((Vdbe*)pNew);
58587   sqlite3VdbeFinalize((Vdbe*)pNew);
58588   return 1;
58589 }
58590
58591
58592 /*
58593 ** Two versions of the official API.  Legacy and new use.  In the legacy
58594 ** version, the original SQL text is not saved in the prepared statement
58595 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
58596 ** sqlite3_step().  In the new version, the original SQL text is retained
58597 ** and the statement is automatically recompiled if an schema change
58598 ** occurs.
58599 */
58600 SQLITE_API int sqlite3_prepare(
58601   sqlite3 *db,              /* Database handle. */
58602   const char *zSql,         /* UTF-8 encoded SQL statement. */
58603   int nBytes,               /* Length of zSql in bytes. */
58604   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
58605   const char **pzTail       /* OUT: End of parsed string */
58606 ){
58607   return sqlite3LockAndPrepare(db,zSql,nBytes,0,ppStmt,pzTail);
58608 }
58609 SQLITE_API int sqlite3_prepare_v2(
58610   sqlite3 *db,              /* Database handle. */
58611   const char *zSql,         /* UTF-8 encoded SQL statement. */
58612   int nBytes,               /* Length of zSql in bytes. */
58613   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
58614   const char **pzTail       /* OUT: End of parsed string */
58615 ){
58616   return sqlite3LockAndPrepare(db,zSql,nBytes,1,ppStmt,pzTail);
58617 }
58618
58619
58620 #ifndef SQLITE_OMIT_UTF16
58621 /*
58622 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
58623 */
58624 static int sqlite3Prepare16(
58625   sqlite3 *db,              /* Database handle. */ 
58626   const void *zSql,         /* UTF-8 encoded SQL statement. */
58627   int nBytes,               /* Length of zSql in bytes. */
58628   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
58629   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
58630   const void **pzTail       /* OUT: End of parsed string */
58631 ){
58632   /* This function currently works by first transforming the UTF-16
58633   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
58634   ** tricky bit is figuring out the pointer to return in *pzTail.
58635   */
58636   char *zSql8;
58637   const char *zTail8 = 0;
58638   int rc = SQLITE_OK;
58639
58640   if( sqlite3SafetyCheck(db) ){
58641     return SQLITE_MISUSE;
58642   }
58643   sqlite3_mutex_enter(db->mutex);
58644   zSql8 = sqlite3Utf16to8(db, zSql, nBytes);
58645   if( zSql8 ){
58646     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, ppStmt, &zTail8);
58647   }
58648
58649   if( zTail8 && pzTail ){
58650     /* If sqlite3_prepare returns a tail pointer, we calculate the
58651     ** equivalent pointer into the UTF-16 string by counting the unicode
58652     ** characters between zSql8 and zTail8, and then returning a pointer
58653     ** the same number of characters into the UTF-16 string.
58654     */
58655     int chars_parsed = sqlite3Utf8CharLen(zSql8, zTail8-zSql8);
58656     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
58657   }
58658   sqlite3_free(zSql8); 
58659   rc = sqlite3ApiExit(db, rc);
58660   sqlite3_mutex_leave(db->mutex);
58661   return rc;
58662 }
58663
58664 /*
58665 ** Two versions of the official API.  Legacy and new use.  In the legacy
58666 ** version, the original SQL text is not saved in the prepared statement
58667 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
58668 ** sqlite3_step().  In the new version, the original SQL text is retained
58669 ** and the statement is automatically recompiled if an schema change
58670 ** occurs.
58671 */
58672 SQLITE_API int sqlite3_prepare16(
58673   sqlite3 *db,              /* Database handle. */ 
58674   const void *zSql,         /* UTF-8 encoded SQL statement. */
58675   int nBytes,               /* Length of zSql in bytes. */
58676   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
58677   const void **pzTail       /* OUT: End of parsed string */
58678 ){
58679   return sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
58680 }
58681 SQLITE_API int sqlite3_prepare16_v2(
58682   sqlite3 *db,              /* Database handle. */ 
58683   const void *zSql,         /* UTF-8 encoded SQL statement. */
58684   int nBytes,               /* Length of zSql in bytes. */
58685   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
58686   const void **pzTail       /* OUT: End of parsed string */
58687 ){
58688   return sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
58689 }
58690
58691 #endif /* SQLITE_OMIT_UTF16 */
58692
58693 /************** End of prepare.c *********************************************/
58694 /************** Begin file select.c ******************************************/
58695 /*
58696 ** 2001 September 15
58697 **
58698 ** The author disclaims copyright to this source code.  In place of
58699 ** a legal notice, here is a blessing:
58700 **
58701 **    May you do good and not evil.
58702 **    May you find forgiveness for yourself and forgive others.
58703 **    May you share freely, never taking more than you give.
58704 **
58705 *************************************************************************
58706 ** This file contains C code routines that are called by the parser
58707 ** to handle SELECT statements in SQLite.
58708 **
58709 ** $Id: select.c,v 1.372 2007/12/14 17:24:40 drh Exp $
58710 */
58711
58712
58713 /*
58714 ** Delete all the content of a Select structure but do not deallocate
58715 ** the select structure itself.
58716 */
58717 static void clearSelect(Select *p){
58718   sqlite3ExprListDelete(p->pEList);
58719   sqlite3SrcListDelete(p->pSrc);
58720   sqlite3ExprDelete(p->pWhere);
58721   sqlite3ExprListDelete(p->pGroupBy);
58722   sqlite3ExprDelete(p->pHaving);
58723   sqlite3ExprListDelete(p->pOrderBy);
58724   sqlite3SelectDelete(p->pPrior);
58725   sqlite3ExprDelete(p->pLimit);
58726   sqlite3ExprDelete(p->pOffset);
58727 }
58728
58729
58730 /*
58731 ** Allocate a new Select structure and return a pointer to that
58732 ** structure.
58733 */
58734 SQLITE_PRIVATE Select *sqlite3SelectNew(
58735   Parse *pParse,        /* Parsing context */
58736   ExprList *pEList,     /* which columns to include in the result */
58737   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
58738   Expr *pWhere,         /* the WHERE clause */
58739   ExprList *pGroupBy,   /* the GROUP BY clause */
58740   Expr *pHaving,        /* the HAVING clause */
58741   ExprList *pOrderBy,   /* the ORDER BY clause */
58742   int isDistinct,       /* true if the DISTINCT keyword is present */
58743   Expr *pLimit,         /* LIMIT value.  NULL means not used */
58744   Expr *pOffset         /* OFFSET value.  NULL means no offset */
58745 ){
58746   Select *pNew;
58747   Select standin;
58748   sqlite3 *db = pParse->db;
58749   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
58750   assert( !pOffset || pLimit );   /* Can't have OFFSET without LIMIT. */
58751   if( pNew==0 ){
58752     pNew = &standin;
58753     memset(pNew, 0, sizeof(*pNew));
58754   }
58755   if( pEList==0 ){
58756     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0,0,0), 0);
58757   }
58758   pNew->pEList = pEList;
58759   pNew->pSrc = pSrc;
58760   pNew->pWhere = pWhere;
58761   pNew->pGroupBy = pGroupBy;
58762   pNew->pHaving = pHaving;
58763   pNew->pOrderBy = pOrderBy;
58764   pNew->isDistinct = isDistinct;
58765   pNew->op = TK_SELECT;
58766   assert( pOffset==0 || pLimit!=0 );
58767   pNew->pLimit = pLimit;
58768   pNew->pOffset = pOffset;
58769   pNew->iLimit = -1;
58770   pNew->iOffset = -1;
58771   pNew->addrOpenEphm[0] = -1;
58772   pNew->addrOpenEphm[1] = -1;
58773   pNew->addrOpenEphm[2] = -1;
58774   if( pNew==&standin) {
58775     clearSelect(pNew);
58776     pNew = 0;
58777   }
58778   return pNew;
58779 }
58780
58781 /*
58782 ** Delete the given Select structure and all of its substructures.
58783 */
58784 SQLITE_PRIVATE void sqlite3SelectDelete(Select *p){
58785   if( p ){
58786     clearSelect(p);
58787     sqlite3_free(p);
58788   }
58789 }
58790
58791 /*
58792 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
58793 ** type of join.  Return an integer constant that expresses that type
58794 ** in terms of the following bit values:
58795 **
58796 **     JT_INNER
58797 **     JT_CROSS
58798 **     JT_OUTER
58799 **     JT_NATURAL
58800 **     JT_LEFT
58801 **     JT_RIGHT
58802 **
58803 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
58804 **
58805 ** If an illegal or unsupported join type is seen, then still return
58806 ** a join type, but put an error in the pParse structure.
58807 */
58808 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
58809   int jointype = 0;
58810   Token *apAll[3];
58811   Token *p;
58812   static const struct {
58813     const char zKeyword[8];
58814     u8 nChar;
58815     u8 code;
58816   } keywords[] = {
58817     { "natural", 7, JT_NATURAL },
58818     { "left",    4, JT_LEFT|JT_OUTER },
58819     { "right",   5, JT_RIGHT|JT_OUTER },
58820     { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
58821     { "outer",   5, JT_OUTER },
58822     { "inner",   5, JT_INNER },
58823     { "cross",   5, JT_INNER|JT_CROSS },
58824   };
58825   int i, j;
58826   apAll[0] = pA;
58827   apAll[1] = pB;
58828   apAll[2] = pC;
58829   for(i=0; i<3 && apAll[i]; i++){
58830     p = apAll[i];
58831     for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
58832       if( p->n==keywords[j].nChar 
58833           && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){
58834         jointype |= keywords[j].code;
58835         break;
58836       }
58837     }
58838     if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
58839       jointype |= JT_ERROR;
58840       break;
58841     }
58842   }
58843   if(
58844      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
58845      (jointype & JT_ERROR)!=0
58846   ){
58847     const char *zSp1 = " ";
58848     const char *zSp2 = " ";
58849     if( pB==0 ){ zSp1++; }
58850     if( pC==0 ){ zSp2++; }
58851     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
58852        "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
58853     jointype = JT_INNER;
58854   }else if( jointype & JT_RIGHT ){
58855     sqlite3ErrorMsg(pParse, 
58856       "RIGHT and FULL OUTER JOINs are not currently supported");
58857     jointype = JT_INNER;
58858   }
58859   return jointype;
58860 }
58861
58862 /*
58863 ** Return the index of a column in a table.  Return -1 if the column
58864 ** is not contained in the table.
58865 */
58866 static int columnIndex(Table *pTab, const char *zCol){
58867   int i;
58868   for(i=0; i<pTab->nCol; i++){
58869     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
58870   }
58871   return -1;
58872 }
58873
58874 /*
58875 ** Set the value of a token to a '\000'-terminated string.
58876 */
58877 static void setToken(Token *p, const char *z){
58878   p->z = (u8*)z;
58879   p->n = z ? strlen(z) : 0;
58880   p->dyn = 0;
58881 }
58882
58883 /*
58884 ** Set the token to the double-quoted and escaped version of the string pointed
58885 ** to by z. For example;
58886 **
58887 **    {a"bc}  ->  {"a""bc"}
58888 */
58889 static void setQuotedToken(Parse *pParse, Token *p, const char *z){
58890   p->z = (u8 *)sqlite3MPrintf(0, "\"%w\"", z);
58891   p->dyn = 1;
58892   if( p->z ){
58893     p->n = strlen((char *)p->z);
58894   }else{
58895     pParse->db->mallocFailed = 1;
58896   }
58897 }
58898
58899 /*
58900 ** Create an expression node for an identifier with the name of zName
58901 */
58902 SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){
58903   Token dummy;
58904   setToken(&dummy, zName);
58905   return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy);
58906 }
58907
58908
58909 /*
58910 ** Add a term to the WHERE expression in *ppExpr that requires the
58911 ** zCol column to be equal in the two tables pTab1 and pTab2.
58912 */
58913 static void addWhereTerm(
58914   Parse *pParse,           /* Parsing context */
58915   const char *zCol,        /* Name of the column */
58916   const Table *pTab1,      /* First table */
58917   const char *zAlias1,     /* Alias for first table.  May be NULL */
58918   const Table *pTab2,      /* Second table */
58919   const char *zAlias2,     /* Alias for second table.  May be NULL */
58920   int iRightJoinTable,     /* VDBE cursor for the right table */
58921   Expr **ppExpr            /* Add the equality term to this expression */
58922 ){
58923   Expr *pE1a, *pE1b, *pE1c;
58924   Expr *pE2a, *pE2b, *pE2c;
58925   Expr *pE;
58926
58927   pE1a = sqlite3CreateIdExpr(pParse, zCol);
58928   pE2a = sqlite3CreateIdExpr(pParse, zCol);
58929   if( zAlias1==0 ){
58930     zAlias1 = pTab1->zName;
58931   }
58932   pE1b = sqlite3CreateIdExpr(pParse, zAlias1);
58933   if( zAlias2==0 ){
58934     zAlias2 = pTab2->zName;
58935   }
58936   pE2b = sqlite3CreateIdExpr(pParse, zAlias2);
58937   pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0);
58938   pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0);
58939   pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0);
58940   if( pE ){
58941     ExprSetProperty(pE, EP_FromJoin);
58942     pE->iRightJoinTable = iRightJoinTable;
58943   }
58944   *ppExpr = sqlite3ExprAnd(pParse->db,*ppExpr, pE);
58945 }
58946
58947 /*
58948 ** Set the EP_FromJoin property on all terms of the given expression.
58949 ** And set the Expr.iRightJoinTable to iTable for every term in the
58950 ** expression.
58951 **
58952 ** The EP_FromJoin property is used on terms of an expression to tell
58953 ** the LEFT OUTER JOIN processing logic that this term is part of the
58954 ** join restriction specified in the ON or USING clause and not a part
58955 ** of the more general WHERE clause.  These terms are moved over to the
58956 ** WHERE clause during join processing but we need to remember that they
58957 ** originated in the ON or USING clause.
58958 **
58959 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
58960 ** expression depends on table iRightJoinTable even if that table is not
58961 ** explicitly mentioned in the expression.  That information is needed
58962 ** for cases like this:
58963 **
58964 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
58965 **
58966 ** The where clause needs to defer the handling of the t1.x=5
58967 ** term until after the t2 loop of the join.  In that way, a
58968 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
58969 ** defer the handling of t1.x=5, it will be processed immediately
58970 ** after the t1 loop and rows with t1.x!=5 will never appear in
58971 ** the output, which is incorrect.
58972 */
58973 static void setJoinExpr(Expr *p, int iTable){
58974   while( p ){
58975     ExprSetProperty(p, EP_FromJoin);
58976     p->iRightJoinTable = iTable;
58977     setJoinExpr(p->pLeft, iTable);
58978     p = p->pRight;
58979   } 
58980 }
58981
58982 /*
58983 ** This routine processes the join information for a SELECT statement.
58984 ** ON and USING clauses are converted into extra terms of the WHERE clause.
58985 ** NATURAL joins also create extra WHERE clause terms.
58986 **
58987 ** The terms of a FROM clause are contained in the Select.pSrc structure.
58988 ** The left most table is the first entry in Select.pSrc.  The right-most
58989 ** table is the last entry.  The join operator is held in the entry to
58990 ** the left.  Thus entry 0 contains the join operator for the join between
58991 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
58992 ** also attached to the left entry.
58993 **
58994 ** This routine returns the number of errors encountered.
58995 */
58996 static int sqliteProcessJoin(Parse *pParse, Select *p){
58997   SrcList *pSrc;                  /* All tables in the FROM clause */
58998   int i, j;                       /* Loop counters */
58999   struct SrcList_item *pLeft;     /* Left table being joined */
59000   struct SrcList_item *pRight;    /* Right table being joined */
59001
59002   pSrc = p->pSrc;
59003   pLeft = &pSrc->a[0];
59004   pRight = &pLeft[1];
59005   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
59006     Table *pLeftTab = pLeft->pTab;
59007     Table *pRightTab = pRight->pTab;
59008
59009     if( pLeftTab==0 || pRightTab==0 ) continue;
59010
59011     /* When the NATURAL keyword is present, add WHERE clause terms for
59012     ** every column that the two tables have in common.
59013     */
59014     if( pRight->jointype & JT_NATURAL ){
59015       if( pRight->pOn || pRight->pUsing ){
59016         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
59017            "an ON or USING clause", 0);
59018         return 1;
59019       }
59020       for(j=0; j<pLeftTab->nCol; j++){
59021         char *zName = pLeftTab->aCol[j].zName;
59022         if( columnIndex(pRightTab, zName)>=0 ){
59023           addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 
59024                               pRightTab, pRight->zAlias,
59025                               pRight->iCursor, &p->pWhere);
59026           
59027         }
59028       }
59029     }
59030
59031     /* Disallow both ON and USING clauses in the same join
59032     */
59033     if( pRight->pOn && pRight->pUsing ){
59034       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
59035         "clauses in the same join");
59036       return 1;
59037     }
59038
59039     /* Add the ON clause to the end of the WHERE clause, connected by
59040     ** an AND operator.
59041     */
59042     if( pRight->pOn ){
59043       setJoinExpr(pRight->pOn, pRight->iCursor);
59044       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
59045       pRight->pOn = 0;
59046     }
59047
59048     /* Create extra terms on the WHERE clause for each column named
59049     ** in the USING clause.  Example: If the two tables to be joined are 
59050     ** A and B and the USING clause names X, Y, and Z, then add this
59051     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
59052     ** Report an error if any column mentioned in the USING clause is
59053     ** not contained in both tables to be joined.
59054     */
59055     if( pRight->pUsing ){
59056       IdList *pList = pRight->pUsing;
59057       for(j=0; j<pList->nId; j++){
59058         char *zName = pList->a[j].zName;
59059         if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
59060           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
59061             "not present in both tables", zName);
59062           return 1;
59063         }
59064         addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 
59065                             pRightTab, pRight->zAlias,
59066                             pRight->iCursor, &p->pWhere);
59067       }
59068     }
59069   }
59070   return 0;
59071 }
59072
59073 /*
59074 ** Insert code into "v" that will push the record on the top of the
59075 ** stack into the sorter.
59076 */
59077 static void pushOntoSorter(
59078   Parse *pParse,         /* Parser context */
59079   ExprList *pOrderBy,    /* The ORDER BY clause */
59080   Select *pSelect        /* The whole SELECT statement */
59081 ){
59082   Vdbe *v = pParse->pVdbe;
59083   sqlite3ExprCodeExprList(pParse, pOrderBy);
59084   sqlite3VdbeAddOp(v, OP_Sequence, pOrderBy->iECursor, 0);
59085   sqlite3VdbeAddOp(v, OP_Pull, pOrderBy->nExpr + 1, 0);
59086   sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr + 2, 0);
59087   sqlite3VdbeAddOp(v, OP_IdxInsert, pOrderBy->iECursor, 0);
59088   if( pSelect->iLimit>=0 ){
59089     int addr1, addr2;
59090     addr1 = sqlite3VdbeAddOp(v, OP_IfMemZero, pSelect->iLimit+1, 0);
59091     sqlite3VdbeAddOp(v, OP_MemIncr, -1, pSelect->iLimit+1);
59092     addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
59093     sqlite3VdbeJumpHere(v, addr1);
59094     sqlite3VdbeAddOp(v, OP_Last, pOrderBy->iECursor, 0);
59095     sqlite3VdbeAddOp(v, OP_Delete, pOrderBy->iECursor, 0);
59096     sqlite3VdbeJumpHere(v, addr2);
59097     pSelect->iLimit = -1;
59098   }
59099 }
59100
59101 /*
59102 ** Add code to implement the OFFSET
59103 */
59104 static void codeOffset(
59105   Vdbe *v,          /* Generate code into this VM */
59106   Select *p,        /* The SELECT statement being coded */
59107   int iContinue,    /* Jump here to skip the current record */
59108   int nPop          /* Number of times to pop stack when jumping */
59109 ){
59110   if( p->iOffset>=0 && iContinue!=0 ){
59111     int addr;
59112     sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iOffset);
59113     addr = sqlite3VdbeAddOp(v, OP_IfMemNeg, p->iOffset, 0);
59114     if( nPop>0 ){
59115       sqlite3VdbeAddOp(v, OP_Pop, nPop, 0);
59116     }
59117     sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
59118     VdbeComment((v, "# skip OFFSET records"));
59119     sqlite3VdbeJumpHere(v, addr);
59120   }
59121 }
59122
59123 /*
59124 ** Add code that will check to make sure the top N elements of the
59125 ** stack are distinct.  iTab is a sorting index that holds previously
59126 ** seen combinations of the N values.  A new entry is made in iTab
59127 ** if the current N values are new.
59128 **
59129 ** A jump to addrRepeat is made and the N+1 values are popped from the
59130 ** stack if the top N elements are not distinct.
59131 */
59132 static void codeDistinct(
59133   Vdbe *v,           /* Generate code into this VM */
59134   int iTab,          /* A sorting index used to test for distinctness */
59135   int addrRepeat,    /* Jump to here if not distinct */
59136   int N              /* The top N elements of the stack must be distinct */
59137 ){
59138   sqlite3VdbeAddOp(v, OP_MakeRecord, -N, 0);
59139   sqlite3VdbeAddOp(v, OP_Distinct, iTab, sqlite3VdbeCurrentAddr(v)+3);
59140   sqlite3VdbeAddOp(v, OP_Pop, N+1, 0);
59141   sqlite3VdbeAddOp(v, OP_Goto, 0, addrRepeat);
59142   VdbeComment((v, "# skip indistinct records"));
59143   sqlite3VdbeAddOp(v, OP_IdxInsert, iTab, 0);
59144 }
59145
59146 /*
59147 ** Generate an error message when a SELECT is used within a subexpression
59148 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
59149 ** column.  We do this in a subroutine because the error occurs in multiple
59150 ** places.
59151 */
59152 static int checkForMultiColumnSelectError(Parse *pParse, int eDest, int nExpr){
59153   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
59154     sqlite3ErrorMsg(pParse, "only a single result allowed for "
59155        "a SELECT that is part of an expression");
59156     return 1;
59157   }else{
59158     return 0;
59159   }
59160 }
59161
59162 /*
59163 ** This routine generates the code for the inside of the inner loop
59164 ** of a SELECT.
59165 **
59166 ** If srcTab and nColumn are both zero, then the pEList expressions
59167 ** are evaluated in order to get the data for this row.  If nColumn>0
59168 ** then data is pulled from srcTab and pEList is used only to get the
59169 ** datatypes for each column.
59170 */
59171 static int selectInnerLoop(
59172   Parse *pParse,          /* The parser context */
59173   Select *p,              /* The complete select statement being coded */
59174   ExprList *pEList,       /* List of values being extracted */
59175   int srcTab,             /* Pull data from this table */
59176   int nColumn,            /* Number of columns in the source table */
59177   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
59178   int distinct,           /* If >=0, make sure results are distinct */
59179   int eDest,              /* How to dispose of the results */
59180   int iParm,              /* An argument to the disposal method */
59181   int iContinue,          /* Jump here to continue with next row */
59182   int iBreak,             /* Jump here to break out of the inner loop */
59183   char *aff               /* affinity string if eDest is SRT_Union */
59184 ){
59185   Vdbe *v = pParse->pVdbe;
59186   int i;
59187   int hasDistinct;        /* True if the DISTINCT keyword is present */
59188
59189   if( v==0 ) return 0;
59190   assert( pEList!=0 );
59191
59192   /* If there was a LIMIT clause on the SELECT statement, then do the check
59193   ** to see if this row should be output.
59194   */
59195   hasDistinct = distinct>=0 && pEList->nExpr>0;
59196   if( pOrderBy==0 && !hasDistinct ){
59197     codeOffset(v, p, iContinue, 0);
59198   }
59199
59200   /* Pull the requested columns.
59201   */
59202   if( nColumn>0 ){
59203     for(i=0; i<nColumn; i++){
59204       sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
59205     }
59206   }else{
59207     nColumn = pEList->nExpr;
59208     sqlite3ExprCodeExprList(pParse, pEList);
59209   }
59210
59211   /* If the DISTINCT keyword was present on the SELECT statement
59212   ** and this row has been seen before, then do not make this row
59213   ** part of the result.
59214   */
59215   if( hasDistinct ){
59216     assert( pEList!=0 );
59217     assert( pEList->nExpr==nColumn );
59218     codeDistinct(v, distinct, iContinue, nColumn);
59219     if( pOrderBy==0 ){
59220       codeOffset(v, p, iContinue, nColumn);
59221     }
59222   }
59223
59224   if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){
59225     return 0;
59226   }
59227
59228   switch( eDest ){
59229     /* In this mode, write each query result to the key of the temporary
59230     ** table iParm.
59231     */
59232 #ifndef SQLITE_OMIT_COMPOUND_SELECT
59233     case SRT_Union: {
59234       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
59235       if( aff ){
59236         sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
59237       }
59238       sqlite3VdbeAddOp(v, OP_IdxInsert, iParm, 0);
59239       break;
59240     }
59241
59242     /* Construct a record from the query result, but instead of
59243     ** saving that record, use it as a key to delete elements from
59244     ** the temporary table iParm.
59245     */
59246     case SRT_Except: {
59247       int addr;
59248       addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
59249       sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
59250       sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
59251       sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
59252       break;
59253     }
59254 #endif
59255
59256     /* Store the result as data using a unique key.
59257     */
59258     case SRT_Table:
59259     case SRT_EphemTab: {
59260       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
59261       if( pOrderBy ){
59262         pushOntoSorter(pParse, pOrderBy, p);
59263       }else{
59264         sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
59265         sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
59266         sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND);
59267       }
59268       break;
59269     }
59270
59271 #ifndef SQLITE_OMIT_SUBQUERY
59272     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
59273     ** then there should be a single item on the stack.  Write this
59274     ** item into the set table with bogus data.
59275     */
59276     case SRT_Set: {
59277       int addr1 = sqlite3VdbeCurrentAddr(v);
59278       int addr2;
59279
59280       assert( nColumn==1 );
59281       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
59282       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
59283       addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
59284       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr,(iParm>>16)&0xff);
59285       if( pOrderBy ){
59286         /* At first glance you would think we could optimize out the
59287         ** ORDER BY in this case since the order of entries in the set
59288         ** does not matter.  But there might be a LIMIT clause, in which
59289         ** case the order does matter */
59290         pushOntoSorter(pParse, pOrderBy, p);
59291       }else{
59292         sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1);
59293         sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
59294       }
59295       sqlite3VdbeJumpHere(v, addr2);
59296       break;
59297     }
59298
59299     /* If any row exist in the result set, record that fact and abort.
59300     */
59301     case SRT_Exists: {
59302       sqlite3VdbeAddOp(v, OP_MemInt, 1, iParm);
59303       sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
59304       /* The LIMIT clause will terminate the loop for us */
59305       break;
59306     }
59307
59308     /* If this is a scalar select that is part of an expression, then
59309     ** store the results in the appropriate memory cell and break out
59310     ** of the scan loop.
59311     */
59312     case SRT_Mem: {
59313       assert( nColumn==1 );
59314       if( pOrderBy ){
59315         pushOntoSorter(pParse, pOrderBy, p);
59316       }else{
59317         sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
59318         /* The LIMIT clause will jump out of the loop for us */
59319       }
59320       break;
59321     }
59322 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
59323
59324     /* Send the data to the callback function or to a subroutine.  In the
59325     ** case of a subroutine, the subroutine itself is responsible for
59326     ** popping the data from the stack.
59327     */
59328     case SRT_Subroutine:
59329     case SRT_Callback: {
59330       if( pOrderBy ){
59331         sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
59332         pushOntoSorter(pParse, pOrderBy, p);
59333       }else if( eDest==SRT_Subroutine ){
59334         sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
59335       }else{
59336         sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
59337       }
59338       break;
59339     }
59340
59341 #if !defined(SQLITE_OMIT_TRIGGER)
59342     /* Discard the results.  This is used for SELECT statements inside
59343     ** the body of a TRIGGER.  The purpose of such selects is to call
59344     ** user-defined functions that have side effects.  We do not care
59345     ** about the actual results of the select.
59346     */
59347     default: {
59348       assert( eDest==SRT_Discard );
59349       sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
59350       break;
59351     }
59352 #endif
59353   }
59354
59355   /* Jump to the end of the loop if the LIMIT is reached.
59356   */
59357   if( p->iLimit>=0 && pOrderBy==0 ){
59358     sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit);
59359     sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, iBreak);
59360   }
59361   return 0;
59362 }
59363
59364 /*
59365 ** Given an expression list, generate a KeyInfo structure that records
59366 ** the collating sequence for each expression in that expression list.
59367 **
59368 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
59369 ** KeyInfo structure is appropriate for initializing a virtual index to
59370 ** implement that clause.  If the ExprList is the result set of a SELECT
59371 ** then the KeyInfo structure is appropriate for initializing a virtual
59372 ** index to implement a DISTINCT test.
59373 **
59374 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
59375 ** function is responsible for seeing that this structure is eventually
59376 ** freed.  Add the KeyInfo structure to the P3 field of an opcode using
59377 ** P3_KEYINFO_HANDOFF is the usual way of dealing with this.
59378 */
59379 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
59380   sqlite3 *db = pParse->db;
59381   int nExpr;
59382   KeyInfo *pInfo;
59383   struct ExprList_item *pItem;
59384   int i;
59385
59386   nExpr = pList->nExpr;
59387   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
59388   if( pInfo ){
59389     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
59390     pInfo->nField = nExpr;
59391     pInfo->enc = ENC(db);
59392     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
59393       CollSeq *pColl;
59394       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
59395       if( !pColl ){
59396         pColl = db->pDfltColl;
59397       }
59398       pInfo->aColl[i] = pColl;
59399       pInfo->aSortOrder[i] = pItem->sortOrder;
59400     }
59401   }
59402   return pInfo;
59403 }
59404
59405
59406 /*
59407 ** If the inner loop was generated using a non-null pOrderBy argument,
59408 ** then the results were placed in a sorter.  After the loop is terminated
59409 ** we need to run the sorter and output the results.  The following
59410 ** routine generates the code needed to do that.
59411 */
59412 static void generateSortTail(
59413   Parse *pParse,   /* Parsing context */
59414   Select *p,       /* The SELECT statement */
59415   Vdbe *v,         /* Generate code into this VDBE */
59416   int nColumn,     /* Number of columns of data */
59417   int eDest,       /* Write the sorted results here */
59418   int iParm        /* Optional parameter associated with eDest */
59419 ){
59420   int brk = sqlite3VdbeMakeLabel(v);
59421   int cont = sqlite3VdbeMakeLabel(v);
59422   int addr;
59423   int iTab;
59424   int pseudoTab = 0;
59425   ExprList *pOrderBy = p->pOrderBy;
59426
59427   iTab = pOrderBy->iECursor;
59428   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
59429     pseudoTab = pParse->nTab++;
59430     sqlite3VdbeAddOp(v, OP_OpenPseudo, pseudoTab, 0);
59431     sqlite3VdbeAddOp(v, OP_SetNumColumns, pseudoTab, nColumn);
59432   }
59433   addr = 1 + sqlite3VdbeAddOp(v, OP_Sort, iTab, brk);
59434   codeOffset(v, p, cont, 0);
59435   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
59436     sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
59437   }
59438   sqlite3VdbeAddOp(v, OP_Column, iTab, pOrderBy->nExpr + 1);
59439   switch( eDest ){
59440     case SRT_Table:
59441     case SRT_EphemTab: {
59442       sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
59443       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
59444       sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND);
59445       break;
59446     }
59447 #ifndef SQLITE_OMIT_SUBQUERY
59448     case SRT_Set: {
59449       assert( nColumn==1 );
59450       sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
59451       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
59452       sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
59453       sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1);
59454       sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
59455       break;
59456     }
59457     case SRT_Mem: {
59458       assert( nColumn==1 );
59459       sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
59460       /* The LIMIT clause will terminate the loop for us */
59461       break;
59462     }
59463 #endif
59464     case SRT_Callback:
59465     case SRT_Subroutine: {
59466       int i;
59467       sqlite3VdbeAddOp(v, OP_Insert, pseudoTab, 0);
59468       for(i=0; i<nColumn; i++){
59469         sqlite3VdbeAddOp(v, OP_Column, pseudoTab, i);
59470       }
59471       if( eDest==SRT_Callback ){
59472         sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
59473       }else{
59474         sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
59475       }
59476       break;
59477     }
59478     default: {
59479       /* Do nothing */
59480       break;
59481     }
59482   }
59483
59484   /* Jump to the end of the loop when the LIMIT is reached
59485   */
59486   if( p->iLimit>=0 ){
59487     sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit);
59488     sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, brk);
59489   }
59490
59491   /* The bottom of the loop
59492   */
59493   sqlite3VdbeResolveLabel(v, cont);
59494   sqlite3VdbeAddOp(v, OP_Next, iTab, addr);
59495   sqlite3VdbeResolveLabel(v, brk);
59496   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
59497     sqlite3VdbeAddOp(v, OP_Close, pseudoTab, 0);
59498   }
59499
59500 }
59501
59502 /*
59503 ** Return a pointer to a string containing the 'declaration type' of the
59504 ** expression pExpr. The string may be treated as static by the caller.
59505 **
59506 ** The declaration type is the exact datatype definition extracted from the
59507 ** original CREATE TABLE statement if the expression is a column. The
59508 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
59509 ** is considered a column can be complex in the presence of subqueries. The
59510 ** result-set expression in all of the following SELECT statements is 
59511 ** considered a column by this function.
59512 **
59513 **   SELECT col FROM tbl;
59514 **   SELECT (SELECT col FROM tbl;
59515 **   SELECT (SELECT col FROM tbl);
59516 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
59517 ** 
59518 ** The declaration type for any expression other than a column is NULL.
59519 */
59520 static const char *columnType(
59521   NameContext *pNC, 
59522   Expr *pExpr,
59523   const char **pzOriginDb,
59524   const char **pzOriginTab,
59525   const char **pzOriginCol
59526 ){
59527   char const *zType = 0;
59528   char const *zOriginDb = 0;
59529   char const *zOriginTab = 0;
59530   char const *zOriginCol = 0;
59531   int j;
59532   if( pExpr==0 || pNC->pSrcList==0 ) return 0;
59533
59534   switch( pExpr->op ){
59535     case TK_AGG_COLUMN:
59536     case TK_COLUMN: {
59537       /* The expression is a column. Locate the table the column is being
59538       ** extracted from in NameContext.pSrcList. This table may be real
59539       ** database table or a subquery.
59540       */
59541       Table *pTab = 0;            /* Table structure column is extracted from */
59542       Select *pS = 0;             /* Select the column is extracted from */
59543       int iCol = pExpr->iColumn;  /* Index of column in pTab */
59544       while( pNC && !pTab ){
59545         SrcList *pTabList = pNC->pSrcList;
59546         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
59547         if( j<pTabList->nSrc ){
59548           pTab = pTabList->a[j].pTab;
59549           pS = pTabList->a[j].pSelect;
59550         }else{
59551           pNC = pNC->pNext;
59552         }
59553       }
59554
59555       if( pTab==0 ){
59556         /* FIX ME:
59557         ** This can occurs if you have something like "SELECT new.x;" inside
59558         ** a trigger.  In other words, if you reference the special "new"
59559         ** table in the result set of a select.  We do not have a good way
59560         ** to find the actual table type, so call it "TEXT".  This is really
59561         ** something of a bug, but I do not know how to fix it.
59562         **
59563         ** This code does not produce the correct answer - it just prevents
59564         ** a segfault.  See ticket #1229.
59565         */
59566         zType = "TEXT";
59567         break;
59568       }
59569
59570       assert( pTab );
59571       if( pS ){
59572         /* The "table" is actually a sub-select or a view in the FROM clause
59573         ** of the SELECT statement. Return the declaration type and origin
59574         ** data for the result-set column of the sub-select.
59575         */
59576         if( iCol>=0 && iCol<pS->pEList->nExpr ){
59577           /* If iCol is less than zero, then the expression requests the
59578           ** rowid of the sub-select or view. This expression is legal (see 
59579           ** test case misc2.2.2) - it always evaluates to NULL.
59580           */
59581           NameContext sNC;
59582           Expr *p = pS->pEList->a[iCol].pExpr;
59583           sNC.pSrcList = pS->pSrc;
59584           sNC.pNext = 0;
59585           sNC.pParse = pNC->pParse;
59586           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
59587         }
59588       }else if( pTab->pSchema ){
59589         /* A real table */
59590         assert( !pS );
59591         if( iCol<0 ) iCol = pTab->iPKey;
59592         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
59593         if( iCol<0 ){
59594           zType = "INTEGER";
59595           zOriginCol = "rowid";
59596         }else{
59597           zType = pTab->aCol[iCol].zType;
59598           zOriginCol = pTab->aCol[iCol].zName;
59599         }
59600         zOriginTab = pTab->zName;
59601         if( pNC->pParse ){
59602           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
59603           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
59604         }
59605       }
59606       break;
59607     }
59608 #ifndef SQLITE_OMIT_SUBQUERY
59609     case TK_SELECT: {
59610       /* The expression is a sub-select. Return the declaration type and
59611       ** origin info for the single column in the result set of the SELECT
59612       ** statement.
59613       */
59614       NameContext sNC;
59615       Select *pS = pExpr->pSelect;
59616       Expr *p = pS->pEList->a[0].pExpr;
59617       sNC.pSrcList = pS->pSrc;
59618       sNC.pNext = pNC;
59619       sNC.pParse = pNC->pParse;
59620       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
59621       break;
59622     }
59623 #endif
59624   }
59625   
59626   if( pzOriginDb ){
59627     assert( pzOriginTab && pzOriginCol );
59628     *pzOriginDb = zOriginDb;
59629     *pzOriginTab = zOriginTab;
59630     *pzOriginCol = zOriginCol;
59631   }
59632   return zType;
59633 }
59634
59635 /*
59636 ** Generate code that will tell the VDBE the declaration types of columns
59637 ** in the result set.
59638 */
59639 static void generateColumnTypes(
59640   Parse *pParse,      /* Parser context */
59641   SrcList *pTabList,  /* List of tables */
59642   ExprList *pEList    /* Expressions defining the result set */
59643 ){
59644   Vdbe *v = pParse->pVdbe;
59645   int i;
59646   NameContext sNC;
59647   sNC.pSrcList = pTabList;
59648   sNC.pParse = pParse;
59649   for(i=0; i<pEList->nExpr; i++){
59650     Expr *p = pEList->a[i].pExpr;
59651     const char *zOrigDb = 0;
59652     const char *zOrigTab = 0;
59653     const char *zOrigCol = 0;
59654     const char *zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
59655
59656     /* The vdbe must make its own copy of the column-type and other 
59657     ** column specific strings, in case the schema is reset before this
59658     ** virtual machine is deleted.
59659     */
59660     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P3_TRANSIENT);
59661     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P3_TRANSIENT);
59662     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P3_TRANSIENT);
59663     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P3_TRANSIENT);
59664   }
59665 }
59666
59667 /*
59668 ** Generate code that will tell the VDBE the names of columns
59669 ** in the result set.  This information is used to provide the
59670 ** azCol[] values in the callback.
59671 */
59672 static void generateColumnNames(
59673   Parse *pParse,      /* Parser context */
59674   SrcList *pTabList,  /* List of tables */
59675   ExprList *pEList    /* Expressions defining the result set */
59676 ){
59677   Vdbe *v = pParse->pVdbe;
59678   int i, j;
59679   sqlite3 *db = pParse->db;
59680   int fullNames, shortNames;
59681
59682 #ifndef SQLITE_OMIT_EXPLAIN
59683   /* If this is an EXPLAIN, skip this step */
59684   if( pParse->explain ){
59685     return;
59686   }
59687 #endif
59688
59689   assert( v!=0 );
59690   if( pParse->colNamesSet || v==0 || db->mallocFailed ) return;
59691   pParse->colNamesSet = 1;
59692   fullNames = (db->flags & SQLITE_FullColNames)!=0;
59693   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
59694   sqlite3VdbeSetNumCols(v, pEList->nExpr);
59695   for(i=0; i<pEList->nExpr; i++){
59696     Expr *p;
59697     p = pEList->a[i].pExpr;
59698     if( p==0 ) continue;
59699     if( pEList->a[i].zName ){
59700       char *zName = pEList->a[i].zName;
59701       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName));
59702       continue;
59703     }
59704     if( p->op==TK_COLUMN && pTabList ){
59705       Table *pTab;
59706       char *zCol;
59707       int iCol = p->iColumn;
59708       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
59709       assert( j<pTabList->nSrc );
59710       pTab = pTabList->a[j].pTab;
59711       if( iCol<0 ) iCol = pTab->iPKey;
59712       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
59713       if( iCol<0 ){
59714         zCol = "rowid";
59715       }else{
59716         zCol = pTab->aCol[iCol].zName;
59717       }
59718       if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
59719         sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
59720       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
59721         char *zName = 0;
59722         char *zTab;
59723  
59724         zTab = pTabList->a[j].zAlias;
59725         if( fullNames || zTab==0 ) zTab = pTab->zName;
59726         sqlite3SetString(&zName, zTab, ".", zCol, (char*)0);
59727         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P3_DYNAMIC);
59728       }else{
59729         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol));
59730       }
59731     }else if( p->span.z && p->span.z[0] ){
59732       sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
59733       /* sqlite3VdbeCompressSpace(v, addr); */
59734     }else{
59735       char zName[30];
59736       assert( p->op!=TK_COLUMN || pTabList==0 );
59737       sqlite3_snprintf(sizeof(zName), zName, "column%d", i+1);
59738       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, 0);
59739     }
59740   }
59741   generateColumnTypes(pParse, pTabList, pEList);
59742 }
59743
59744 #ifndef SQLITE_OMIT_COMPOUND_SELECT
59745 /*
59746 ** Name of the connection operator, used for error messages.
59747 */
59748 static const char *selectOpName(int id){
59749   char *z;
59750   switch( id ){
59751     case TK_ALL:       z = "UNION ALL";   break;
59752     case TK_INTERSECT: z = "INTERSECT";   break;
59753     case TK_EXCEPT:    z = "EXCEPT";      break;
59754     default:           z = "UNION";       break;
59755   }
59756   return z;
59757 }
59758 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
59759
59760 /*
59761 ** Forward declaration
59762 */
59763 static int prepSelectStmt(Parse*, Select*);
59764
59765 /*
59766 ** Given a SELECT statement, generate a Table structure that describes
59767 ** the result set of that SELECT.
59768 */
59769 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
59770   Table *pTab;
59771   int i, j;
59772   ExprList *pEList;
59773   Column *aCol, *pCol;
59774   sqlite3 *db = pParse->db;
59775
59776   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
59777   if( prepSelectStmt(pParse, pSelect) ){
59778     return 0;
59779   }
59780   if( sqlite3SelectResolve(pParse, pSelect, 0) ){
59781     return 0;
59782   }
59783   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
59784   if( pTab==0 ){
59785     return 0;
59786   }
59787   pTab->nRef = 1;
59788   pTab->zName = zTabName ? sqlite3DbStrDup(db, zTabName) : 0;
59789   pEList = pSelect->pEList;
59790   pTab->nCol = pEList->nExpr;
59791   assert( pTab->nCol>0 );
59792   pTab->aCol = aCol = sqlite3DbMallocZero(db, sizeof(pTab->aCol[0])*pTab->nCol);
59793   for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
59794     Expr *p, *pR;
59795     char *zType;
59796     char *zName;
59797     int nName;
59798     CollSeq *pColl;
59799     int cnt;
59800     NameContext sNC;
59801     
59802     /* Get an appropriate name for the column
59803     */
59804     p = pEList->a[i].pExpr;
59805     assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
59806     if( (zName = pEList->a[i].zName)!=0 ){
59807       /* If the column contains an "AS <name>" phrase, use <name> as the name */
59808       zName = sqlite3DbStrDup(db, zName);
59809     }else if( p->op==TK_DOT 
59810               && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
59811       /* For columns of the from A.B use B as the name */
59812       zName = sqlite3MPrintf(db, "%T", &pR->token);
59813     }else if( p->span.z && p->span.z[0] ){
59814       /* Use the original text of the column expression as its name */
59815       zName = sqlite3MPrintf(db, "%T", &p->span);
59816     }else{
59817       /* If all else fails, make up a name */
59818       zName = sqlite3MPrintf(db, "column%d", i+1);
59819     }
59820     if( !zName || db->mallocFailed ){
59821       db->mallocFailed = 1;
59822       sqlite3_free(zName);
59823       sqlite3DeleteTable(pTab);
59824       return 0;
59825     }
59826     sqlite3Dequote(zName);
59827
59828     /* Make sure the column name is unique.  If the name is not unique,
59829     ** append a integer to the name so that it becomes unique.
59830     */
59831     nName = strlen(zName);
59832     for(j=cnt=0; j<i; j++){
59833       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
59834         zName[nName] = 0;
59835         zName = sqlite3MPrintf(db, "%z:%d", zName, ++cnt);
59836         j = -1;
59837         if( zName==0 ) break;
59838       }
59839     }
59840     pCol->zName = zName;
59841
59842     /* Get the typename, type affinity, and collating sequence for the
59843     ** column.
59844     */
59845     memset(&sNC, 0, sizeof(sNC));
59846     sNC.pSrcList = pSelect->pSrc;
59847     zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
59848     pCol->zType = zType;
59849     pCol->affinity = sqlite3ExprAffinity(p);
59850     pColl = sqlite3ExprCollSeq(pParse, p);
59851     if( pColl ){
59852       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
59853     }
59854   }
59855   pTab->iPKey = -1;
59856   return pTab;
59857 }
59858
59859 /*
59860 ** Prepare a SELECT statement for processing by doing the following
59861 ** things:
59862 **
59863 **    (1)  Make sure VDBE cursor numbers have been assigned to every
59864 **         element of the FROM clause.
59865 **
59866 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
59867 **         defines FROM clause.  When views appear in the FROM clause,
59868 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
59869 **         that implements the view.  A copy is made of the view's SELECT
59870 **         statement so that we can freely modify or delete that statement
59871 **         without worrying about messing up the presistent representation
59872 **         of the view.
59873 **
59874 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
59875 **         on joins and the ON and USING clause of joins.
59876 **
59877 **    (4)  Scan the list of columns in the result set (pEList) looking
59878 **         for instances of the "*" operator or the TABLE.* operator.
59879 **         If found, expand each "*" to be every column in every table
59880 **         and TABLE.* to be every column in TABLE.
59881 **
59882 ** Return 0 on success.  If there are problems, leave an error message
59883 ** in pParse and return non-zero.
59884 */
59885 static int prepSelectStmt(Parse *pParse, Select *p){
59886   int i, j, k, rc;
59887   SrcList *pTabList;
59888   ExprList *pEList;
59889   struct SrcList_item *pFrom;
59890   sqlite3 *db = pParse->db;
59891
59892   if( p==0 || p->pSrc==0 || db->mallocFailed ){
59893     return 1;
59894   }
59895   pTabList = p->pSrc;
59896   pEList = p->pEList;
59897
59898   /* Make sure cursor numbers have been assigned to all entries in
59899   ** the FROM clause of the SELECT statement.
59900   */
59901   sqlite3SrcListAssignCursors(pParse, p->pSrc);
59902
59903   /* Look up every table named in the FROM clause of the select.  If
59904   ** an entry of the FROM clause is a subquery instead of a table or view,
59905   ** then create a transient table structure to describe the subquery.
59906   */
59907   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
59908     Table *pTab;
59909     if( pFrom->pTab!=0 ){
59910       /* This statement has already been prepared.  There is no need
59911       ** to go further. */
59912       assert( i==0 );
59913       return 0;
59914     }
59915     if( pFrom->zName==0 ){
59916 #ifndef SQLITE_OMIT_SUBQUERY
59917       /* A sub-query in the FROM clause of a SELECT */
59918       assert( pFrom->pSelect!=0 );
59919       if( pFrom->zAlias==0 ){
59920         pFrom->zAlias =
59921           sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pFrom->pSelect);
59922       }
59923       assert( pFrom->pTab==0 );
59924       pFrom->pTab = pTab = 
59925         sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
59926       if( pTab==0 ){
59927         return 1;
59928       }
59929       /* The isEphem flag indicates that the Table structure has been
59930       ** dynamically allocated and may be freed at any time.  In other words,
59931       ** pTab is not pointing to a persistent table structure that defines
59932       ** part of the schema. */
59933       pTab->isEphem = 1;
59934 #endif
59935     }else{
59936       /* An ordinary table or view name in the FROM clause */
59937       assert( pFrom->pTab==0 );
59938       pFrom->pTab = pTab = 
59939         sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
59940       if( pTab==0 ){
59941         return 1;
59942       }
59943       pTab->nRef++;
59944 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
59945       if( pTab->pSelect || IsVirtual(pTab) ){
59946         /* We reach here if the named table is a really a view */
59947         if( sqlite3ViewGetColumnNames(pParse, pTab) ){
59948           return 1;
59949         }
59950         /* If pFrom->pSelect!=0 it means we are dealing with a
59951         ** view within a view.  The SELECT structure has already been
59952         ** copied by the outer view so we can skip the copy step here
59953         ** in the inner view.
59954         */
59955         if( pFrom->pSelect==0 ){
59956           pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect);
59957         }
59958       }
59959 #endif
59960     }
59961   }
59962
59963   /* Process NATURAL keywords, and ON and USING clauses of joins.
59964   */
59965   if( sqliteProcessJoin(pParse, p) ) return 1;
59966
59967   /* For every "*" that occurs in the column list, insert the names of
59968   ** all columns in all tables.  And for every TABLE.* insert the names
59969   ** of all columns in TABLE.  The parser inserted a special expression
59970   ** with the TK_ALL operator for each "*" that it found in the column list.
59971   ** The following code just has to locate the TK_ALL expressions and expand
59972   ** each one to the list of all columns in all tables.
59973   **
59974   ** The first loop just checks to see if there are any "*" operators
59975   ** that need expanding.
59976   */
59977   for(k=0; k<pEList->nExpr; k++){
59978     Expr *pE = pEList->a[k].pExpr;
59979     if( pE->op==TK_ALL ) break;
59980     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
59981          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
59982   }
59983   rc = 0;
59984   if( k<pEList->nExpr ){
59985     /*
59986     ** If we get here it means the result set contains one or more "*"
59987     ** operators that need to be expanded.  Loop through each expression
59988     ** in the result set and expand them one by one.
59989     */
59990     struct ExprList_item *a = pEList->a;
59991     ExprList *pNew = 0;
59992     int flags = pParse->db->flags;
59993     int longNames = (flags & SQLITE_FullColNames)!=0 &&
59994                       (flags & SQLITE_ShortColNames)==0;
59995
59996     for(k=0; k<pEList->nExpr; k++){
59997       Expr *pE = a[k].pExpr;
59998       if( pE->op!=TK_ALL &&
59999            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
60000         /* This particular expression does not need to be expanded.
60001         */
60002         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0);
60003         if( pNew ){
60004           pNew->a[pNew->nExpr-1].zName = a[k].zName;
60005         }else{
60006           rc = 1;
60007         }
60008         a[k].pExpr = 0;
60009         a[k].zName = 0;
60010       }else{
60011         /* This expression is a "*" or a "TABLE.*" and needs to be
60012         ** expanded. */
60013         int tableSeen = 0;      /* Set to 1 when TABLE matches */
60014         char *zTName;            /* text of name of TABLE */
60015         if( pE->op==TK_DOT && pE->pLeft ){
60016           zTName = sqlite3NameFromToken(db, &pE->pLeft->token);
60017         }else{
60018           zTName = 0;
60019         }
60020         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
60021           Table *pTab = pFrom->pTab;
60022           char *zTabName = pFrom->zAlias;
60023           if( zTabName==0 || zTabName[0]==0 ){ 
60024             zTabName = pTab->zName;
60025           }
60026           if( zTName && (zTabName==0 || zTabName[0]==0 || 
60027                  sqlite3StrICmp(zTName, zTabName)!=0) ){
60028             continue;
60029           }
60030           tableSeen = 1;
60031           for(j=0; j<pTab->nCol; j++){
60032             Expr *pExpr, *pRight;
60033             char *zName = pTab->aCol[j].zName;
60034
60035             /* If a column is marked as 'hidden' (currently only possible
60036             ** for virtual tables), do not include it in the expanded
60037             ** result-set list.
60038             */
60039             if( IsHiddenColumn(&pTab->aCol[j]) ){
60040               assert(IsVirtual(pTab));
60041               continue;
60042             }
60043
60044             if( i>0 ){
60045               struct SrcList_item *pLeft = &pTabList->a[i-1];
60046               if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
60047                         columnIndex(pLeft->pTab, zName)>=0 ){
60048                 /* In a NATURAL join, omit the join columns from the 
60049                 ** table on the right */
60050                 continue;
60051               }
60052               if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
60053                 /* In a join with a USING clause, omit columns in the
60054                 ** using clause from the table on the right. */
60055                 continue;
60056               }
60057             }
60058             pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
60059             if( pRight==0 ) break;
60060             setQuotedToken(pParse, &pRight->token, zName);
60061             if( zTabName && (longNames || pTabList->nSrc>1) ){
60062               Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
60063               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
60064               if( pExpr==0 ) break;
60065               setQuotedToken(pParse, &pLeft->token, zTabName);
60066               setToken(&pExpr->span, 
60067                   sqlite3MPrintf(db, "%s.%s", zTabName, zName));
60068               pExpr->span.dyn = 1;
60069               pExpr->token.z = 0;
60070               pExpr->token.n = 0;
60071               pExpr->token.dyn = 0;
60072             }else{
60073               pExpr = pRight;
60074               pExpr->span = pExpr->token;
60075               pExpr->span.dyn = 0;
60076             }
60077             if( longNames ){
60078               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span);
60079             }else{
60080               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token);
60081             }
60082           }
60083         }
60084         if( !tableSeen ){
60085           if( zTName ){
60086             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
60087           }else{
60088             sqlite3ErrorMsg(pParse, "no tables specified");
60089           }
60090           rc = 1;
60091         }
60092         sqlite3_free(zTName);
60093       }
60094     }
60095     sqlite3ExprListDelete(pEList);
60096     p->pEList = pNew;
60097   }
60098   if( p->pEList && p->pEList->nExpr>SQLITE_MAX_COLUMN ){
60099     sqlite3ErrorMsg(pParse, "too many columns in result set");
60100     rc = SQLITE_ERROR;
60101   }
60102   if( db->mallocFailed ){
60103     rc = SQLITE_NOMEM;
60104   }
60105   return rc;
60106 }
60107
60108 /*
60109 ** pE is a pointer to an expression which is a single term in
60110 ** ORDER BY or GROUP BY clause.
60111 **
60112 ** If pE evaluates to an integer constant i, then return i.
60113 ** This is an indication to the caller that it should sort
60114 ** by the i-th column of the result set.
60115 **
60116 ** If pE is a well-formed expression and the SELECT statement
60117 ** is not compound, then return 0.  This indicates to the
60118 ** caller that it should sort by the value of the ORDER BY
60119 ** expression.
60120 **
60121 ** If the SELECT is compound, then attempt to match pE against
60122 ** result set columns in the left-most SELECT statement.  Return
60123 ** the index i of the matching column, as an indication to the 
60124 ** caller that it should sort by the i-th column.  If there is
60125 ** no match, return -1 and leave an error message in pParse.
60126 */
60127 static int matchOrderByTermToExprList(
60128   Parse *pParse,     /* Parsing context for error messages */
60129   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
60130   Expr *pE,          /* The specific ORDER BY term */
60131   int idx,           /* When ORDER BY term is this */
60132   int isCompound,    /* True if this is a compound SELECT */
60133   u8 *pHasAgg        /* True if expression contains aggregate functions */
60134 ){
60135   int i;             /* Loop counter */
60136   ExprList *pEList;  /* The columns of the result set */
60137   NameContext nc;    /* Name context for resolving pE */
60138
60139
60140   /* If the term is an integer constant, return the value of that
60141   ** constant */
60142   pEList = pSelect->pEList;
60143   if( sqlite3ExprIsInteger(pE, &i) ){
60144     if( i<=0 ){
60145       /* If i is too small, make it too big.  That way the calling
60146       ** function still sees a value that is out of range, but does
60147       ** not confuse the column number with 0 or -1 result code.
60148       */
60149       i = pEList->nExpr+1;
60150     }
60151     return i;
60152   }
60153
60154   /* If the term is a simple identifier that try to match that identifier
60155   ** against a column name in the result set.
60156   */
60157   if( pE->op==TK_ID || (pE->op==TK_STRING && pE->token.z[0]!='\'') ){
60158     sqlite3 *db = pParse->db;
60159     char *zCol = sqlite3NameFromToken(db, &pE->token);
60160     if( zCol==0 ){
60161       return -1;
60162     }
60163     for(i=0; i<pEList->nExpr; i++){
60164       char *zAs = pEList->a[i].zName;
60165       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
60166         sqlite3_free(zCol);
60167         return i+1;
60168       }
60169     }
60170     sqlite3_free(zCol);
60171   }
60172
60173   /* Resolve all names in the ORDER BY term expression
60174   */
60175   memset(&nc, 0, sizeof(nc));
60176   nc.pParse = pParse;
60177   nc.pSrcList = pSelect->pSrc;
60178   nc.pEList = pEList;
60179   nc.allowAgg = 1;
60180   nc.nErr = 0;
60181   if( sqlite3ExprResolveNames(&nc, pE) ){
60182     if( isCompound ){
60183       sqlite3ErrorClear(pParse);
60184       return 0;
60185     }else{
60186       return -1;
60187     }
60188   }
60189   if( nc.hasAgg && pHasAgg ){
60190     *pHasAgg = 1;
60191   }
60192
60193   /* For a compound SELECT, we need to try to match the ORDER BY
60194   ** expression against an expression in the result set
60195   */
60196   if( isCompound ){
60197     for(i=0; i<pEList->nExpr; i++){
60198       if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
60199         return i+1;
60200       }
60201     }
60202   }
60203   return 0;
60204 }
60205
60206
60207 /*
60208 ** Analyze and ORDER BY or GROUP BY clause in a simple SELECT statement.
60209 ** Return the number of errors seen.
60210 **
60211 ** Every term of the ORDER BY or GROUP BY clause needs to be an
60212 ** expression.  If any expression is an integer constant, then
60213 ** that expression is replaced by the corresponding 
60214 ** expression from the result set.
60215 */
60216 static int processOrderGroupBy(
60217   Parse *pParse,        /* Parsing context.  Leave error messages here */
60218   Select *pSelect,      /* The SELECT statement containing the clause */
60219   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
60220   int isOrder,          /* 1 for ORDER BY.  0 for GROUP BY */
60221   u8 *pHasAgg           /* Set to TRUE if any term contains an aggregate */
60222 ){
60223   int i;
60224   sqlite3 *db = pParse->db;
60225   ExprList *pEList;
60226
60227   if( pOrderBy==0 ) return 0;
60228   if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){
60229     const char *zType = isOrder ? "ORDER" : "GROUP";
60230     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
60231     return 1;
60232   }
60233   pEList = pSelect->pEList;
60234   if( pEList==0 ){
60235     return 0;
60236   }
60237   for(i=0; i<pOrderBy->nExpr; i++){
60238     int iCol;
60239     Expr *pE = pOrderBy->a[i].pExpr;
60240     iCol = matchOrderByTermToExprList(pParse, pSelect, pE, i+1, 0, pHasAgg);
60241     if( iCol<0 ){
60242       return 1;
60243     }
60244     if( iCol>pEList->nExpr ){
60245       const char *zType = isOrder ? "ORDER" : "GROUP";
60246       sqlite3ErrorMsg(pParse, 
60247          "%r %s BY term out of range - should be "
60248          "between 1 and %d", i+1, zType, pEList->nExpr);
60249       return 1;
60250     }
60251     if( iCol>0 ){
60252       CollSeq *pColl = pE->pColl;
60253       int flags = pE->flags & EP_ExpCollate;
60254       sqlite3ExprDelete(pE);
60255       pE = sqlite3ExprDup(db, pEList->a[iCol-1].pExpr);
60256       pOrderBy->a[i].pExpr = pE;
60257       if( pColl && flags ){
60258         pE->pColl = pColl;
60259         pE->flags |= flags;
60260       }
60261     }
60262   }
60263   return 0;
60264 }
60265
60266 /*
60267 ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement.  Return
60268 ** the number of errors seen.
60269 **
60270 ** The processing depends on whether the SELECT is simple or compound.
60271 ** For a simple SELECT statement, evry term of the ORDER BY or GROUP BY
60272 ** clause needs to be an expression.  If any expression is an integer
60273 ** constant, then that expression is replaced by the corresponding 
60274 ** expression from the result set.
60275 **
60276 ** For compound SELECT statements, every expression needs to be of
60277 ** type TK_COLUMN with a iTable value as given in the 4th parameter.
60278 ** If any expression is an integer, that becomes the column number.
60279 ** Otherwise, match the expression against result set columns from
60280 ** the left-most SELECT.
60281 */
60282 static int processCompoundOrderBy(
60283   Parse *pParse,        /* Parsing context.  Leave error messages here */
60284   Select *pSelect,      /* The SELECT statement containing the ORDER BY */
60285   int iTable            /* Output table for compound SELECT statements */
60286 ){
60287   int i;
60288   ExprList *pOrderBy;
60289   ExprList *pEList;
60290   sqlite3 *db;
60291   int moreToDo = 1;
60292
60293   pOrderBy = pSelect->pOrderBy;
60294   if( pOrderBy==0 ) return 0;
60295   if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){
60296     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
60297     return 1;
60298   }
60299   db = pParse->db;
60300   for(i=0; i<pOrderBy->nExpr; i++){
60301     pOrderBy->a[i].done = 0;
60302   }
60303   while( pSelect->pPrior ){
60304     pSelect = pSelect->pPrior;
60305   }
60306   while( pSelect && moreToDo ){
60307     moreToDo = 0;
60308     for(i=0; i<pOrderBy->nExpr; i++){
60309       int iCol;
60310       Expr *pE, *pDup;
60311       if( pOrderBy->a[i].done ) continue;
60312       pE = pOrderBy->a[i].pExpr;
60313       pDup = sqlite3ExprDup(db, pE);
60314       if( pDup==0 ){
60315         return 1;
60316       }
60317       iCol = matchOrderByTermToExprList(pParse, pSelect, pDup, i+1, 1, 0);
60318       sqlite3ExprDelete(pDup);
60319       if( iCol<0 ){
60320         return 1;
60321       }
60322       pEList = pSelect->pEList;
60323       if( pEList==0 ){
60324         return 1;
60325       }
60326       if( iCol>pEList->nExpr ){
60327         sqlite3ErrorMsg(pParse, 
60328            "%r ORDER BY term out of range - should be "
60329            "between 1 and %d", i+1, pEList->nExpr);
60330         return 1;
60331       }
60332       if( iCol>0 ){
60333         pE->op = TK_COLUMN;
60334         pE->iTable = iTable;
60335         pE->iAgg = -1;
60336         pE->iColumn = iCol-1;
60337         pE->pTab = 0;
60338         pOrderBy->a[i].done = 1;
60339       }else{
60340         moreToDo = 1;
60341       }
60342     }
60343     pSelect = pSelect->pNext;
60344   }
60345   for(i=0; i<pOrderBy->nExpr; i++){
60346     if( pOrderBy->a[i].done==0 ){
60347       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
60348             "column in the result set", i+1);
60349       return 1;
60350     }
60351   }
60352   return 0;
60353 }
60354
60355 /*
60356 ** Get a VDBE for the given parser context.  Create a new one if necessary.
60357 ** If an error occurs, return NULL and leave a message in pParse.
60358 */
60359 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
60360   Vdbe *v = pParse->pVdbe;
60361   if( v==0 ){
60362     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
60363   }
60364   return v;
60365 }
60366
60367
60368 /*
60369 ** Compute the iLimit and iOffset fields of the SELECT based on the
60370 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
60371 ** that appear in the original SQL statement after the LIMIT and OFFSET
60372 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
60373 ** are the integer memory register numbers for counters used to compute 
60374 ** the limit and offset.  If there is no limit and/or offset, then 
60375 ** iLimit and iOffset are negative.
60376 **
60377 ** This routine changes the values of iLimit and iOffset only if
60378 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
60379 ** iOffset should have been preset to appropriate default values
60380 ** (usually but not always -1) prior to calling this routine.
60381 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
60382 ** redefined.  The UNION ALL operator uses this property to force
60383 ** the reuse of the same limit and offset registers across multiple
60384 ** SELECT statements.
60385 */
60386 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
60387   Vdbe *v = 0;
60388   int iLimit = 0;
60389   int iOffset;
60390   int addr1, addr2;
60391
60392   /* 
60393   ** "LIMIT -1" always shows all rows.  There is some
60394   ** contraversy about what the correct behavior should be.
60395   ** The current implementation interprets "LIMIT 0" to mean
60396   ** no rows.
60397   */
60398   if( p->pLimit ){
60399     p->iLimit = iLimit = pParse->nMem;
60400     pParse->nMem += 2;
60401     v = sqlite3GetVdbe(pParse);
60402     if( v==0 ) return;
60403     sqlite3ExprCode(pParse, p->pLimit);
60404     sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
60405     sqlite3VdbeAddOp(v, OP_MemStore, iLimit, 1);
60406     VdbeComment((v, "# LIMIT counter"));
60407     sqlite3VdbeAddOp(v, OP_IfMemZero, iLimit, iBreak);
60408     sqlite3VdbeAddOp(v, OP_MemLoad, iLimit, 0);
60409   }
60410   if( p->pOffset ){
60411     p->iOffset = iOffset = pParse->nMem++;
60412     v = sqlite3GetVdbe(pParse);
60413     if( v==0 ) return;
60414     sqlite3ExprCode(pParse, p->pOffset);
60415     sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
60416     sqlite3VdbeAddOp(v, OP_MemStore, iOffset, p->pLimit==0);
60417     VdbeComment((v, "# OFFSET counter"));
60418     addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iOffset, 0);
60419     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
60420     sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
60421     sqlite3VdbeJumpHere(v, addr1);
60422     if( p->pLimit ){
60423       sqlite3VdbeAddOp(v, OP_Add, 0, 0);
60424     }
60425   }
60426   if( p->pLimit ){
60427     addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iLimit, 0);
60428     sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
60429     sqlite3VdbeAddOp(v, OP_MemInt, -1, iLimit+1);
60430     addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
60431     sqlite3VdbeJumpHere(v, addr1);
60432     sqlite3VdbeAddOp(v, OP_MemStore, iLimit+1, 1);
60433     VdbeComment((v, "# LIMIT+OFFSET"));
60434     sqlite3VdbeJumpHere(v, addr2);
60435   }
60436 }
60437
60438 /*
60439 ** Allocate a virtual index to use for sorting.
60440 */
60441 static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){
60442   if( pOrderBy ){
60443     int addr;
60444     assert( pOrderBy->iECursor==0 );
60445     pOrderBy->iECursor = pParse->nTab++;
60446     addr = sqlite3VdbeAddOp(pParse->pVdbe, OP_OpenEphemeral,
60447                             pOrderBy->iECursor, pOrderBy->nExpr+1);
60448     assert( p->addrOpenEphm[2] == -1 );
60449     p->addrOpenEphm[2] = addr;
60450   }
60451 }
60452
60453 #ifndef SQLITE_OMIT_COMPOUND_SELECT
60454 /*
60455 ** Return the appropriate collating sequence for the iCol-th column of
60456 ** the result set for the compound-select statement "p".  Return NULL if
60457 ** the column has no default collating sequence.
60458 **
60459 ** The collating sequence for the compound select is taken from the
60460 ** left-most term of the select that has a collating sequence.
60461 */
60462 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
60463   CollSeq *pRet;
60464   if( p->pPrior ){
60465     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
60466   }else{
60467     pRet = 0;
60468   }
60469   if( pRet==0 ){
60470     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
60471   }
60472   return pRet;
60473 }
60474 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
60475
60476 #ifndef SQLITE_OMIT_COMPOUND_SELECT
60477 /*
60478 ** This routine is called to process a query that is really the union
60479 ** or intersection of two or more separate queries.
60480 **
60481 ** "p" points to the right-most of the two queries.  the query on the
60482 ** left is p->pPrior.  The left query could also be a compound query
60483 ** in which case this routine will be called recursively. 
60484 **
60485 ** The results of the total query are to be written into a destination
60486 ** of type eDest with parameter iParm.
60487 **
60488 ** Example 1:  Consider a three-way compound SQL statement.
60489 **
60490 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
60491 **
60492 ** This statement is parsed up as follows:
60493 **
60494 **     SELECT c FROM t3
60495 **      |
60496 **      `----->  SELECT b FROM t2
60497 **                |
60498 **                `------>  SELECT a FROM t1
60499 **
60500 ** The arrows in the diagram above represent the Select.pPrior pointer.
60501 ** So if this routine is called with p equal to the t3 query, then
60502 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
60503 **
60504 ** Notice that because of the way SQLite parses compound SELECTs, the
60505 ** individual selects always group from left to right.
60506 */
60507 static int multiSelect(
60508   Parse *pParse,        /* Parsing context */
60509   Select *p,            /* The right-most of SELECTs to be coded */
60510   int eDest,            /* \___  Store query results as specified */
60511   int iParm,            /* /     by these two parameters.         */
60512   char *aff             /* If eDest is SRT_Union, the affinity string */
60513 ){
60514   int rc = SQLITE_OK;   /* Success code from a subroutine */
60515   Select *pPrior;       /* Another SELECT immediately to our left */
60516   Vdbe *v;              /* Generate code to this VDBE */
60517   int nCol;             /* Number of columns in the result set */
60518   ExprList *pOrderBy;   /* The ORDER BY clause on p */
60519   int aSetP2[2];        /* Set P2 value of these op to number of columns */
60520   int nSetP2 = 0;       /* Number of slots in aSetP2[] used */
60521
60522   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
60523   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
60524   */
60525   if( p==0 || p->pPrior==0 ){
60526     rc = 1;
60527     goto multi_select_end;
60528   }
60529   pPrior = p->pPrior;
60530   assert( pPrior->pRightmost!=pPrior );
60531   assert( pPrior->pRightmost==p->pRightmost );
60532   if( pPrior->pOrderBy ){
60533     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
60534       selectOpName(p->op));
60535     rc = 1;
60536     goto multi_select_end;
60537   }
60538   if( pPrior->pLimit ){
60539     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
60540       selectOpName(p->op));
60541     rc = 1;
60542     goto multi_select_end;
60543   }
60544
60545   /* Make sure we have a valid query engine.  If not, create a new one.
60546   */
60547   v = sqlite3GetVdbe(pParse);
60548   if( v==0 ){
60549     rc = 1;
60550     goto multi_select_end;
60551   }
60552
60553   /* Create the destination temporary table if necessary
60554   */
60555   if( eDest==SRT_EphemTab ){
60556     assert( p->pEList );
60557     assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
60558     aSetP2[nSetP2++] = sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 0);
60559     eDest = SRT_Table;
60560   }
60561
60562   /* Generate code for the left and right SELECT statements.
60563   */
60564   pOrderBy = p->pOrderBy;
60565   switch( p->op ){
60566     case TK_ALL: {
60567       if( pOrderBy==0 ){
60568         int addr = 0;
60569         assert( !pPrior->pLimit );
60570         pPrior->pLimit = p->pLimit;
60571         pPrior->pOffset = p->pOffset;
60572         rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
60573         p->pLimit = 0;
60574         p->pOffset = 0;
60575         if( rc ){
60576           goto multi_select_end;
60577         }
60578         p->pPrior = 0;
60579         p->iLimit = pPrior->iLimit;
60580         p->iOffset = pPrior->iOffset;
60581         if( p->iLimit>=0 ){
60582           addr = sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, 0);
60583           VdbeComment((v, "# Jump ahead if LIMIT reached"));
60584         }
60585         rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
60586         p->pPrior = pPrior;
60587         if( rc ){
60588           goto multi_select_end;
60589         }
60590         if( addr ){
60591           sqlite3VdbeJumpHere(v, addr);
60592         }
60593         break;
60594       }
60595       /* For UNION ALL ... ORDER BY fall through to the next case */
60596     }
60597     case TK_EXCEPT:
60598     case TK_UNION: {
60599       int unionTab;    /* Cursor number of the temporary table holding result */
60600       int op = 0;      /* One of the SRT_ operations to apply to self */
60601       int priorOp;     /* The SRT_ operation to apply to prior selects */
60602       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
60603       int addr;
60604
60605       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
60606       if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){
60607         /* We can reuse a temporary table generated by a SELECT to our
60608         ** right.
60609         */
60610         unionTab = iParm;
60611       }else{
60612         /* We will need to create our own temporary table to hold the
60613         ** intermediate results.
60614         */
60615         unionTab = pParse->nTab++;
60616         if( processCompoundOrderBy(pParse, p, unionTab) ){
60617           rc = 1;
60618           goto multi_select_end;
60619         }
60620         addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, unionTab, 0);
60621         if( priorOp==SRT_Table ){
60622           assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
60623           aSetP2[nSetP2++] = addr;
60624         }else{
60625           assert( p->addrOpenEphm[0] == -1 );
60626           p->addrOpenEphm[0] = addr;
60627           p->pRightmost->usesEphm = 1;
60628         }
60629         createSortingIndex(pParse, p, pOrderBy);
60630         assert( p->pEList );
60631       }
60632
60633       /* Code the SELECT statements to our left
60634       */
60635       assert( !pPrior->pOrderBy );
60636       rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
60637       if( rc ){
60638         goto multi_select_end;
60639       }
60640
60641       /* Code the current SELECT statement
60642       */
60643       switch( p->op ){
60644          case TK_EXCEPT:  op = SRT_Except;   break;
60645          case TK_UNION:   op = SRT_Union;    break;
60646          case TK_ALL:     op = SRT_Table;    break;
60647       }
60648       p->pPrior = 0;
60649       p->pOrderBy = 0;
60650       p->disallowOrderBy = pOrderBy!=0;
60651       pLimit = p->pLimit;
60652       p->pLimit = 0;
60653       pOffset = p->pOffset;
60654       p->pOffset = 0;
60655       rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
60656       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
60657       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
60658       sqlite3ExprListDelete(p->pOrderBy);
60659       p->pPrior = pPrior;
60660       p->pOrderBy = pOrderBy;
60661       sqlite3ExprDelete(p->pLimit);
60662       p->pLimit = pLimit;
60663       p->pOffset = pOffset;
60664       p->iLimit = -1;
60665       p->iOffset = -1;
60666       if( rc ){
60667         goto multi_select_end;
60668       }
60669
60670
60671       /* Convert the data in the temporary table into whatever form
60672       ** it is that we currently need.
60673       */      
60674       if( eDest!=priorOp || unionTab!=iParm ){
60675         int iCont, iBreak, iStart;
60676         assert( p->pEList );
60677         if( eDest==SRT_Callback ){
60678           Select *pFirst = p;
60679           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
60680           generateColumnNames(pParse, 0, pFirst->pEList);
60681         }
60682         iBreak = sqlite3VdbeMakeLabel(v);
60683         iCont = sqlite3VdbeMakeLabel(v);
60684         computeLimitRegisters(pParse, p, iBreak);
60685         sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
60686         iStart = sqlite3VdbeCurrentAddr(v);
60687         rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
60688                              pOrderBy, -1, eDest, iParm, 
60689                              iCont, iBreak, 0);
60690         if( rc ){
60691           rc = 1;
60692           goto multi_select_end;
60693         }
60694         sqlite3VdbeResolveLabel(v, iCont);
60695         sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
60696         sqlite3VdbeResolveLabel(v, iBreak);
60697         sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
60698       }
60699       break;
60700     }
60701     case TK_INTERSECT: {
60702       int tab1, tab2;
60703       int iCont, iBreak, iStart;
60704       Expr *pLimit, *pOffset;
60705       int addr;
60706
60707       /* INTERSECT is different from the others since it requires
60708       ** two temporary tables.  Hence it has its own case.  Begin
60709       ** by allocating the tables we will need.
60710       */
60711       tab1 = pParse->nTab++;
60712       tab2 = pParse->nTab++;
60713       if( processCompoundOrderBy(pParse, p, tab1) ){
60714         rc = 1;
60715         goto multi_select_end;
60716       }
60717       createSortingIndex(pParse, p, pOrderBy);
60718
60719       addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab1, 0);
60720       assert( p->addrOpenEphm[0] == -1 );
60721       p->addrOpenEphm[0] = addr;
60722       p->pRightmost->usesEphm = 1;
60723       assert( p->pEList );
60724
60725       /* Code the SELECTs to our left into temporary table "tab1".
60726       */
60727       rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
60728       if( rc ){
60729         goto multi_select_end;
60730       }
60731
60732       /* Code the current SELECT into temporary table "tab2"
60733       */
60734       addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab2, 0);
60735       assert( p->addrOpenEphm[1] == -1 );
60736       p->addrOpenEphm[1] = addr;
60737       p->pPrior = 0;
60738       pLimit = p->pLimit;
60739       p->pLimit = 0;
60740       pOffset = p->pOffset;
60741       p->pOffset = 0;
60742       rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
60743       p->pPrior = pPrior;
60744       sqlite3ExprDelete(p->pLimit);
60745       p->pLimit = pLimit;
60746       p->pOffset = pOffset;
60747       if( rc ){
60748         goto multi_select_end;
60749       }
60750
60751       /* Generate code to take the intersection of the two temporary
60752       ** tables.
60753       */
60754       assert( p->pEList );
60755       if( eDest==SRT_Callback ){
60756         Select *pFirst = p;
60757         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
60758         generateColumnNames(pParse, 0, pFirst->pEList);
60759       }
60760       iBreak = sqlite3VdbeMakeLabel(v);
60761       iCont = sqlite3VdbeMakeLabel(v);
60762       computeLimitRegisters(pParse, p, iBreak);
60763       sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
60764       iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0);
60765       sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
60766       rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
60767                              pOrderBy, -1, eDest, iParm, 
60768                              iCont, iBreak, 0);
60769       if( rc ){
60770         rc = 1;
60771         goto multi_select_end;
60772       }
60773       sqlite3VdbeResolveLabel(v, iCont);
60774       sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
60775       sqlite3VdbeResolveLabel(v, iBreak);
60776       sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
60777       sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
60778       break;
60779     }
60780   }
60781
60782   /* Make sure all SELECTs in the statement have the same number of elements
60783   ** in their result sets.
60784   */
60785   assert( p->pEList && pPrior->pEList );
60786   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
60787     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
60788       " do not have the same number of result columns", selectOpName(p->op));
60789     rc = 1;
60790     goto multi_select_end;
60791   }
60792
60793   /* Set the number of columns in temporary tables
60794   */
60795   nCol = p->pEList->nExpr;
60796   while( nSetP2 ){
60797     sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol);
60798   }
60799
60800   /* Compute collating sequences used by either the ORDER BY clause or
60801   ** by any temporary tables needed to implement the compound select.
60802   ** Attach the KeyInfo structure to all temporary tables.  Invoke the
60803   ** ORDER BY processing if there is an ORDER BY clause.
60804   **
60805   ** This section is run by the right-most SELECT statement only.
60806   ** SELECT statements to the left always skip this part.  The right-most
60807   ** SELECT might also skip this part if it has no ORDER BY clause and
60808   ** no temp tables are required.
60809   */
60810   if( pOrderBy || p->usesEphm ){
60811     int i;                        /* Loop counter */
60812     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
60813     Select *pLoop;                /* For looping through SELECT statements */
60814     int nKeyCol;                  /* Number of entries in pKeyInfo->aCol[] */
60815     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
60816     CollSeq **aCopy;              /* A copy of pKeyInfo->aColl[] */
60817
60818     assert( p->pRightmost==p );
60819     nKeyCol = nCol + (pOrderBy ? pOrderBy->nExpr : 0);
60820     pKeyInfo = sqlite3DbMallocZero(pParse->db,
60821                        sizeof(*pKeyInfo)+nKeyCol*(sizeof(CollSeq*) + 1));
60822     if( !pKeyInfo ){
60823       rc = SQLITE_NOMEM;
60824       goto multi_select_end;
60825     }
60826
60827     pKeyInfo->enc = ENC(pParse->db);
60828     pKeyInfo->nField = nCol;
60829
60830     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
60831       *apColl = multiSelectCollSeq(pParse, p, i);
60832       if( 0==*apColl ){
60833         *apColl = pParse->db->pDfltColl;
60834       }
60835     }
60836
60837     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
60838       for(i=0; i<2; i++){
60839         int addr = pLoop->addrOpenEphm[i];
60840         if( addr<0 ){
60841           /* If [0] is unused then [1] is also unused.  So we can
60842           ** always safely abort as soon as the first unused slot is found */
60843           assert( pLoop->addrOpenEphm[1]<0 );
60844           break;
60845         }
60846         sqlite3VdbeChangeP2(v, addr, nCol);
60847         sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO);
60848         pLoop->addrOpenEphm[i] = -1;
60849       }
60850     }
60851
60852     if( pOrderBy ){
60853       struct ExprList_item *pOTerm = pOrderBy->a;
60854       int nOrderByExpr = pOrderBy->nExpr;
60855       int addr;
60856       u8 *pSortOrder;
60857
60858       /* Reuse the same pKeyInfo for the ORDER BY as was used above for
60859       ** the compound select statements.  Except we have to change out the
60860       ** pKeyInfo->aColl[] values.  Some of the aColl[] values will be
60861       ** reused when constructing the pKeyInfo for the ORDER BY, so make
60862       ** a copy.  Sufficient space to hold both the nCol entries for
60863       ** the compound select and the nOrderbyExpr entries for the ORDER BY
60864       ** was allocated above.  But we need to move the compound select
60865       ** entries out of the way before constructing the ORDER BY entries.
60866       ** Move the compound select entries into aCopy[] where they can be
60867       ** accessed and reused when constructing the ORDER BY entries.
60868       ** Because nCol might be greater than or less than nOrderByExpr
60869       ** we have to use memmove() when doing the copy.
60870       */
60871       aCopy = &pKeyInfo->aColl[nOrderByExpr];
60872       pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol];
60873       memmove(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*));
60874
60875       apColl = pKeyInfo->aColl;
60876       for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){
60877         Expr *pExpr = pOTerm->pExpr;
60878         if( (pExpr->flags & EP_ExpCollate) ){
60879           assert( pExpr->pColl!=0 );
60880           *apColl = pExpr->pColl;
60881         }else{
60882           *apColl = aCopy[pExpr->iColumn];
60883         }
60884         *pSortOrder = pOTerm->sortOrder;
60885       }
60886       assert( p->pRightmost==p );
60887       assert( p->addrOpenEphm[2]>=0 );
60888       addr = p->addrOpenEphm[2];
60889       sqlite3VdbeChangeP2(v, addr, p->pOrderBy->nExpr+2);
60890       pKeyInfo->nField = nOrderByExpr;
60891       sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
60892       pKeyInfo = 0;
60893       generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
60894     }
60895
60896     sqlite3_free(pKeyInfo);
60897   }
60898
60899 multi_select_end:
60900   return rc;
60901 }
60902 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
60903
60904 #ifndef SQLITE_OMIT_VIEW
60905 /* Forward Declarations */
60906 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
60907 static void substSelect(sqlite3*, Select *, int, ExprList *);
60908
60909 /*
60910 ** Scan through the expression pExpr.  Replace every reference to
60911 ** a column in table number iTable with a copy of the iColumn-th
60912 ** entry in pEList.  (But leave references to the ROWID column 
60913 ** unchanged.)
60914 **
60915 ** This routine is part of the flattening procedure.  A subquery
60916 ** whose result set is defined by pEList appears as entry in the
60917 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
60918 ** FORM clause entry is iTable.  This routine make the necessary 
60919 ** changes to pExpr so that it refers directly to the source table
60920 ** of the subquery rather the result set of the subquery.
60921 */
60922 static void substExpr(
60923   sqlite3 *db,        /* Report malloc errors to this connection */
60924   Expr *pExpr,        /* Expr in which substitution occurs */
60925   int iTable,         /* Table to be substituted */
60926   ExprList *pEList    /* Substitute expressions */
60927 ){
60928   if( pExpr==0 ) return;
60929   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
60930     if( pExpr->iColumn<0 ){
60931       pExpr->op = TK_NULL;
60932     }else{
60933       Expr *pNew;
60934       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
60935       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
60936       pNew = pEList->a[pExpr->iColumn].pExpr;
60937       assert( pNew!=0 );
60938       pExpr->op = pNew->op;
60939       assert( pExpr->pLeft==0 );
60940       pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft);
60941       assert( pExpr->pRight==0 );
60942       pExpr->pRight = sqlite3ExprDup(db, pNew->pRight);
60943       assert( pExpr->pList==0 );
60944       pExpr->pList = sqlite3ExprListDup(db, pNew->pList);
60945       pExpr->iTable = pNew->iTable;
60946       pExpr->pTab = pNew->pTab;
60947       pExpr->iColumn = pNew->iColumn;
60948       pExpr->iAgg = pNew->iAgg;
60949       sqlite3TokenCopy(db, &pExpr->token, &pNew->token);
60950       sqlite3TokenCopy(db, &pExpr->span, &pNew->span);
60951       pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect);
60952       pExpr->flags = pNew->flags;
60953     }
60954   }else{
60955     substExpr(db, pExpr->pLeft, iTable, pEList);
60956     substExpr(db, pExpr->pRight, iTable, pEList);
60957     substSelect(db, pExpr->pSelect, iTable, pEList);
60958     substExprList(db, pExpr->pList, iTable, pEList);
60959   }
60960 }
60961 static void substExprList(
60962   sqlite3 *db,         /* Report malloc errors here */
60963   ExprList *pList,     /* List to scan and in which to make substitutes */
60964   int iTable,          /* Table to be substituted */
60965   ExprList *pEList     /* Substitute values */
60966 ){
60967   int i;
60968   if( pList==0 ) return;
60969   for(i=0; i<pList->nExpr; i++){
60970     substExpr(db, pList->a[i].pExpr, iTable, pEList);
60971   }
60972 }
60973 static void substSelect(
60974   sqlite3 *db,         /* Report malloc errors here */
60975   Select *p,           /* SELECT statement in which to make substitutions */
60976   int iTable,          /* Table to be replaced */
60977   ExprList *pEList     /* Substitute values */
60978 ){
60979   if( !p ) return;
60980   substExprList(db, p->pEList, iTable, pEList);
60981   substExprList(db, p->pGroupBy, iTable, pEList);
60982   substExprList(db, p->pOrderBy, iTable, pEList);
60983   substExpr(db, p->pHaving, iTable, pEList);
60984   substExpr(db, p->pWhere, iTable, pEList);
60985   substSelect(db, p->pPrior, iTable, pEList);
60986 }
60987 #endif /* !defined(SQLITE_OMIT_VIEW) */
60988
60989 #ifndef SQLITE_OMIT_VIEW
60990 /*
60991 ** This routine attempts to flatten subqueries in order to speed
60992 ** execution.  It returns 1 if it makes changes and 0 if no flattening
60993 ** occurs.
60994 **
60995 ** To understand the concept of flattening, consider the following
60996 ** query:
60997 **
60998 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
60999 **
61000 ** The default way of implementing this query is to execute the
61001 ** subquery first and store the results in a temporary table, then
61002 ** run the outer query on that temporary table.  This requires two
61003 ** passes over the data.  Furthermore, because the temporary table
61004 ** has no indices, the WHERE clause on the outer query cannot be
61005 ** optimized.
61006 **
61007 ** This routine attempts to rewrite queries such as the above into
61008 ** a single flat select, like this:
61009 **
61010 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
61011 **
61012 ** The code generated for this simpification gives the same result
61013 ** but only has to scan the data once.  And because indices might 
61014 ** exist on the table t1, a complete scan of the data might be
61015 ** avoided.
61016 **
61017 ** Flattening is only attempted if all of the following are true:
61018 **
61019 **   (1)  The subquery and the outer query do not both use aggregates.
61020 **
61021 **   (2)  The subquery is not an aggregate or the outer query is not a join.
61022 **
61023 **   (3)  The subquery is not the right operand of a left outer join, or
61024 **        the subquery is not itself a join.  (Ticket #306)
61025 **
61026 **   (4)  The subquery is not DISTINCT or the outer query is not a join.
61027 **
61028 **   (5)  The subquery is not DISTINCT or the outer query does not use
61029 **        aggregates.
61030 **
61031 **   (6)  The subquery does not use aggregates or the outer query is not
61032 **        DISTINCT.
61033 **
61034 **   (7)  The subquery has a FROM clause.
61035 **
61036 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
61037 **
61038 **   (9)  The subquery does not use LIMIT or the outer query does not use
61039 **        aggregates.
61040 **
61041 **  (10)  The subquery does not use aggregates or the outer query does not
61042 **        use LIMIT.
61043 **
61044 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
61045 **
61046 **  (12)  The subquery is not the right term of a LEFT OUTER JOIN or the
61047 **        subquery has no WHERE clause.  (added by ticket #350)
61048 **
61049 **  (13)  The subquery and outer query do not both use LIMIT
61050 **
61051 **  (14)  The subquery does not use OFFSET
61052 **
61053 **  (15)  The outer query is not part of a compound select or the
61054 **        subquery does not have both an ORDER BY and a LIMIT clause.
61055 **        (See ticket #2339)
61056 **
61057 ** In this routine, the "p" parameter is a pointer to the outer query.
61058 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
61059 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
61060 **
61061 ** If flattening is not attempted, this routine is a no-op and returns 0.
61062 ** If flattening is attempted this routine returns 1.
61063 **
61064 ** All of the expression analysis must occur on both the outer query and
61065 ** the subquery before this routine runs.
61066 */
61067 static int flattenSubquery(
61068   sqlite3 *db,         /* Database connection */
61069   Select *p,           /* The parent or outer SELECT statement */
61070   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
61071   int isAgg,           /* True if outer SELECT uses aggregate functions */
61072   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
61073 ){
61074   Select *pSub;       /* The inner query or "subquery" */
61075   SrcList *pSrc;      /* The FROM clause of the outer query */
61076   SrcList *pSubSrc;   /* The FROM clause of the subquery */
61077   ExprList *pList;    /* The result set of the outer query */
61078   int iParent;        /* VDBE cursor number of the pSub result set temp table */
61079   int i;              /* Loop counter */
61080   Expr *pWhere;                    /* The WHERE clause */
61081   struct SrcList_item *pSubitem;   /* The subquery */
61082
61083   /* Check to see if flattening is permitted.  Return 0 if not.
61084   */
61085   if( p==0 ) return 0;
61086   pSrc = p->pSrc;
61087   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
61088   pSubitem = &pSrc->a[iFrom];
61089   pSub = pSubitem->pSelect;
61090   assert( pSub!=0 );
61091   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
61092   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
61093   pSubSrc = pSub->pSrc;
61094   assert( pSubSrc );
61095   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
61096   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
61097   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
61098   ** became arbitrary expressions, we were forced to add restrictions (13)
61099   ** and (14). */
61100   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
61101   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
61102   if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
61103     return 0;                                            /* Restriction (15) */
61104   }
61105   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
61106   if( (pSub->isDistinct || pSub->pLimit) 
61107          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
61108      return 0;       
61109   }
61110   if( p->isDistinct && subqueryIsAgg ) return 0;         /* Restriction (6)  */
61111   if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){
61112      return 0;                                           /* Restriction (11) */
61113   }
61114
61115   /* Restriction 3:  If the subquery is a join, make sure the subquery is 
61116   ** not used as the right operand of an outer join.  Examples of why this
61117   ** is not allowed:
61118   **
61119   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
61120   **
61121   ** If we flatten the above, we would get
61122   **
61123   **         (t1 LEFT OUTER JOIN t2) JOIN t3
61124   **
61125   ** which is not at all the same thing.
61126   */
61127   if( pSubSrc->nSrc>1 && (pSubitem->jointype & JT_OUTER)!=0 ){
61128     return 0;
61129   }
61130
61131   /* Restriction 12:  If the subquery is the right operand of a left outer
61132   ** join, make sure the subquery has no WHERE clause.
61133   ** An examples of why this is not allowed:
61134   **
61135   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
61136   **
61137   ** If we flatten the above, we would get
61138   **
61139   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
61140   **
61141   ** But the t2.x>0 test will always fail on a NULL row of t2, which
61142   ** effectively converts the OUTER JOIN into an INNER JOIN.
61143   */
61144   if( (pSubitem->jointype & JT_OUTER)!=0 && pSub->pWhere!=0 ){
61145     return 0;
61146   }
61147
61148   /* If we reach this point, it means flattening is permitted for the
61149   ** iFrom-th entry of the FROM clause in the outer query.
61150   */
61151
61152   /* Move all of the FROM elements of the subquery into the
61153   ** the FROM clause of the outer query.  Before doing this, remember
61154   ** the cursor number for the original outer query FROM element in
61155   ** iParent.  The iParent cursor will never be used.  Subsequent code
61156   ** will scan expressions looking for iParent references and replace
61157   ** those references with expressions that resolve to the subquery FROM
61158   ** elements we are now copying in.
61159   */
61160   iParent = pSubitem->iCursor;
61161   {
61162     int nSubSrc = pSubSrc->nSrc;
61163     int jointype = pSubitem->jointype;
61164
61165     sqlite3DeleteTable(pSubitem->pTab);
61166     sqlite3_free(pSubitem->zDatabase);
61167     sqlite3_free(pSubitem->zName);
61168     sqlite3_free(pSubitem->zAlias);
61169     pSubitem->pTab = 0;
61170     pSubitem->zDatabase = 0;
61171     pSubitem->zName = 0;
61172     pSubitem->zAlias = 0;
61173     if( nSubSrc>1 ){
61174       int extra = nSubSrc - 1;
61175       for(i=1; i<nSubSrc; i++){
61176         pSrc = sqlite3SrcListAppend(db, pSrc, 0, 0);
61177         if( pSrc==0 ){
61178           p->pSrc = 0;
61179           return 1;
61180         }
61181       }
61182       p->pSrc = pSrc;
61183       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
61184         pSrc->a[i] = pSrc->a[i-extra];
61185       }
61186     }
61187     for(i=0; i<nSubSrc; i++){
61188       pSrc->a[i+iFrom] = pSubSrc->a[i];
61189       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
61190     }
61191     pSrc->a[iFrom].jointype = jointype;
61192   }
61193
61194   /* Now begin substituting subquery result set expressions for 
61195   ** references to the iParent in the outer query.
61196   ** 
61197   ** Example:
61198   **
61199   **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
61200   **   \                     \_____________ subquery __________/          /
61201   **    \_____________________ outer query ______________________________/
61202   **
61203   ** We look at every expression in the outer query and every place we see
61204   ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
61205   */
61206   pList = p->pEList;
61207   for(i=0; i<pList->nExpr; i++){
61208     Expr *pExpr;
61209     if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
61210       pList->a[i].zName = 
61211              sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n);
61212     }
61213   }
61214   substExprList(db, p->pEList, iParent, pSub->pEList);
61215   if( isAgg ){
61216     substExprList(db, p->pGroupBy, iParent, pSub->pEList);
61217     substExpr(db, p->pHaving, iParent, pSub->pEList);
61218   }
61219   if( pSub->pOrderBy ){
61220     assert( p->pOrderBy==0 );
61221     p->pOrderBy = pSub->pOrderBy;
61222     pSub->pOrderBy = 0;
61223   }else if( p->pOrderBy ){
61224     substExprList(db, p->pOrderBy, iParent, pSub->pEList);
61225   }
61226   if( pSub->pWhere ){
61227     pWhere = sqlite3ExprDup(db, pSub->pWhere);
61228   }else{
61229     pWhere = 0;
61230   }
61231   if( subqueryIsAgg ){
61232     assert( p->pHaving==0 );
61233     p->pHaving = p->pWhere;
61234     p->pWhere = pWhere;
61235     substExpr(db, p->pHaving, iParent, pSub->pEList);
61236     p->pHaving = sqlite3ExprAnd(db, p->pHaving, 
61237                                 sqlite3ExprDup(db, pSub->pHaving));
61238     assert( p->pGroupBy==0 );
61239     p->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy);
61240   }else{
61241     substExpr(db, p->pWhere, iParent, pSub->pEList);
61242     p->pWhere = sqlite3ExprAnd(db, p->pWhere, pWhere);
61243   }
61244
61245   /* The flattened query is distinct if either the inner or the
61246   ** outer query is distinct. 
61247   */
61248   p->isDistinct = p->isDistinct || pSub->isDistinct;
61249
61250   /*
61251   ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
61252   **
61253   ** One is tempted to try to add a and b to combine the limits.  But this
61254   ** does not work if either limit is negative.
61255   */
61256   if( pSub->pLimit ){
61257     p->pLimit = pSub->pLimit;
61258     pSub->pLimit = 0;
61259   }
61260
61261   /* Finially, delete what is left of the subquery and return
61262   ** success.
61263   */
61264   sqlite3SelectDelete(pSub);
61265   return 1;
61266 }
61267 #endif /* SQLITE_OMIT_VIEW */
61268
61269 /*
61270 ** Analyze the SELECT statement passed in as an argument to see if it
61271 ** is a simple min() or max() query.  If it is and this query can be
61272 ** satisfied using a single seek to the beginning or end of an index,
61273 ** then generate the code for this SELECT and return 1.  If this is not a 
61274 ** simple min() or max() query, then return 0;
61275 **
61276 ** A simply min() or max() query looks like this:
61277 **
61278 **    SELECT min(a) FROM table;
61279 **    SELECT max(a) FROM table;
61280 **
61281 ** The query may have only a single table in its FROM argument.  There
61282 ** can be no GROUP BY or HAVING or WHERE clauses.  The result set must
61283 ** be the min() or max() of a single column of the table.  The column
61284 ** in the min() or max() function must be indexed.
61285 **
61286 ** The parameters to this routine are the same as for sqlite3Select().
61287 ** See the header comment on that routine for additional information.
61288 */
61289 static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
61290   Expr *pExpr;
61291   int iCol;
61292   Table *pTab;
61293   Index *pIdx;
61294   int base;
61295   Vdbe *v;
61296   int seekOp;
61297   ExprList *pEList, *pList, eList;
61298   struct ExprList_item eListItem;
61299   SrcList *pSrc;
61300   int brk;
61301   int iDb;
61302
61303   /* Check to see if this query is a simple min() or max() query.  Return
61304   ** zero if it is  not.
61305   */
61306   if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
61307   pSrc = p->pSrc;
61308   if( pSrc->nSrc!=1 ) return 0;
61309   pEList = p->pEList;
61310   if( pEList->nExpr!=1 ) return 0;
61311   pExpr = pEList->a[0].pExpr;
61312   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
61313   pList = pExpr->pList;
61314   if( pList==0 || pList->nExpr!=1 ) return 0;
61315   if( pExpr->token.n!=3 ) return 0;
61316   if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
61317     seekOp = OP_Rewind;
61318   }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
61319     seekOp = OP_Last;
61320   }else{
61321     return 0;
61322   }
61323   pExpr = pList->a[0].pExpr;
61324   if( pExpr->op!=TK_COLUMN ) return 0;
61325   iCol = pExpr->iColumn;
61326   pTab = pSrc->a[0].pTab;
61327
61328   /* This optimization cannot be used with virtual tables. */
61329   if( IsVirtual(pTab) ) return 0;
61330
61331   /* If we get to here, it means the query is of the correct form.
61332   ** Check to make sure we have an index and make pIdx point to the
61333   ** appropriate index.  If the min() or max() is on an INTEGER PRIMARY
61334   ** key column, no index is necessary so set pIdx to NULL.  If no
61335   ** usable index is found, return 0.
61336   */
61337   if( iCol<0 ){
61338     pIdx = 0;
61339   }else{
61340     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
61341     if( pColl==0 ) return 0;
61342     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
61343       assert( pIdx->nColumn>=1 );
61344       if( pIdx->aiColumn[0]==iCol && 
61345           0==sqlite3StrICmp(pIdx->azColl[0], pColl->zName) ){
61346         break;
61347       }
61348     }
61349     if( pIdx==0 ) return 0;
61350   }
61351
61352   /* Identify column types if we will be using the callback.  This
61353   ** step is skipped if the output is going to a table or a memory cell.
61354   ** The column names have already been generated in the calling function.
61355   */
61356   v = sqlite3GetVdbe(pParse);
61357   if( v==0 ) return 0;
61358
61359   /* If the output is destined for a temporary table, open that table.
61360   */
61361   if( eDest==SRT_EphemTab ){
61362     sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 1);
61363   }
61364
61365   /* Generating code to find the min or the max.  Basically all we have
61366   ** to do is find the first or the last entry in the chosen index.  If
61367   ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
61368   ** or last entry in the main table.
61369   */
61370   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
61371   assert( iDb>=0 || pTab->isEphem );
61372   sqlite3CodeVerifySchema(pParse, iDb);
61373   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
61374   base = pSrc->a[0].iCursor;
61375   brk = sqlite3VdbeMakeLabel(v);
61376   computeLimitRegisters(pParse, p, brk);
61377   if( pSrc->a[0].pSelect==0 ){
61378     sqlite3OpenTable(pParse, base, iDb, pTab, OP_OpenRead);
61379   }
61380   if( pIdx==0 ){
61381     sqlite3VdbeAddOp(v, seekOp, base, 0);
61382   }else{
61383     /* Even though the cursor used to open the index here is closed
61384     ** as soon as a single value has been read from it, allocate it
61385     ** using (pParse->nTab++) to prevent the cursor id from being 
61386     ** reused. This is important for statements of the form 
61387     ** "INSERT INTO x SELECT max() FROM x".
61388     */
61389     int iIdx;
61390     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
61391     iIdx = pParse->nTab++;
61392     assert( pIdx->pSchema==pTab->pSchema );
61393     sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
61394     sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum, 
61395         (char*)pKey, P3_KEYINFO_HANDOFF);
61396     if( seekOp==OP_Rewind ){
61397       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
61398       sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
61399       seekOp = OP_MoveGt;
61400     }
61401     if( pIdx->aSortOrder[0]==SQLITE_SO_DESC ){
61402       /* Ticket #2514: invert the seek operator if we are using
61403       ** a descending index. */
61404       if( seekOp==OP_Last ){
61405         seekOp = OP_Rewind;
61406       }else{
61407         assert( seekOp==OP_MoveGt );
61408         seekOp = OP_MoveLt;
61409       }
61410     }
61411     sqlite3VdbeAddOp(v, seekOp, iIdx, 0);
61412     sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0);
61413     sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
61414     sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
61415   }
61416   eList.nExpr = 1;
61417   memset(&eListItem, 0, sizeof(eListItem));
61418   eList.a = &eListItem;
61419   eList.a[0].pExpr = pExpr;
61420   selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, brk, brk, 0);
61421   sqlite3VdbeResolveLabel(v, brk);
61422   sqlite3VdbeAddOp(v, OP_Close, base, 0);
61423   
61424   return 1;
61425 }
61426
61427 /*
61428 ** This routine resolves any names used in the result set of the
61429 ** supplied SELECT statement. If the SELECT statement being resolved
61430 ** is a sub-select, then pOuterNC is a pointer to the NameContext 
61431 ** of the parent SELECT.
61432 */
61433 SQLITE_PRIVATE int sqlite3SelectResolve(
61434   Parse *pParse,         /* The parser context */
61435   Select *p,             /* The SELECT statement being coded. */
61436   NameContext *pOuterNC  /* The outer name context. May be NULL. */
61437 ){
61438   ExprList *pEList;          /* Result set. */
61439   int i;                     /* For-loop variable used in multiple places */
61440   NameContext sNC;           /* Local name-context */
61441   ExprList *pGroupBy;        /* The group by clause */
61442
61443   /* If this routine has run before, return immediately. */
61444   if( p->isResolved ){
61445     assert( !pOuterNC );
61446     return SQLITE_OK;
61447   }
61448   p->isResolved = 1;
61449
61450   /* If there have already been errors, do nothing. */
61451   if( pParse->nErr>0 ){
61452     return SQLITE_ERROR;
61453   }
61454
61455   /* Prepare the select statement. This call will allocate all cursors
61456   ** required to handle the tables and subqueries in the FROM clause.
61457   */
61458   if( prepSelectStmt(pParse, p) ){
61459     return SQLITE_ERROR;
61460   }
61461
61462   /* Resolve the expressions in the LIMIT and OFFSET clauses. These
61463   ** are not allowed to refer to any names, so pass an empty NameContext.
61464   */
61465   memset(&sNC, 0, sizeof(sNC));
61466   sNC.pParse = pParse;
61467   if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
61468       sqlite3ExprResolveNames(&sNC, p->pOffset) ){
61469     return SQLITE_ERROR;
61470   }
61471
61472   /* Set up the local name-context to pass to ExprResolveNames() to
61473   ** resolve the expression-list.
61474   */
61475   sNC.allowAgg = 1;
61476   sNC.pSrcList = p->pSrc;
61477   sNC.pNext = pOuterNC;
61478
61479   /* Resolve names in the result set. */
61480   pEList = p->pEList;
61481   if( !pEList ) return SQLITE_ERROR;
61482   for(i=0; i<pEList->nExpr; i++){
61483     Expr *pX = pEList->a[i].pExpr;
61484     if( sqlite3ExprResolveNames(&sNC, pX) ){
61485       return SQLITE_ERROR;
61486     }
61487   }
61488
61489   /* If there are no aggregate functions in the result-set, and no GROUP BY 
61490   ** expression, do not allow aggregates in any of the other expressions.
61491   */
61492   assert( !p->isAgg );
61493   pGroupBy = p->pGroupBy;
61494   if( pGroupBy || sNC.hasAgg ){
61495     p->isAgg = 1;
61496   }else{
61497     sNC.allowAgg = 0;
61498   }
61499
61500   /* If a HAVING clause is present, then there must be a GROUP BY clause.
61501   */
61502   if( p->pHaving && !pGroupBy ){
61503     sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
61504     return SQLITE_ERROR;
61505   }
61506
61507   /* Add the expression list to the name-context before parsing the
61508   ** other expressions in the SELECT statement. This is so that
61509   ** expressions in the WHERE clause (etc.) can refer to expressions by
61510   ** aliases in the result set.
61511   **
61512   ** Minor point: If this is the case, then the expression will be
61513   ** re-evaluated for each reference to it.
61514   */
61515   sNC.pEList = p->pEList;
61516   if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
61517      sqlite3ExprResolveNames(&sNC, p->pHaving) ){
61518     return SQLITE_ERROR;
61519   }
61520   if( p->pPrior==0 ){
61521     if( processOrderGroupBy(pParse, p, p->pOrderBy, 1, &sNC.hasAgg) ){
61522       return SQLITE_ERROR;
61523     }
61524   }
61525   if( processOrderGroupBy(pParse, p, pGroupBy, 0, &sNC.hasAgg) ){
61526     return SQLITE_ERROR;
61527   }
61528
61529   if( pParse->db->mallocFailed ){
61530     return SQLITE_NOMEM;
61531   }
61532
61533   /* Make sure the GROUP BY clause does not contain aggregate functions.
61534   */
61535   if( pGroupBy ){
61536     struct ExprList_item *pItem;
61537   
61538     for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
61539       if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
61540         sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
61541             "the GROUP BY clause");
61542         return SQLITE_ERROR;
61543       }
61544     }
61545   }
61546
61547   /* If this is one SELECT of a compound, be sure to resolve names
61548   ** in the other SELECTs.
61549   */
61550   if( p->pPrior ){
61551     return sqlite3SelectResolve(pParse, p->pPrior, pOuterNC);
61552   }else{
61553     return SQLITE_OK;
61554   }
61555 }
61556
61557 /*
61558 ** Reset the aggregate accumulator.
61559 **
61560 ** The aggregate accumulator is a set of memory cells that hold
61561 ** intermediate results while calculating an aggregate.  This
61562 ** routine simply stores NULLs in all of those memory cells.
61563 */
61564 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
61565   Vdbe *v = pParse->pVdbe;
61566   int i;
61567   struct AggInfo_func *pFunc;
61568   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
61569     return;
61570   }
61571   for(i=0; i<pAggInfo->nColumn; i++){
61572     sqlite3VdbeAddOp(v, OP_MemNull, pAggInfo->aCol[i].iMem, 0);
61573   }
61574   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
61575     sqlite3VdbeAddOp(v, OP_MemNull, pFunc->iMem, 0);
61576     if( pFunc->iDistinct>=0 ){
61577       Expr *pE = pFunc->pExpr;
61578       if( pE->pList==0 || pE->pList->nExpr!=1 ){
61579         sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
61580            "by an expression");
61581         pFunc->iDistinct = -1;
61582       }else{
61583         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
61584         sqlite3VdbeOp3(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 
61585                           (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
61586       }
61587     }
61588   }
61589 }
61590
61591 /*
61592 ** Invoke the OP_AggFinalize opcode for every aggregate function
61593 ** in the AggInfo structure.
61594 */
61595 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
61596   Vdbe *v = pParse->pVdbe;
61597   int i;
61598   struct AggInfo_func *pF;
61599   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
61600     ExprList *pList = pF->pExpr->pList;
61601     sqlite3VdbeOp3(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0,
61602                       (void*)pF->pFunc, P3_FUNCDEF);
61603   }
61604 }
61605
61606 /*
61607 ** Update the accumulator memory cells for an aggregate based on
61608 ** the current cursor position.
61609 */
61610 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
61611   Vdbe *v = pParse->pVdbe;
61612   int i;
61613   struct AggInfo_func *pF;
61614   struct AggInfo_col *pC;
61615
61616   pAggInfo->directMode = 1;
61617   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
61618     int nArg;
61619     int addrNext = 0;
61620     ExprList *pList = pF->pExpr->pList;
61621     if( pList ){
61622       nArg = pList->nExpr;
61623       sqlite3ExprCodeExprList(pParse, pList);
61624     }else{
61625       nArg = 0;
61626     }
61627     if( pF->iDistinct>=0 ){
61628       addrNext = sqlite3VdbeMakeLabel(v);
61629       assert( nArg==1 );
61630       codeDistinct(v, pF->iDistinct, addrNext, 1);
61631     }
61632     if( pF->pFunc->needCollSeq ){
61633       CollSeq *pColl = 0;
61634       struct ExprList_item *pItem;
61635       int j;
61636       assert( pList!=0 );  /* pList!=0 if pF->pFunc->needCollSeq is true */
61637       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
61638         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
61639       }
61640       if( !pColl ){
61641         pColl = pParse->db->pDfltColl;
61642       }
61643       sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
61644     }
61645     sqlite3VdbeOp3(v, OP_AggStep, pF->iMem, nArg, (void*)pF->pFunc, P3_FUNCDEF);
61646     if( addrNext ){
61647       sqlite3VdbeResolveLabel(v, addrNext);
61648     }
61649   }
61650   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
61651     sqlite3ExprCode(pParse, pC->pExpr);
61652     sqlite3VdbeAddOp(v, OP_MemStore, pC->iMem, 1);
61653   }
61654   pAggInfo->directMode = 0;
61655 }
61656
61657
61658 /*
61659 ** Generate code for the given SELECT statement.
61660 **
61661 ** The results are distributed in various ways depending on the
61662 ** value of eDest and iParm.
61663 **
61664 **     eDest Value       Result
61665 **     ------------    -------------------------------------------
61666 **     SRT_Callback    Invoke the callback for each row of the result.
61667 **
61668 **     SRT_Mem         Store first result in memory cell iParm
61669 **
61670 **     SRT_Set         Store results as keys of table iParm.
61671 **
61672 **     SRT_Union       Store results as a key in a temporary table iParm
61673 **
61674 **     SRT_Except      Remove results from the temporary table iParm.
61675 **
61676 **     SRT_Table       Store results in temporary table iParm
61677 **
61678 ** The table above is incomplete.  Additional eDist value have be added
61679 ** since this comment was written.  See the selectInnerLoop() function for
61680 ** a complete listing of the allowed values of eDest and their meanings.
61681 **
61682 ** This routine returns the number of errors.  If any errors are
61683 ** encountered, then an appropriate error message is left in
61684 ** pParse->zErrMsg.
61685 **
61686 ** This routine does NOT free the Select structure passed in.  The
61687 ** calling function needs to do that.
61688 **
61689 ** The pParent, parentTab, and *pParentAgg fields are filled in if this
61690 ** SELECT is a subquery.  This routine may try to combine this SELECT
61691 ** with its parent to form a single flat query.  In so doing, it might
61692 ** change the parent query from a non-aggregate to an aggregate query.
61693 ** For that reason, the pParentAgg flag is passed as a pointer, so it
61694 ** can be changed.
61695 **
61696 ** Example 1:   The meaning of the pParent parameter.
61697 **
61698 **    SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
61699 **    \                      \_______ subquery _______/        /
61700 **     \                                                      /
61701 **      \____________________ outer query ___________________/
61702 **
61703 ** This routine is called for the outer query first.   For that call,
61704 ** pParent will be NULL.  During the processing of the outer query, this 
61705 ** routine is called recursively to handle the subquery.  For the recursive
61706 ** call, pParent will point to the outer query.  Because the subquery is
61707 ** the second element in a three-way join, the parentTab parameter will
61708 ** be 1 (the 2nd value of a 0-indexed array.)
61709 */
61710 SQLITE_PRIVATE int sqlite3Select(
61711   Parse *pParse,         /* The parser context */
61712   Select *p,             /* The SELECT statement being coded. */
61713   int eDest,             /* How to dispose of the results */
61714   int iParm,             /* A parameter used by the eDest disposal method */
61715   Select *pParent,       /* Another SELECT for which this is a sub-query */
61716   int parentTab,         /* Index in pParent->pSrc of this query */
61717   int *pParentAgg,       /* True if pParent uses aggregate functions */
61718   char *aff              /* If eDest is SRT_Union, the affinity string */
61719 ){
61720   int i, j;              /* Loop counters */
61721   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
61722   Vdbe *v;               /* The virtual machine under construction */
61723   int isAgg;             /* True for select lists like "count(*)" */
61724   ExprList *pEList;      /* List of columns to extract. */
61725   SrcList *pTabList;     /* List of tables to select from */
61726   Expr *pWhere;          /* The WHERE clause.  May be NULL */
61727   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
61728   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
61729   Expr *pHaving;         /* The HAVING clause.  May be NULL */
61730   int isDistinct;        /* True if the DISTINCT keyword is present */
61731   int distinct;          /* Table to use for the distinct set */
61732   int rc = 1;            /* Value to return from this function */
61733   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
61734   AggInfo sAggInfo;      /* Information used by aggregate queries */
61735   int iEnd;              /* Address of the end of the query */
61736   sqlite3 *db;           /* The database connection */
61737
61738   db = pParse->db;
61739   if( p==0 || db->mallocFailed || pParse->nErr ){
61740     return 1;
61741   }
61742   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
61743   memset(&sAggInfo, 0, sizeof(sAggInfo));
61744
61745   pOrderBy = p->pOrderBy;
61746   if( IgnorableOrderby(eDest) ){
61747     p->pOrderBy = 0;
61748   }
61749   if( sqlite3SelectResolve(pParse, p, 0) ){
61750     goto select_end;
61751   }
61752   p->pOrderBy = pOrderBy;
61753
61754 #ifndef SQLITE_OMIT_COMPOUND_SELECT
61755   /* If there is are a sequence of queries, do the earlier ones first.
61756   */
61757   if( p->pPrior ){
61758     if( p->pRightmost==0 ){
61759       Select *pLoop, *pRight = 0;
61760       int cnt = 0;
61761       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
61762         pLoop->pRightmost = p;
61763         pLoop->pNext = pRight;
61764         pRight = pLoop;
61765       }
61766       if( SQLITE_MAX_COMPOUND_SELECT>0 && cnt>SQLITE_MAX_COMPOUND_SELECT ){
61767         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
61768         return 1;
61769       }
61770     }
61771     return multiSelect(pParse, p, eDest, iParm, aff);
61772   }
61773 #endif
61774
61775   /* Make local copies of the parameters for this query.
61776   */
61777   pTabList = p->pSrc;
61778   pWhere = p->pWhere;
61779   pGroupBy = p->pGroupBy;
61780   pHaving = p->pHaving;
61781   isAgg = p->isAgg;
61782   isDistinct = p->isDistinct;
61783   pEList = p->pEList;
61784   if( pEList==0 ) goto select_end;
61785
61786   /* 
61787   ** Do not even attempt to generate any code if we have already seen
61788   ** errors before this routine starts.
61789   */
61790   if( pParse->nErr>0 ) goto select_end;
61791
61792   /* If writing to memory or generating a set
61793   ** only a single column may be output.
61794   */
61795 #ifndef SQLITE_OMIT_SUBQUERY
61796   if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){
61797     goto select_end;
61798   }
61799 #endif
61800
61801   /* ORDER BY is ignored for some destinations.
61802   */
61803   if( IgnorableOrderby(eDest) ){
61804     pOrderBy = 0;
61805   }
61806
61807   /* Begin generating code.
61808   */
61809   v = sqlite3GetVdbe(pParse);
61810   if( v==0 ) goto select_end;
61811
61812   /* Generate code for all sub-queries in the FROM clause
61813   */
61814 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
61815   for(i=0; i<pTabList->nSrc; i++){
61816     const char *zSavedAuthContext = 0;
61817     int needRestoreContext;
61818     struct SrcList_item *pItem = &pTabList->a[i];
61819
61820     if( pItem->pSelect==0 || pItem->isPopulated ) continue;
61821     if( pItem->zName!=0 ){
61822       zSavedAuthContext = pParse->zAuthContext;
61823       pParse->zAuthContext = pItem->zName;
61824       needRestoreContext = 1;
61825     }else{
61826       needRestoreContext = 0;
61827     }
61828 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
61829     /* Increment Parse.nHeight by the height of the largest expression
61830     ** tree refered to by this, the parent select. The child select
61831     ** may contain expression trees of at most
61832     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
61833     ** more conservative than necessary, but much easier than enforcing
61834     ** an exact limit.
61835     */
61836     pParse->nHeight += sqlite3SelectExprHeight(p);
61837 #endif
61838     sqlite3Select(pParse, pItem->pSelect, SRT_EphemTab, 
61839                  pItem->iCursor, p, i, &isAgg, 0);
61840     if( db->mallocFailed ){
61841       goto select_end;
61842     }
61843 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
61844     pParse->nHeight -= sqlite3SelectExprHeight(p);
61845 #endif
61846     if( needRestoreContext ){
61847       pParse->zAuthContext = zSavedAuthContext;
61848     }
61849     pTabList = p->pSrc;
61850     pWhere = p->pWhere;
61851     if( !IgnorableOrderby(eDest) ){
61852       pOrderBy = p->pOrderBy;
61853     }
61854     pGroupBy = p->pGroupBy;
61855     pHaving = p->pHaving;
61856     isDistinct = p->isDistinct;
61857   }
61858 #endif
61859
61860   /* Check for the special case of a min() or max() function by itself
61861   ** in the result set.
61862   */
61863   if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
61864     rc = 0;
61865     goto select_end;
61866   }
61867
61868   /* Check to see if this is a subquery that can be "flattened" into its parent.
61869   ** If flattening is a possiblity, do so and return immediately.  
61870   */
61871 #ifndef SQLITE_OMIT_VIEW
61872   if( pParent && pParentAgg &&
61873       flattenSubquery(db, pParent, parentTab, *pParentAgg, isAgg) ){
61874     if( isAgg ) *pParentAgg = 1;
61875     goto select_end;
61876   }
61877 #endif
61878
61879   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
61880   ** GROUP BY may use an index, DISTINCT never does.
61881   */
61882   if( p->isDistinct && !p->isAgg && !p->pGroupBy ){
61883     p->pGroupBy = sqlite3ExprListDup(db, p->pEList);
61884     pGroupBy = p->pGroupBy;
61885     p->isDistinct = 0;
61886     isDistinct = 0;
61887   }
61888
61889   /* If there is an ORDER BY clause, then this sorting
61890   ** index might end up being unused if the data can be 
61891   ** extracted in pre-sorted order.  If that is the case, then the
61892   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
61893   ** we figure out that the sorting index is not needed.  The addrSortIndex
61894   ** variable is used to facilitate that change.
61895   */
61896   if( pOrderBy ){
61897     KeyInfo *pKeyInfo;
61898     if( pParse->nErr ){
61899       goto select_end;
61900     }
61901     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
61902     pOrderBy->iECursor = pParse->nTab++;
61903     p->addrOpenEphm[2] = addrSortIndex =
61904       sqlite3VdbeOp3(v, OP_OpenEphemeral, pOrderBy->iECursor, pOrderBy->nExpr+2,                     (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
61905   }else{
61906     addrSortIndex = -1;
61907   }
61908
61909   /* If the output is destined for a temporary table, open that table.
61910   */
61911   if( eDest==SRT_EphemTab ){
61912     sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, pEList->nExpr);
61913   }
61914
61915   /* Set the limiter.
61916   */
61917   iEnd = sqlite3VdbeMakeLabel(v);
61918   computeLimitRegisters(pParse, p, iEnd);
61919
61920   /* Open a virtual index to use for the distinct set.
61921   */
61922   if( isDistinct ){
61923     KeyInfo *pKeyInfo;
61924     assert( isAgg || pGroupBy );
61925     distinct = pParse->nTab++;
61926     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
61927     sqlite3VdbeOp3(v, OP_OpenEphemeral, distinct, 0, 
61928                         (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
61929   }else{
61930     distinct = -1;
61931   }
61932
61933   /* Aggregate and non-aggregate queries are handled differently */
61934   if( !isAgg && pGroupBy==0 ){
61935     /* This case is for non-aggregate queries
61936     ** Begin the database scan
61937     */
61938     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy);
61939     if( pWInfo==0 ) goto select_end;
61940
61941     /* If sorting index that was created by a prior OP_OpenEphemeral 
61942     ** instruction ended up not being needed, then change the OP_OpenEphemeral
61943     ** into an OP_Noop.
61944     */
61945     if( addrSortIndex>=0 && pOrderBy==0 ){
61946       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
61947       p->addrOpenEphm[2] = -1;
61948     }
61949
61950     /* Use the standard inner loop
61951     */
61952     assert(!isDistinct);
61953     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, eDest,
61954                     iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
61955        goto select_end;
61956     }
61957
61958     /* End the database scan loop.
61959     */
61960     sqlite3WhereEnd(pWInfo);
61961   }else{
61962     /* This is the processing for aggregate queries */
61963     NameContext sNC;    /* Name context for processing aggregate information */
61964     int iAMem;          /* First Mem address for storing current GROUP BY */
61965     int iBMem;          /* First Mem address for previous GROUP BY */
61966     int iUseFlag;       /* Mem address holding flag indicating that at least
61967                         ** one row of the input to the aggregator has been
61968                         ** processed */
61969     int iAbortFlag;     /* Mem address which causes query abort if positive */
61970     int groupBySort;    /* Rows come from source in GROUP BY order */
61971
61972
61973     /* The following variables hold addresses or labels for parts of the
61974     ** virtual machine program we are putting together */
61975     int addrOutputRow;      /* Start of subroutine that outputs a result row */
61976     int addrSetAbort;       /* Set the abort flag and return */
61977     int addrInitializeLoop; /* Start of code that initializes the input loop */
61978     int addrTopOfLoop;      /* Top of the input loop */
61979     int addrGroupByChange;  /* Code that runs when any GROUP BY term changes */
61980     int addrProcessRow;     /* Code to process a single input row */
61981     int addrEnd;            /* End of all processing */
61982     int addrSortingIdx;     /* The OP_OpenEphemeral for the sorting index */
61983     int addrReset;          /* Subroutine for resetting the accumulator */
61984
61985     addrEnd = sqlite3VdbeMakeLabel(v);
61986
61987     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
61988     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
61989     ** SELECT statement.
61990     */
61991     memset(&sNC, 0, sizeof(sNC));
61992     sNC.pParse = pParse;
61993     sNC.pSrcList = pTabList;
61994     sNC.pAggInfo = &sAggInfo;
61995     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
61996     sAggInfo.pGroupBy = pGroupBy;
61997     if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){
61998       goto select_end;
61999     }
62000     if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){
62001       goto select_end;
62002     }
62003     if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){
62004       goto select_end;
62005     }
62006     sAggInfo.nAccumulator = sAggInfo.nColumn;
62007     for(i=0; i<sAggInfo.nFunc; i++){
62008       if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){
62009         goto select_end;
62010       }
62011     }
62012     if( db->mallocFailed ) goto select_end;
62013
62014     /* Processing for aggregates with GROUP BY is very different and
62015     ** much more complex than aggregates without a GROUP BY.
62016     */
62017     if( pGroupBy ){
62018       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
62019
62020       /* Create labels that we will be needing
62021       */
62022      
62023       addrInitializeLoop = sqlite3VdbeMakeLabel(v);
62024       addrGroupByChange = sqlite3VdbeMakeLabel(v);
62025       addrProcessRow = sqlite3VdbeMakeLabel(v);
62026
62027       /* If there is a GROUP BY clause we might need a sorting index to
62028       ** implement it.  Allocate that sorting index now.  If it turns out
62029       ** that we do not need it after all, the OpenEphemeral instruction
62030       ** will be converted into a Noop.  
62031       */
62032       sAggInfo.sortingIdx = pParse->nTab++;
62033       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
62034       addrSortingIdx =
62035           sqlite3VdbeOp3(v, OP_OpenEphemeral, sAggInfo.sortingIdx,
62036                          sAggInfo.nSortingColumn,
62037                          (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
62038
62039       /* Initialize memory locations used by GROUP BY aggregate processing
62040       */
62041       iUseFlag = pParse->nMem++;
62042       iAbortFlag = pParse->nMem++;
62043       iAMem = pParse->nMem;
62044       pParse->nMem += pGroupBy->nExpr;
62045       iBMem = pParse->nMem;
62046       pParse->nMem += pGroupBy->nExpr;
62047       sqlite3VdbeAddOp(v, OP_MemInt, 0, iAbortFlag);
62048       VdbeComment((v, "# clear abort flag"));
62049       sqlite3VdbeAddOp(v, OP_MemInt, 0, iUseFlag);
62050       VdbeComment((v, "# indicate accumulator empty"));
62051       sqlite3VdbeAddOp(v, OP_Goto, 0, addrInitializeLoop);
62052
62053       /* Generate a subroutine that outputs a single row of the result
62054       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
62055       ** is less than or equal to zero, the subroutine is a no-op.  If
62056       ** the processing calls for the query to abort, this subroutine
62057       ** increments the iAbortFlag memory location before returning in
62058       ** order to signal the caller to abort.
62059       */
62060       addrSetAbort = sqlite3VdbeCurrentAddr(v);
62061       sqlite3VdbeAddOp(v, OP_MemInt, 1, iAbortFlag);
62062       VdbeComment((v, "# set abort flag"));
62063       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
62064       addrOutputRow = sqlite3VdbeCurrentAddr(v);
62065       sqlite3VdbeAddOp(v, OP_IfMemPos, iUseFlag, addrOutputRow+2);
62066       VdbeComment((v, "# Groupby result generator entry point"));
62067       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
62068       finalizeAggFunctions(pParse, &sAggInfo);
62069       if( pHaving ){
62070         sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1);
62071       }
62072       rc = selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
62073                            distinct, eDest, iParm, 
62074                            addrOutputRow+1, addrSetAbort, aff);
62075       if( rc ){
62076         goto select_end;
62077       }
62078       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
62079       VdbeComment((v, "# end groupby result generator"));
62080
62081       /* Generate a subroutine that will reset the group-by accumulator
62082       */
62083       addrReset = sqlite3VdbeCurrentAddr(v);
62084       resetAccumulator(pParse, &sAggInfo);
62085       sqlite3VdbeAddOp(v, OP_Return, 0, 0);
62086
62087       /* Begin a loop that will extract all source rows in GROUP BY order.
62088       ** This might involve two separate loops with an OP_Sort in between, or
62089       ** it might be a single loop that uses an index to extract information
62090       ** in the right order to begin with.
62091       */
62092       sqlite3VdbeResolveLabel(v, addrInitializeLoop);
62093       sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
62094       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy);
62095       if( pWInfo==0 ) goto select_end;
62096       if( pGroupBy==0 ){
62097         /* The optimizer is able to deliver rows in group by order so
62098         ** we do not have to sort.  The OP_OpenEphemeral table will be
62099         ** cancelled later because we still need to use the pKeyInfo
62100         */
62101         pGroupBy = p->pGroupBy;
62102         groupBySort = 0;
62103       }else{
62104         /* Rows are coming out in undetermined order.  We have to push
62105         ** each row into a sorting index, terminate the first loop,
62106         ** then loop over the sorting index in order to get the output
62107         ** in sorted order
62108         */
62109         groupBySort = 1;
62110         sqlite3ExprCodeExprList(pParse, pGroupBy);
62111         sqlite3VdbeAddOp(v, OP_Sequence, sAggInfo.sortingIdx, 0);
62112         j = pGroupBy->nExpr+1;
62113         for(i=0; i<sAggInfo.nColumn; i++){
62114           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
62115           if( pCol->iSorterColumn<j ) continue;
62116           sqlite3ExprCodeGetColumn(v, pCol->pTab, pCol->iColumn, pCol->iTable);
62117           j++;
62118         }
62119         sqlite3VdbeAddOp(v, OP_MakeRecord, j, 0);
62120         sqlite3VdbeAddOp(v, OP_IdxInsert, sAggInfo.sortingIdx, 0);
62121         sqlite3WhereEnd(pWInfo);
62122         sqlite3VdbeAddOp(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
62123         VdbeComment((v, "# GROUP BY sort"));
62124         sAggInfo.useSortingIdx = 1;
62125       }
62126
62127       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
62128       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
62129       ** Then compare the current GROUP BY terms against the GROUP BY terms
62130       ** from the previous row currently stored in a0, a1, a2...
62131       */
62132       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
62133       for(j=0; j<pGroupBy->nExpr; j++){
62134         if( groupBySort ){
62135           sqlite3VdbeAddOp(v, OP_Column, sAggInfo.sortingIdx, j);
62136         }else{
62137           sAggInfo.directMode = 1;
62138           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr);
62139         }
62140         sqlite3VdbeAddOp(v, OP_MemStore, iBMem+j, j<pGroupBy->nExpr-1);
62141       }
62142       for(j=pGroupBy->nExpr-1; j>=0; j--){
62143         if( j<pGroupBy->nExpr-1 ){
62144           sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0);
62145         }
62146         sqlite3VdbeAddOp(v, OP_MemLoad, iAMem+j, 0);
62147         if( j==0 ){
62148           sqlite3VdbeAddOp(v, OP_Eq, 0x200, addrProcessRow);
62149         }else{
62150           sqlite3VdbeAddOp(v, OP_Ne, 0x200, addrGroupByChange);
62151         }
62152         sqlite3VdbeChangeP3(v, -1, (void*)pKeyInfo->aColl[j], P3_COLLSEQ);
62153       }
62154
62155       /* Generate code that runs whenever the GROUP BY changes.
62156       ** Change in the GROUP BY are detected by the previous code
62157       ** block.  If there were no changes, this block is skipped.
62158       **
62159       ** This code copies current group by terms in b0,b1,b2,...
62160       ** over to a0,a1,a2.  It then calls the output subroutine
62161       ** and resets the aggregate accumulator registers in preparation
62162       ** for the next GROUP BY batch.
62163       */
62164       sqlite3VdbeResolveLabel(v, addrGroupByChange);
62165       for(j=0; j<pGroupBy->nExpr; j++){
62166         sqlite3VdbeAddOp(v, OP_MemMove, iAMem+j, iBMem+j);
62167       }
62168       sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
62169       VdbeComment((v, "# output one row"));
62170       sqlite3VdbeAddOp(v, OP_IfMemPos, iAbortFlag, addrEnd);
62171       VdbeComment((v, "# check abort flag"));
62172       sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
62173       VdbeComment((v, "# reset accumulator"));
62174
62175       /* Update the aggregate accumulators based on the content of
62176       ** the current row
62177       */
62178       sqlite3VdbeResolveLabel(v, addrProcessRow);
62179       updateAccumulator(pParse, &sAggInfo);
62180       sqlite3VdbeAddOp(v, OP_MemInt, 1, iUseFlag);
62181       VdbeComment((v, "# indicate data in accumulator"));
62182
62183       /* End of the loop
62184       */
62185       if( groupBySort ){
62186         sqlite3VdbeAddOp(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
62187       }else{
62188         sqlite3WhereEnd(pWInfo);
62189         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
62190       }
62191
62192       /* Output the final row of result
62193       */
62194       sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
62195       VdbeComment((v, "# output final row"));
62196       
62197     } /* endif pGroupBy */
62198     else {
62199       /* This case runs if the aggregate has no GROUP BY clause.  The
62200       ** processing is much simpler since there is only a single row
62201       ** of output.
62202       */
62203       resetAccumulator(pParse, &sAggInfo);
62204       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
62205       if( pWInfo==0 ) goto select_end;
62206       updateAccumulator(pParse, &sAggInfo);
62207       sqlite3WhereEnd(pWInfo);
62208       finalizeAggFunctions(pParse, &sAggInfo);
62209       pOrderBy = 0;
62210       if( pHaving ){
62211         sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1);
62212       }
62213       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
62214                       eDest, iParm, addrEnd, addrEnd, aff);
62215     }
62216     sqlite3VdbeResolveLabel(v, addrEnd);
62217     
62218   } /* endif aggregate query */
62219
62220   /* If there is an ORDER BY clause, then we need to sort the results
62221   ** and send them to the callback one by one.
62222   */
62223   if( pOrderBy ){
62224     generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
62225   }
62226
62227 #ifndef SQLITE_OMIT_SUBQUERY
62228   /* If this was a subquery, we have now converted the subquery into a
62229   ** temporary table.  So set the SrcList_item.isPopulated flag to prevent
62230   ** this subquery from being evaluated again and to force the use of
62231   ** the temporary table.
62232   */
62233   if( pParent ){
62234     assert( pParent->pSrc->nSrc>parentTab );
62235     assert( pParent->pSrc->a[parentTab].pSelect==p );
62236     pParent->pSrc->a[parentTab].isPopulated = 1;
62237   }
62238 #endif
62239
62240   /* Jump here to skip this query
62241   */
62242   sqlite3VdbeResolveLabel(v, iEnd);
62243
62244   /* The SELECT was successfully coded.   Set the return code to 0
62245   ** to indicate no errors.
62246   */
62247   rc = 0;
62248
62249   /* Control jumps to here if an error is encountered above, or upon
62250   ** successful coding of the SELECT.
62251   */
62252 select_end:
62253
62254   /* Identify column names if we will be using them in a callback.  This
62255   ** step is skipped if the output is going to some other destination.
62256   */
62257   if( rc==SQLITE_OK && eDest==SRT_Callback ){
62258     generateColumnNames(pParse, pTabList, pEList);
62259   }
62260
62261   sqlite3_free(sAggInfo.aCol);
62262   sqlite3_free(sAggInfo.aFunc);
62263   return rc;
62264 }
62265
62266 #if defined(SQLITE_DEBUG)
62267 /*
62268 *******************************************************************************
62269 ** The following code is used for testing and debugging only.  The code
62270 ** that follows does not appear in normal builds.
62271 **
62272 ** These routines are used to print out the content of all or part of a 
62273 ** parse structures such as Select or Expr.  Such printouts are useful
62274 ** for helping to understand what is happening inside the code generator
62275 ** during the execution of complex SELECT statements.
62276 **
62277 ** These routine are not called anywhere from within the normal
62278 ** code base.  Then are intended to be called from within the debugger
62279 ** or from temporary "printf" statements inserted for debugging.
62280 */
62281 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
62282   if( p->token.z && p->token.n>0 ){
62283     sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
62284   }else{
62285     sqlite3DebugPrintf("(%d", p->op);
62286   }
62287   if( p->pLeft ){
62288     sqlite3DebugPrintf(" ");
62289     sqlite3PrintExpr(p->pLeft);
62290   }
62291   if( p->pRight ){
62292     sqlite3DebugPrintf(" ");
62293     sqlite3PrintExpr(p->pRight);
62294   }
62295   sqlite3DebugPrintf(")");
62296 }
62297 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
62298   int i;
62299   for(i=0; i<pList->nExpr; i++){
62300     sqlite3PrintExpr(pList->a[i].pExpr);
62301     if( i<pList->nExpr-1 ){
62302       sqlite3DebugPrintf(", ");
62303     }
62304   }
62305 }
62306 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
62307   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
62308   sqlite3PrintExprList(p->pEList);
62309   sqlite3DebugPrintf("\n");
62310   if( p->pSrc ){
62311     char *zPrefix;
62312     int i;
62313     zPrefix = "FROM";
62314     for(i=0; i<p->pSrc->nSrc; i++){
62315       struct SrcList_item *pItem = &p->pSrc->a[i];
62316       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
62317       zPrefix = "";
62318       if( pItem->pSelect ){
62319         sqlite3DebugPrintf("(\n");
62320         sqlite3PrintSelect(pItem->pSelect, indent+10);
62321         sqlite3DebugPrintf("%*s)", indent+8, "");
62322       }else if( pItem->zName ){
62323         sqlite3DebugPrintf("%s", pItem->zName);
62324       }
62325       if( pItem->pTab ){
62326         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
62327       }
62328       if( pItem->zAlias ){
62329         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
62330       }
62331       if( i<p->pSrc->nSrc-1 ){
62332         sqlite3DebugPrintf(",");
62333       }
62334       sqlite3DebugPrintf("\n");
62335     }
62336   }
62337   if( p->pWhere ){
62338     sqlite3DebugPrintf("%*s WHERE ", indent, "");
62339     sqlite3PrintExpr(p->pWhere);
62340     sqlite3DebugPrintf("\n");
62341   }
62342   if( p->pGroupBy ){
62343     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
62344     sqlite3PrintExprList(p->pGroupBy);
62345     sqlite3DebugPrintf("\n");
62346   }
62347   if( p->pHaving ){
62348     sqlite3DebugPrintf("%*s HAVING ", indent, "");
62349     sqlite3PrintExpr(p->pHaving);
62350     sqlite3DebugPrintf("\n");
62351   }
62352   if( p->pOrderBy ){
62353     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
62354     sqlite3PrintExprList(p->pOrderBy);
62355     sqlite3DebugPrintf("\n");
62356   }
62357 }
62358 /* End of the structure debug printing code
62359 *****************************************************************************/
62360 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
62361
62362 /************** End of select.c **********************************************/
62363 /************** Begin file table.c *******************************************/
62364 /*
62365 ** 2001 September 15
62366 **
62367 ** The author disclaims copyright to this source code.  In place of
62368 ** a legal notice, here is a blessing:
62369 **
62370 **    May you do good and not evil.
62371 **    May you find forgiveness for yourself and forgive others.
62372 **    May you share freely, never taking more than you give.
62373 **
62374 *************************************************************************
62375 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
62376 ** interface routines.  These are just wrappers around the main
62377 ** interface routine of sqlite3_exec().
62378 **
62379 ** These routines are in a separate files so that they will not be linked
62380 ** if they are not used.
62381 */
62382
62383 #ifndef SQLITE_OMIT_GET_TABLE
62384
62385 /*
62386 ** This structure is used to pass data from sqlite3_get_table() through
62387 ** to the callback function is uses to build the result.
62388 */
62389 typedef struct TabResult {
62390   char **azResult;
62391   char *zErrMsg;
62392   int nResult;
62393   int nAlloc;
62394   int nRow;
62395   int nColumn;
62396   int nData;
62397   int rc;
62398 } TabResult;
62399
62400 /*
62401 ** This routine is called once for each row in the result table.  Its job
62402 ** is to fill in the TabResult structure appropriately, allocating new
62403 ** memory as necessary.
62404 */
62405 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
62406   TabResult *p = (TabResult*)pArg;
62407   int need;
62408   int i;
62409   char *z;
62410
62411   /* Make sure there is enough space in p->azResult to hold everything
62412   ** we need to remember from this invocation of the callback.
62413   */
62414   if( p->nRow==0 && argv!=0 ){
62415     need = nCol*2;
62416   }else{
62417     need = nCol;
62418   }
62419   if( p->nData + need >= p->nAlloc ){
62420     char **azNew;
62421     p->nAlloc = p->nAlloc*2 + need + 1;
62422     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
62423     if( azNew==0 ) goto malloc_failed;
62424     p->azResult = azNew;
62425   }
62426
62427   /* If this is the first row, then generate an extra row containing
62428   ** the names of all columns.
62429   */
62430   if( p->nRow==0 ){
62431     p->nColumn = nCol;
62432     for(i=0; i<nCol; i++){
62433       if( colv[i]==0 ){
62434         z = sqlite3_mprintf("");
62435       }else{
62436         z = sqlite3_mprintf("%s", colv[i]);
62437       }
62438       p->azResult[p->nData++] = z;
62439     }
62440   }else if( p->nColumn!=nCol ){
62441     sqlite3SetString(&p->zErrMsg,
62442        "sqlite3_get_table() called with two or more incompatible queries",
62443        (char*)0);
62444     p->rc = SQLITE_ERROR;
62445     return 1;
62446   }
62447
62448   /* Copy over the row data
62449   */
62450   if( argv!=0 ){
62451     for(i=0; i<nCol; i++){
62452       if( argv[i]==0 ){
62453         z = 0;
62454       }else{
62455         int n = strlen(argv[i])+1;
62456         z = sqlite3_malloc( n );
62457         if( z==0 ) goto malloc_failed;
62458         memcpy(z, argv[i], n);
62459       }
62460       p->azResult[p->nData++] = z;
62461     }
62462     p->nRow++;
62463   }
62464   return 0;
62465
62466 malloc_failed:
62467   p->rc = SQLITE_NOMEM;
62468   return 1;
62469 }
62470
62471 /*
62472 ** Query the database.  But instead of invoking a callback for each row,
62473 ** malloc() for space to hold the result and return the entire results
62474 ** at the conclusion of the call.
62475 **
62476 ** The result that is written to ***pazResult is held in memory obtained
62477 ** from malloc().  But the caller cannot free this memory directly.  
62478 ** Instead, the entire table should be passed to sqlite3_free_table() when
62479 ** the calling procedure is finished using it.
62480 */
62481 SQLITE_API int sqlite3_get_table(
62482   sqlite3 *db,                /* The database on which the SQL executes */
62483   const char *zSql,           /* The SQL to be executed */
62484   char ***pazResult,          /* Write the result table here */
62485   int *pnRow,                 /* Write the number of rows in the result here */
62486   int *pnColumn,              /* Write the number of columns of result here */
62487   char **pzErrMsg             /* Write error messages here */
62488 ){
62489   int rc;
62490   TabResult res;
62491   if( pazResult==0 ){ return SQLITE_ERROR; }
62492   *pazResult = 0;
62493   if( pnColumn ) *pnColumn = 0;
62494   if( pnRow ) *pnRow = 0;
62495   res.zErrMsg = 0;
62496   res.nResult = 0;
62497   res.nRow = 0;
62498   res.nColumn = 0;
62499   res.nData = 1;
62500   res.nAlloc = 20;
62501   res.rc = SQLITE_OK;
62502   res.azResult = sqlite3_malloc( sizeof(char*)*res.nAlloc );
62503   if( res.azResult==0 ) return SQLITE_NOMEM;
62504   res.azResult[0] = 0;
62505   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
62506 #ifndef NDEBUG
62507   sqlite3_mutex_enter(db->mutex);
62508   assert((rc&db->errMask)==rc && (res.rc&db->errMask)==res.rc);
62509   sqlite3_mutex_leave(db->mutex);
62510 #endif
62511   if( res.azResult ){
62512     assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
62513     res.azResult[0] = (char*)res.nData;
62514   }
62515   if( (rc&0xff)==SQLITE_ABORT ){
62516     sqlite3_free_table(&res.azResult[1]);
62517     if( res.zErrMsg ){
62518       if( pzErrMsg ){
62519         sqlite3_free(*pzErrMsg);
62520         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
62521       }
62522       sqlite3_free(res.zErrMsg);
62523     }
62524     sqlite3_mutex_enter(db->mutex);
62525     db->errCode = res.rc;
62526     sqlite3_mutex_leave(db->mutex);
62527     return res.rc;
62528   }
62529   sqlite3_free(res.zErrMsg);
62530   if( rc!=SQLITE_OK ){
62531     sqlite3_free_table(&res.azResult[1]);
62532     return rc;
62533   }
62534   if( res.nAlloc>res.nData ){
62535     char **azNew;
62536     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*(res.nData+1) );
62537     if( azNew==0 ){
62538       sqlite3_free_table(&res.azResult[1]);
62539       return SQLITE_NOMEM;
62540     }
62541     res.nAlloc = res.nData+1;
62542     res.azResult = azNew;
62543   }
62544   *pazResult = &res.azResult[1];
62545   if( pnColumn ) *pnColumn = res.nColumn;
62546   if( pnRow ) *pnRow = res.nRow;
62547   return rc;
62548 }
62549
62550 /*
62551 ** This routine frees the space the sqlite3_get_table() malloced.
62552 */
62553 SQLITE_API void sqlite3_free_table(
62554   char **azResult            /* Result returned from from sqlite3_get_table() */
62555 ){
62556   if( azResult ){
62557     int i, n;
62558     azResult--;
62559     if( azResult==0 ) return;
62560     n = (int)azResult[0];
62561     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
62562     sqlite3_free(azResult);
62563   }
62564 }
62565
62566 #endif /* SQLITE_OMIT_GET_TABLE */
62567
62568 /************** End of table.c ***********************************************/
62569 /************** Begin file trigger.c *****************************************/
62570 /*
62571 **
62572 ** The author disclaims copyright to this source code.  In place of
62573 ** a legal notice, here is a blessing:
62574 **
62575 **    May you do good and not evil.
62576 **    May you find forgiveness for yourself and forgive others.
62577 **    May you share freely, never taking more than you give.
62578 **
62579 *************************************************************************
62580 *
62581 */
62582
62583 #ifndef SQLITE_OMIT_TRIGGER
62584 /*
62585 ** Delete a linked list of TriggerStep structures.
62586 */
62587 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(TriggerStep *pTriggerStep){
62588   while( pTriggerStep ){
62589     TriggerStep * pTmp = pTriggerStep;
62590     pTriggerStep = pTriggerStep->pNext;
62591
62592     if( pTmp->target.dyn ) sqlite3_free((char*)pTmp->target.z);
62593     sqlite3ExprDelete(pTmp->pWhere);
62594     sqlite3ExprListDelete(pTmp->pExprList);
62595     sqlite3SelectDelete(pTmp->pSelect);
62596     sqlite3IdListDelete(pTmp->pIdList);
62597
62598     sqlite3_free(pTmp);
62599   }
62600 }
62601
62602 /*
62603 ** This is called by the parser when it sees a CREATE TRIGGER statement
62604 ** up to the point of the BEGIN before the trigger actions.  A Trigger
62605 ** structure is generated based on the information available and stored
62606 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
62607 ** sqlite3FinishTrigger() function is called to complete the trigger
62608 ** construction process.
62609 */
62610 SQLITE_PRIVATE void sqlite3BeginTrigger(
62611   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
62612   Token *pName1,      /* The name of the trigger */
62613   Token *pName2,      /* The name of the trigger */
62614   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
62615   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
62616   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
62617   SrcList *pTableName,/* The name of the table/view the trigger applies to */
62618   Expr *pWhen,        /* WHEN clause */
62619   int isTemp,         /* True if the TEMPORARY keyword is present */
62620   int noErr           /* Suppress errors if the trigger already exists */
62621 ){
62622   Trigger *pTrigger = 0;
62623   Table *pTab;
62624   char *zName = 0;        /* Name of the trigger */
62625   sqlite3 *db = pParse->db;
62626   int iDb;                /* The database to store the trigger in */
62627   Token *pName;           /* The unqualified db name */
62628   DbFixer sFix;
62629   int iTabDb;
62630
62631   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
62632   assert( pName2!=0 );
62633   if( isTemp ){
62634     /* If TEMP was specified, then the trigger name may not be qualified. */
62635     if( pName2->n>0 ){
62636       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
62637       goto trigger_cleanup;
62638     }
62639     iDb = 1;
62640     pName = pName1;
62641   }else{
62642     /* Figure out the db that the the trigger will be created in */
62643     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
62644     if( iDb<0 ){
62645       goto trigger_cleanup;
62646     }
62647   }
62648
62649   /* If the trigger name was unqualified, and the table is a temp table,
62650   ** then set iDb to 1 to create the trigger in the temporary database.
62651   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
62652   ** exist, the error is caught by the block below.
62653   */
62654   if( !pTableName || db->mallocFailed ){
62655     goto trigger_cleanup;
62656   }
62657   pTab = sqlite3SrcListLookup(pParse, pTableName);
62658   if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
62659     iDb = 1;
62660   }
62661
62662   /* Ensure the table name matches database name and that the table exists */
62663   if( db->mallocFailed ) goto trigger_cleanup;
62664   assert( pTableName->nSrc==1 );
62665   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
62666       sqlite3FixSrcList(&sFix, pTableName) ){
62667     goto trigger_cleanup;
62668   }
62669   pTab = sqlite3SrcListLookup(pParse, pTableName);
62670   if( !pTab ){
62671     /* The table does not exist. */
62672     goto trigger_cleanup;
62673   }
62674   if( IsVirtual(pTab) ){
62675     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
62676     goto trigger_cleanup;
62677   }
62678
62679   /* Check that the trigger name is not reserved and that no trigger of the
62680   ** specified name exists */
62681   zName = sqlite3NameFromToken(db, pName);
62682   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
62683     goto trigger_cleanup;
62684   }
62685   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash), zName,strlen(zName)) ){
62686     if( !noErr ){
62687       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
62688     }
62689     goto trigger_cleanup;
62690   }
62691
62692   /* Do not create a trigger on a system table */
62693   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
62694     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
62695     pParse->nErr++;
62696     goto trigger_cleanup;
62697   }
62698
62699   /* INSTEAD of triggers are only for views and views only support INSTEAD
62700   ** of triggers.
62701   */
62702   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
62703     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
62704         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
62705     goto trigger_cleanup;
62706   }
62707   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
62708     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
62709         " trigger on table: %S", pTableName, 0);
62710     goto trigger_cleanup;
62711   }
62712   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
62713
62714 #ifndef SQLITE_OMIT_AUTHORIZATION
62715   {
62716     int code = SQLITE_CREATE_TRIGGER;
62717     const char *zDb = db->aDb[iTabDb].zName;
62718     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
62719     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
62720     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
62721       goto trigger_cleanup;
62722     }
62723     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
62724       goto trigger_cleanup;
62725     }
62726   }
62727 #endif
62728
62729   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
62730   ** cannot appear on views.  So we might as well translate every
62731   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
62732   ** elsewhere.
62733   */
62734   if (tr_tm == TK_INSTEAD){
62735     tr_tm = TK_BEFORE;
62736   }
62737
62738   /* Build the Trigger object */
62739   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
62740   if( pTrigger==0 ) goto trigger_cleanup;
62741   pTrigger->name = zName;
62742   zName = 0;
62743   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
62744   pTrigger->pSchema = db->aDb[iDb].pSchema;
62745   pTrigger->pTabSchema = pTab->pSchema;
62746   pTrigger->op = op;
62747   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
62748   pTrigger->pWhen = sqlite3ExprDup(db, pWhen);
62749   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
62750   sqlite3TokenCopy(db, &pTrigger->nameToken,pName);
62751   assert( pParse->pNewTrigger==0 );
62752   pParse->pNewTrigger = pTrigger;
62753
62754 trigger_cleanup:
62755   sqlite3_free(zName);
62756   sqlite3SrcListDelete(pTableName);
62757   sqlite3IdListDelete(pColumns);
62758   sqlite3ExprDelete(pWhen);
62759   if( !pParse->pNewTrigger ){
62760     sqlite3DeleteTrigger(pTrigger);
62761   }else{
62762     assert( pParse->pNewTrigger==pTrigger );
62763   }
62764 }
62765
62766 /*
62767 ** This routine is called after all of the trigger actions have been parsed
62768 ** in order to complete the process of building the trigger.
62769 */
62770 SQLITE_PRIVATE void sqlite3FinishTrigger(
62771   Parse *pParse,          /* Parser context */
62772   TriggerStep *pStepList, /* The triggered program */
62773   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
62774 ){
62775   Trigger *pTrig = 0;     /* The trigger whose construction is finishing up */
62776   sqlite3 *db = pParse->db;  /* The database */
62777   DbFixer sFix;
62778   int iDb;                   /* Database containing the trigger */
62779
62780   pTrig = pParse->pNewTrigger;
62781   pParse->pNewTrigger = 0;
62782   if( pParse->nErr || !pTrig ) goto triggerfinish_cleanup;
62783   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
62784   pTrig->step_list = pStepList;
62785   while( pStepList ){
62786     pStepList->pTrig = pTrig;
62787     pStepList = pStepList->pNext;
62788   }
62789   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &pTrig->nameToken) 
62790           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
62791     goto triggerfinish_cleanup;
62792   }
62793
62794   /* if we are not initializing, and this trigger is not on a TEMP table, 
62795   ** build the sqlite_master entry
62796   */
62797   if( !db->init.busy ){
62798     static const VdbeOpList insertTrig[] = {
62799       { OP_NewRowid,   0, 0,  0          },
62800       { OP_String8,    0, 0,  "trigger"  },
62801       { OP_String8,    0, 0,  0          },  /* 2: trigger name */
62802       { OP_String8,    0, 0,  0          },  /* 3: table name */
62803       { OP_Integer,    0, 0,  0          },
62804       { OP_String8,    0, 0,  "CREATE TRIGGER "},
62805       { OP_String8,    0, 0,  0          },  /* 6: SQL */
62806       { OP_Concat,     0, 0,  0          }, 
62807       { OP_MakeRecord, 5, 0,  "aaada"    },
62808       { OP_Insert,     0, 0,  0          },
62809     };
62810     int addr;
62811     Vdbe *v;
62812
62813     /* Make an entry in the sqlite_master table */
62814     v = sqlite3GetVdbe(pParse);
62815     if( v==0 ) goto triggerfinish_cleanup;
62816     sqlite3BeginWriteOperation(pParse, 0, iDb);
62817     sqlite3OpenMasterTable(pParse, iDb);
62818     addr = sqlite3VdbeAddOpList(v, ArraySize(insertTrig), insertTrig);
62819     sqlite3VdbeChangeP3(v, addr+2, pTrig->name, 0); 
62820     sqlite3VdbeChangeP3(v, addr+3, pTrig->table, 0); 
62821     sqlite3VdbeChangeP3(v, addr+6, (char*)pAll->z, pAll->n);
62822     sqlite3ChangeCookie(db, v, iDb);
62823     sqlite3VdbeAddOp(v, OP_Close, 0, 0);
62824     sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, sqlite3MPrintf(
62825         db, "type='trigger' AND name='%q'", pTrig->name), P3_DYNAMIC
62826     );
62827   }
62828
62829   if( db->init.busy ){
62830     int n;
62831     Table *pTab;
62832     Trigger *pDel;
62833     pDel = sqlite3HashInsert(&db->aDb[iDb].pSchema->trigHash, 
62834                      pTrig->name, strlen(pTrig->name), pTrig);
62835     if( pDel ){
62836       assert( pDel==pTrig );
62837       db->mallocFailed = 1;
62838       goto triggerfinish_cleanup;
62839     }
62840     n = strlen(pTrig->table) + 1;
62841     pTab = sqlite3HashFind(&pTrig->pTabSchema->tblHash, pTrig->table, n);
62842     assert( pTab!=0 );
62843     pTrig->pNext = pTab->pTrigger;
62844     pTab->pTrigger = pTrig;
62845     pTrig = 0;
62846   }
62847
62848 triggerfinish_cleanup:
62849   sqlite3DeleteTrigger(pTrig);
62850   assert( !pParse->pNewTrigger );
62851   sqlite3DeleteTriggerStep(pStepList);
62852 }
62853
62854 /*
62855 ** Make a copy of all components of the given trigger step.  This has
62856 ** the effect of copying all Expr.token.z values into memory obtained
62857 ** from sqlite3_malloc().  As initially created, the Expr.token.z values
62858 ** all point to the input string that was fed to the parser.  But that
62859 ** string is ephemeral - it will go away as soon as the sqlite3_exec()
62860 ** call that started the parser exits.  This routine makes a persistent
62861 ** copy of all the Expr.token.z strings so that the TriggerStep structure
62862 ** will be valid even after the sqlite3_exec() call returns.
62863 */
62864 static void sqlitePersistTriggerStep(sqlite3 *db, TriggerStep *p){
62865   if( p->target.z ){
62866     p->target.z = (u8*)sqlite3DbStrNDup(db, (char*)p->target.z, p->target.n);
62867     p->target.dyn = 1;
62868   }
62869   if( p->pSelect ){
62870     Select *pNew = sqlite3SelectDup(db, p->pSelect);
62871     sqlite3SelectDelete(p->pSelect);
62872     p->pSelect = pNew;
62873   }
62874   if( p->pWhere ){
62875     Expr *pNew = sqlite3ExprDup(db, p->pWhere);
62876     sqlite3ExprDelete(p->pWhere);
62877     p->pWhere = pNew;
62878   }
62879   if( p->pExprList ){
62880     ExprList *pNew = sqlite3ExprListDup(db, p->pExprList);
62881     sqlite3ExprListDelete(p->pExprList);
62882     p->pExprList = pNew;
62883   }
62884   if( p->pIdList ){
62885     IdList *pNew = sqlite3IdListDup(db, p->pIdList);
62886     sqlite3IdListDelete(p->pIdList);
62887     p->pIdList = pNew;
62888   }
62889 }
62890
62891 /*
62892 ** Turn a SELECT statement (that the pSelect parameter points to) into
62893 ** a trigger step.  Return a pointer to a TriggerStep structure.
62894 **
62895 ** The parser calls this routine when it finds a SELECT statement in
62896 ** body of a TRIGGER.  
62897 */
62898 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
62899   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
62900   if( pTriggerStep==0 ) {
62901     sqlite3SelectDelete(pSelect);
62902     return 0;
62903   }
62904
62905   pTriggerStep->op = TK_SELECT;
62906   pTriggerStep->pSelect = pSelect;
62907   pTriggerStep->orconf = OE_Default;
62908   sqlitePersistTriggerStep(db, pTriggerStep);
62909
62910   return pTriggerStep;
62911 }
62912
62913 /*
62914 ** Build a trigger step out of an INSERT statement.  Return a pointer
62915 ** to the new trigger step.
62916 **
62917 ** The parser calls this routine when it sees an INSERT inside the
62918 ** body of a trigger.
62919 */
62920 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
62921   sqlite3 *db,        /* The database connection */
62922   Token *pTableName,  /* Name of the table into which we insert */
62923   IdList *pColumn,    /* List of columns in pTableName to insert into */
62924   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
62925   Select *pSelect,    /* A SELECT statement that supplies values */
62926   int orconf          /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
62927 ){
62928   TriggerStep *pTriggerStep;
62929
62930   assert(pEList == 0 || pSelect == 0);
62931   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
62932
62933   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
62934   if( pTriggerStep ){
62935     pTriggerStep->op = TK_INSERT;
62936     pTriggerStep->pSelect = pSelect;
62937     pTriggerStep->target  = *pTableName;
62938     pTriggerStep->pIdList = pColumn;
62939     pTriggerStep->pExprList = pEList;
62940     pTriggerStep->orconf = orconf;
62941     sqlitePersistTriggerStep(db, pTriggerStep);
62942   }else{
62943     sqlite3IdListDelete(pColumn);
62944     sqlite3ExprListDelete(pEList);
62945     sqlite3SelectDelete(pSelect);
62946   }
62947
62948   return pTriggerStep;
62949 }
62950
62951 /*
62952 ** Construct a trigger step that implements an UPDATE statement and return
62953 ** a pointer to that trigger step.  The parser calls this routine when it
62954 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
62955 */
62956 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
62957   sqlite3 *db,         /* The database connection */
62958   Token *pTableName,   /* Name of the table to be updated */
62959   ExprList *pEList,    /* The SET clause: list of column and new values */
62960   Expr *pWhere,        /* The WHERE clause */
62961   int orconf           /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
62962 ){
62963   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
62964   if( pTriggerStep==0 ){
62965      sqlite3ExprListDelete(pEList);
62966      sqlite3ExprDelete(pWhere);
62967      return 0;
62968   }
62969
62970   pTriggerStep->op = TK_UPDATE;
62971   pTriggerStep->target  = *pTableName;
62972   pTriggerStep->pExprList = pEList;
62973   pTriggerStep->pWhere = pWhere;
62974   pTriggerStep->orconf = orconf;
62975   sqlitePersistTriggerStep(db, pTriggerStep);
62976
62977   return pTriggerStep;
62978 }
62979
62980 /*
62981 ** Construct a trigger step that implements a DELETE statement and return
62982 ** a pointer to that trigger step.  The parser calls this routine when it
62983 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
62984 */
62985 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
62986   sqlite3 *db,            /* Database connection */
62987   Token *pTableName,      /* The table from which rows are deleted */
62988   Expr *pWhere            /* The WHERE clause */
62989 ){
62990   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
62991   if( pTriggerStep==0 ){
62992     sqlite3ExprDelete(pWhere);
62993     return 0;
62994   }
62995
62996   pTriggerStep->op = TK_DELETE;
62997   pTriggerStep->target  = *pTableName;
62998   pTriggerStep->pWhere = pWhere;
62999   pTriggerStep->orconf = OE_Default;
63000   sqlitePersistTriggerStep(db, pTriggerStep);
63001
63002   return pTriggerStep;
63003 }
63004
63005 /* 
63006 ** Recursively delete a Trigger structure
63007 */
63008 SQLITE_PRIVATE void sqlite3DeleteTrigger(Trigger *pTrigger){
63009   if( pTrigger==0 ) return;
63010   sqlite3DeleteTriggerStep(pTrigger->step_list);
63011   sqlite3_free(pTrigger->name);
63012   sqlite3_free(pTrigger->table);
63013   sqlite3ExprDelete(pTrigger->pWhen);
63014   sqlite3IdListDelete(pTrigger->pColumns);
63015   if( pTrigger->nameToken.dyn ) sqlite3_free((char*)pTrigger->nameToken.z);
63016   sqlite3_free(pTrigger);
63017 }
63018
63019 /*
63020 ** This function is called to drop a trigger from the database schema. 
63021 **
63022 ** This may be called directly from the parser and therefore identifies
63023 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
63024 ** same job as this routine except it takes a pointer to the trigger
63025 ** instead of the trigger name.
63026 **/
63027 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
63028   Trigger *pTrigger = 0;
63029   int i;
63030   const char *zDb;
63031   const char *zName;
63032   int nName;
63033   sqlite3 *db = pParse->db;
63034
63035   if( db->mallocFailed ) goto drop_trigger_cleanup;
63036   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
63037     goto drop_trigger_cleanup;
63038   }
63039
63040   assert( pName->nSrc==1 );
63041   zDb = pName->a[0].zDatabase;
63042   zName = pName->a[0].zName;
63043   nName = strlen(zName);
63044   for(i=OMIT_TEMPDB; i<db->nDb; i++){
63045     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
63046     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
63047     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
63048     if( pTrigger ) break;
63049   }
63050   if( !pTrigger ){
63051     if( !noErr ){
63052       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
63053     }
63054     goto drop_trigger_cleanup;
63055   }
63056   sqlite3DropTriggerPtr(pParse, pTrigger);
63057
63058 drop_trigger_cleanup:
63059   sqlite3SrcListDelete(pName);
63060 }
63061
63062 /*
63063 ** Return a pointer to the Table structure for the table that a trigger
63064 ** is set on.
63065 */
63066 static Table *tableOfTrigger(Trigger *pTrigger){
63067   int n = strlen(pTrigger->table) + 1;
63068   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
63069 }
63070
63071
63072 /*
63073 ** Drop a trigger given a pointer to that trigger. 
63074 */
63075 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
63076   Table   *pTable;
63077   Vdbe *v;
63078   sqlite3 *db = pParse->db;
63079   int iDb;
63080
63081   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
63082   assert( iDb>=0 && iDb<db->nDb );
63083   pTable = tableOfTrigger(pTrigger);
63084   assert( pTable );
63085   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
63086 #ifndef SQLITE_OMIT_AUTHORIZATION
63087   {
63088     int code = SQLITE_DROP_TRIGGER;
63089     const char *zDb = db->aDb[iDb].zName;
63090     const char *zTab = SCHEMA_TABLE(iDb);
63091     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
63092     if( sqlite3AuthCheck(pParse, code, pTrigger->name, pTable->zName, zDb) ||
63093       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
63094       return;
63095     }
63096   }
63097 #endif
63098
63099   /* Generate code to destroy the database record of the trigger.
63100   */
63101   assert( pTable!=0 );
63102   if( (v = sqlite3GetVdbe(pParse))!=0 ){
63103     int base;
63104     static const VdbeOpList dropTrigger[] = {
63105       { OP_Rewind,     0, ADDR(9),  0},
63106       { OP_String8,    0, 0,        0}, /* 1 */
63107       { OP_Column,     0, 1,        0},
63108       { OP_Ne,         0, ADDR(8),  0},
63109       { OP_String8,    0, 0,        "trigger"},
63110       { OP_Column,     0, 0,        0},
63111       { OP_Ne,         0, ADDR(8),  0},
63112       { OP_Delete,     0, 0,        0},
63113       { OP_Next,       0, ADDR(1),  0}, /* 8 */
63114     };
63115
63116     sqlite3BeginWriteOperation(pParse, 0, iDb);
63117     sqlite3OpenMasterTable(pParse, iDb);
63118     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
63119     sqlite3VdbeChangeP3(v, base+1, pTrigger->name, 0);
63120     sqlite3ChangeCookie(db, v, iDb);
63121     sqlite3VdbeAddOp(v, OP_Close, 0, 0);
63122     sqlite3VdbeOp3(v, OP_DropTrigger, iDb, 0, pTrigger->name, 0);
63123   }
63124 }
63125
63126 /*
63127 ** Remove a trigger from the hash tables of the sqlite* pointer.
63128 */
63129 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
63130   Trigger *pTrigger;
63131   int nName = strlen(zName);
63132   pTrigger = sqlite3HashInsert(&(db->aDb[iDb].pSchema->trigHash),
63133                                zName, nName, 0);
63134   if( pTrigger ){
63135     Table *pTable = tableOfTrigger(pTrigger);
63136     assert( pTable!=0 );
63137     if( pTable->pTrigger == pTrigger ){
63138       pTable->pTrigger = pTrigger->pNext;
63139     }else{
63140       Trigger *cc = pTable->pTrigger;
63141       while( cc ){ 
63142         if( cc->pNext == pTrigger ){
63143           cc->pNext = cc->pNext->pNext;
63144           break;
63145         }
63146         cc = cc->pNext;
63147       }
63148       assert(cc);
63149     }
63150     sqlite3DeleteTrigger(pTrigger);
63151     db->flags |= SQLITE_InternChanges;
63152   }
63153 }
63154
63155 /*
63156 ** pEList is the SET clause of an UPDATE statement.  Each entry
63157 ** in pEList is of the format <id>=<expr>.  If any of the entries
63158 ** in pEList have an <id> which matches an identifier in pIdList,
63159 ** then return TRUE.  If pIdList==NULL, then it is considered a
63160 ** wildcard that matches anything.  Likewise if pEList==NULL then
63161 ** it matches anything so always return true.  Return false only
63162 ** if there is no match.
63163 */
63164 static int checkColumnOverLap(IdList *pIdList, ExprList *pEList){
63165   int e;
63166   if( !pIdList || !pEList ) return 1;
63167   for(e=0; e<pEList->nExpr; e++){
63168     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
63169   }
63170   return 0; 
63171 }
63172
63173 /*
63174 ** Return a bit vector to indicate what kind of triggers exist for operation
63175 ** "op" on table pTab.  If pChanges is not NULL then it is a list of columns
63176 ** that are being updated.  Triggers only match if the ON clause of the
63177 ** trigger definition overlaps the set of columns being updated.
63178 **
63179 ** The returned bit vector is some combination of TRIGGER_BEFORE and
63180 ** TRIGGER_AFTER.
63181 */
63182 SQLITE_PRIVATE int sqlite3TriggersExist(
63183   Parse *pParse,          /* Used to check for recursive triggers */
63184   Table *pTab,            /* The table the contains the triggers */
63185   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
63186   ExprList *pChanges      /* Columns that change in an UPDATE statement */
63187 ){
63188   Trigger *pTrigger;
63189   int mask = 0;
63190
63191   pTrigger = IsVirtual(pTab) ? 0 : pTab->pTrigger;
63192   while( pTrigger ){
63193     if( pTrigger->op==op && checkColumnOverLap(pTrigger->pColumns, pChanges) ){
63194       mask |= pTrigger->tr_tm;
63195     }
63196     pTrigger = pTrigger->pNext;
63197   }
63198   return mask;
63199 }
63200
63201 /*
63202 ** Convert the pStep->target token into a SrcList and return a pointer
63203 ** to that SrcList.
63204 **
63205 ** This routine adds a specific database name, if needed, to the target when
63206 ** forming the SrcList.  This prevents a trigger in one database from
63207 ** referring to a target in another database.  An exception is when the
63208 ** trigger is in TEMP in which case it can refer to any other database it
63209 ** wants.
63210 */
63211 static SrcList *targetSrcList(
63212   Parse *pParse,       /* The parsing context */
63213   TriggerStep *pStep   /* The trigger containing the target token */
63214 ){
63215   Token sDb;           /* Dummy database name token */
63216   int iDb;             /* Index of the database to use */
63217   SrcList *pSrc;       /* SrcList to be returned */
63218
63219   iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
63220   if( iDb==0 || iDb>=2 ){
63221     assert( iDb<pParse->db->nDb );
63222     sDb.z = (u8*)pParse->db->aDb[iDb].zName;
63223     sDb.n = strlen((char*)sDb.z);
63224     pSrc = sqlite3SrcListAppend(pParse->db, 0, &sDb, &pStep->target);
63225   } else {
63226     pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
63227   }
63228   return pSrc;
63229 }
63230
63231 /*
63232 ** Generate VDBE code for zero or more statements inside the body of a
63233 ** trigger.  
63234 */
63235 static int codeTriggerProgram(
63236   Parse *pParse,            /* The parser context */
63237   TriggerStep *pStepList,   /* List of statements inside the trigger body */
63238   int orconfin              /* Conflict algorithm. (OE_Abort, etc) */  
63239 ){
63240   TriggerStep * pTriggerStep = pStepList;
63241   int orconf;
63242   Vdbe *v = pParse->pVdbe;
63243   sqlite3 *db = pParse->db;
63244
63245   assert( pTriggerStep!=0 );
63246   assert( v!=0 );
63247   sqlite3VdbeAddOp(v, OP_ContextPush, 0, 0);
63248   VdbeComment((v, "# begin trigger %s", pStepList->pTrig->name));
63249   while( pTriggerStep ){
63250     orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
63251     pParse->trigStack->orconf = orconf;
63252     switch( pTriggerStep->op ){
63253       case TK_SELECT: {
63254         Select *ss = sqlite3SelectDup(db, pTriggerStep->pSelect);
63255         if( ss ){
63256           sqlite3SelectResolve(pParse, ss, 0);
63257           sqlite3Select(pParse, ss, SRT_Discard, 0, 0, 0, 0, 0);
63258           sqlite3SelectDelete(ss);
63259         }
63260         break;
63261       }
63262       case TK_UPDATE: {
63263         SrcList *pSrc;
63264         pSrc = targetSrcList(pParse, pTriggerStep);
63265         sqlite3VdbeAddOp(v, OP_ResetCount, 0, 0);
63266         sqlite3Update(pParse, pSrc,
63267                 sqlite3ExprListDup(db, pTriggerStep->pExprList), 
63268                 sqlite3ExprDup(db, pTriggerStep->pWhere), orconf);
63269         sqlite3VdbeAddOp(v, OP_ResetCount, 1, 0);
63270         break;
63271       }
63272       case TK_INSERT: {
63273         SrcList *pSrc;
63274         pSrc = targetSrcList(pParse, pTriggerStep);
63275         sqlite3VdbeAddOp(v, OP_ResetCount, 0, 0);
63276         sqlite3Insert(pParse, pSrc,
63277           sqlite3ExprListDup(db, pTriggerStep->pExprList), 
63278           sqlite3SelectDup(db, pTriggerStep->pSelect), 
63279           sqlite3IdListDup(db, pTriggerStep->pIdList), orconf);
63280         sqlite3VdbeAddOp(v, OP_ResetCount, 1, 0);
63281         break;
63282       }
63283       case TK_DELETE: {
63284         SrcList *pSrc;
63285         sqlite3VdbeAddOp(v, OP_ResetCount, 0, 0);
63286         pSrc = targetSrcList(pParse, pTriggerStep);
63287         sqlite3DeleteFrom(pParse, pSrc, 
63288                           sqlite3ExprDup(db, pTriggerStep->pWhere));
63289         sqlite3VdbeAddOp(v, OP_ResetCount, 1, 0);
63290         break;
63291       }
63292       default:
63293         assert(0);
63294     } 
63295     pTriggerStep = pTriggerStep->pNext;
63296   }
63297   sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
63298   VdbeComment((v, "# end trigger %s", pStepList->pTrig->name));
63299
63300   return 0;
63301 }
63302
63303 /*
63304 ** This is called to code FOR EACH ROW triggers.
63305 **
63306 ** When the code that this function generates is executed, the following 
63307 ** must be true:
63308 **
63309 ** 1. No cursors may be open in the main database.  (But newIdx and oldIdx
63310 **    can be indices of cursors in temporary tables.  See below.)
63311 **
63312 ** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then
63313 **    a temporary vdbe cursor (index newIdx) must be open and pointing at
63314 **    a row containing values to be substituted for new.* expressions in the
63315 **    trigger program(s).
63316 **
63317 ** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
63318 **    a temporary vdbe cursor (index oldIdx) must be open and pointing at
63319 **    a row containing values to be substituted for old.* expressions in the
63320 **    trigger program(s).
63321 **
63322 */
63323 SQLITE_PRIVATE int sqlite3CodeRowTrigger(
63324   Parse *pParse,       /* Parse context */
63325   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
63326   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
63327   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
63328   Table *pTab,         /* The table to code triggers from */
63329   int newIdx,          /* The indice of the "new" row to access */
63330   int oldIdx,          /* The indice of the "old" row to access */
63331   int orconf,          /* ON CONFLICT policy */
63332   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
63333 ){
63334   Trigger *p;
63335   TriggerStack trigStackEntry;
63336
63337   assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
63338   assert(tr_tm == TRIGGER_BEFORE || tr_tm == TRIGGER_AFTER );
63339
63340   assert(newIdx != -1 || oldIdx != -1);
63341
63342   for(p=pTab->pTrigger; p; p=p->pNext){
63343     int fire_this = 0;
63344     sqlite3 *db = pParse->db;
63345
63346     /* Determine whether we should code this trigger */
63347     if( 
63348       p->op==op && 
63349       p->tr_tm==tr_tm && 
63350       (p->pSchema==p->pTabSchema || p->pSchema==db->aDb[1].pSchema) &&
63351       (op!=TK_UPDATE||!p->pColumns||checkColumnOverLap(p->pColumns,pChanges))
63352     ){
63353       TriggerStack *pS;      /* Pointer to trigger-stack entry */
63354       for(pS=pParse->trigStack; pS && p!=pS->pTrigger; pS=pS->pNext){}
63355       if( !pS ){
63356         fire_this = 1;
63357       }
63358 #if 0    /* Give no warning for recursive triggers.  Just do not do them */
63359       else{
63360         sqlite3ErrorMsg(pParse, "recursive triggers not supported (%s)",
63361             p->name);
63362         return SQLITE_ERROR;
63363       }
63364 #endif
63365     }
63366  
63367     if( fire_this ){
63368       int endTrigger;
63369       Expr * whenExpr;
63370       AuthContext sContext;
63371       NameContext sNC;
63372
63373       memset(&sNC, 0, sizeof(sNC));
63374       sNC.pParse = pParse;
63375
63376       /* Push an entry on to the trigger stack */
63377       trigStackEntry.pTrigger = p;
63378       trigStackEntry.newIdx = newIdx;
63379       trigStackEntry.oldIdx = oldIdx;
63380       trigStackEntry.pTab = pTab;
63381       trigStackEntry.pNext = pParse->trigStack;
63382       trigStackEntry.ignoreJump = ignoreJump;
63383       pParse->trigStack = &trigStackEntry;
63384       sqlite3AuthContextPush(pParse, &sContext, p->name);
63385
63386       /* code the WHEN clause */
63387       endTrigger = sqlite3VdbeMakeLabel(pParse->pVdbe);
63388       whenExpr = sqlite3ExprDup(db, p->pWhen);
63389       if( db->mallocFailed || sqlite3ExprResolveNames(&sNC, whenExpr) ){
63390         pParse->trigStack = trigStackEntry.pNext;
63391         sqlite3ExprDelete(whenExpr);
63392         return 1;
63393       }
63394       sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, 1);
63395       sqlite3ExprDelete(whenExpr);
63396
63397       codeTriggerProgram(pParse, p->step_list, orconf); 
63398
63399       /* Pop the entry off the trigger stack */
63400       pParse->trigStack = trigStackEntry.pNext;
63401       sqlite3AuthContextPop(&sContext);
63402
63403       sqlite3VdbeResolveLabel(pParse->pVdbe, endTrigger);
63404     }
63405   }
63406   return 0;
63407 }
63408 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
63409
63410 /************** End of trigger.c *********************************************/
63411 /************** Begin file update.c ******************************************/
63412 /*
63413 ** 2001 September 15
63414 **
63415 ** The author disclaims copyright to this source code.  In place of
63416 ** a legal notice, here is a blessing:
63417 **
63418 **    May you do good and not evil.
63419 **    May you find forgiveness for yourself and forgive others.
63420 **    May you share freely, never taking more than you give.
63421 **
63422 *************************************************************************
63423 ** This file contains C code routines that are called by the parser
63424 ** to handle UPDATE statements.
63425 **
63426 ** $Id: update.c,v 1.144 2007/12/12 16:06:23 danielk1977 Exp $
63427 */
63428
63429 #ifndef SQLITE_OMIT_VIRTUALTABLE
63430 /* Forward declaration */
63431 static void updateVirtualTable(
63432   Parse *pParse,       /* The parsing context */
63433   SrcList *pSrc,       /* The virtual table to be modified */
63434   Table *pTab,         /* The virtual table */
63435   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
63436   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
63437   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
63438   Expr *pWhere         /* WHERE clause of the UPDATE statement */
63439 );
63440 #endif /* SQLITE_OMIT_VIRTUALTABLE */
63441
63442 /*
63443 ** The most recently coded instruction was an OP_Column to retrieve the
63444 ** i-th column of table pTab. This routine sets the P3 parameter of the 
63445 ** OP_Column to the default value, if any.
63446 **
63447 ** The default value of a column is specified by a DEFAULT clause in the 
63448 ** column definition. This was either supplied by the user when the table
63449 ** was created, or added later to the table definition by an ALTER TABLE
63450 ** command. If the latter, then the row-records in the table btree on disk
63451 ** may not contain a value for the column and the default value, taken
63452 ** from the P3 parameter of the OP_Column instruction, is returned instead.
63453 ** If the former, then all row-records are guaranteed to include a value
63454 ** for the column and the P3 value is not required.
63455 **
63456 ** Column definitions created by an ALTER TABLE command may only have 
63457 ** literal default values specified: a number, null or a string. (If a more
63458 ** complicated default expression value was provided, it is evaluated 
63459 ** when the ALTER TABLE is executed and one of the literal values written
63460 ** into the sqlite_master table.)
63461 **
63462 ** Therefore, the P3 parameter is only required if the default value for
63463 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
63464 ** function is capable of transforming these types of expressions into
63465 ** sqlite3_value objects.
63466 */
63467 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i){
63468   if( pTab && !pTab->pSelect ){
63469     sqlite3_value *pValue;
63470     u8 enc = ENC(sqlite3VdbeDb(v));
63471     Column *pCol = &pTab->aCol[i];
63472     assert( i<pTab->nCol );
63473     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, pCol->affinity, &pValue);
63474     if( pValue ){
63475       sqlite3VdbeChangeP3(v, -1, (const char *)pValue, P3_MEM);
63476     }else{
63477       VdbeComment((v, "# %s.%s", pTab->zName, pCol->zName));
63478     }
63479   }
63480 }
63481
63482 /*
63483 ** Process an UPDATE statement.
63484 **
63485 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
63486 **          \_______/ \________/     \______/       \________________/
63487 *            onError   pTabList      pChanges             pWhere
63488 */
63489 SQLITE_PRIVATE void sqlite3Update(
63490   Parse *pParse,         /* The parser context */
63491   SrcList *pTabList,     /* The table in which we should change things */
63492   ExprList *pChanges,    /* Things to be changed */
63493   Expr *pWhere,          /* The WHERE clause.  May be null */
63494   int onError            /* How to handle constraint errors */
63495 ){
63496   int i, j;              /* Loop counters */
63497   Table *pTab;           /* The table to be updated */
63498   int addr = 0;          /* VDBE instruction address of the start of the loop */
63499   WhereInfo *pWInfo;     /* Information about the WHERE clause */
63500   Vdbe *v;               /* The virtual database engine */
63501   Index *pIdx;           /* For looping over indices */
63502   int nIdx;              /* Number of indices that need updating */
63503   int nIdxTotal;         /* Total number of indices */
63504   int iCur;              /* VDBE Cursor number of pTab */
63505   sqlite3 *db;           /* The database structure */
63506   Index **apIdx = 0;     /* An array of indices that need updating too */
63507   char *aIdxUsed = 0;    /* aIdxUsed[i]==1 if the i-th index is used */
63508   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
63509                          ** an expression for the i-th column of the table.
63510                          ** aXRef[i]==-1 if the i-th column is not changed. */
63511   int chngRowid;         /* True if the record number is being changed */
63512   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
63513   int openAll = 0;       /* True if all indices need to be opened */
63514   AuthContext sContext;  /* The authorization context */
63515   NameContext sNC;       /* The name-context to resolve expressions in */
63516   int iDb;               /* Database containing the table being updated */
63517   int memCnt = 0;        /* Memory cell used for counting rows changed */
63518   int mem1;      /* Memory address storing the rowid for next row to update */
63519
63520 #ifndef SQLITE_OMIT_TRIGGER
63521   int isView;                  /* Trying to update a view */
63522   int triggers_exist = 0;      /* True if any row triggers exist */
63523 #endif
63524
63525   int newIdx      = -1;  /* index of trigger "new" temp table       */
63526   int oldIdx      = -1;  /* index of trigger "old" temp table       */
63527
63528   sContext.pParse = 0;
63529   db = pParse->db;
63530   if( pParse->nErr || db->mallocFailed ){
63531     goto update_cleanup;
63532   }
63533   assert( pTabList->nSrc==1 );
63534
63535   /* Locate the table which we want to update. 
63536   */
63537   pTab = sqlite3SrcListLookup(pParse, pTabList);
63538   if( pTab==0 ) goto update_cleanup;
63539   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
63540
63541   /* Figure out if we have any triggers and if the table being
63542   ** updated is a view
63543   */
63544 #ifndef SQLITE_OMIT_TRIGGER
63545   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges);
63546   isView = pTab->pSelect!=0;
63547 #else
63548 # define triggers_exist 0
63549 # define isView 0
63550 #endif
63551 #ifdef SQLITE_OMIT_VIEW
63552 # undef isView
63553 # define isView 0
63554 #endif
63555
63556   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
63557     goto update_cleanup;
63558   }
63559   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
63560     goto update_cleanup;
63561   }
63562   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
63563   if( aXRef==0 ) goto update_cleanup;
63564   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
63565
63566   /* If there are FOR EACH ROW triggers, allocate cursors for the
63567   ** special OLD and NEW tables
63568   */
63569   if( triggers_exist ){
63570     newIdx = pParse->nTab++;
63571     oldIdx = pParse->nTab++;
63572   }
63573
63574   /* Allocate a cursors for the main database table and for all indices.
63575   ** The index cursors might not be used, but if they are used they
63576   ** need to occur right after the database cursor.  So go ahead and
63577   ** allocate enough space, just in case.
63578   */
63579   pTabList->a[0].iCursor = iCur = pParse->nTab++;
63580   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
63581     pParse->nTab++;
63582   }
63583
63584   /* Initialize the name-context */
63585   memset(&sNC, 0, sizeof(sNC));
63586   sNC.pParse = pParse;
63587   sNC.pSrcList = pTabList;
63588
63589   /* Resolve the column names in all the expressions of the
63590   ** of the UPDATE statement.  Also find the column index
63591   ** for each column to be updated in the pChanges array.  For each
63592   ** column to be updated, make sure we have authorization to change
63593   ** that column.
63594   */
63595   chngRowid = 0;
63596   for(i=0; i<pChanges->nExpr; i++){
63597     if( sqlite3ExprResolveNames(&sNC, pChanges->a[i].pExpr) ){
63598       goto update_cleanup;
63599     }
63600     for(j=0; j<pTab->nCol; j++){
63601       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
63602         if( j==pTab->iPKey ){
63603           chngRowid = 1;
63604           pRowidExpr = pChanges->a[i].pExpr;
63605         }
63606         aXRef[j] = i;
63607         break;
63608       }
63609     }
63610     if( j>=pTab->nCol ){
63611       if( sqlite3IsRowid(pChanges->a[i].zName) ){
63612         chngRowid = 1;
63613         pRowidExpr = pChanges->a[i].pExpr;
63614       }else{
63615         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
63616         goto update_cleanup;
63617       }
63618     }
63619 #ifndef SQLITE_OMIT_AUTHORIZATION
63620     {
63621       int rc;
63622       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
63623                            pTab->aCol[j].zName, db->aDb[iDb].zName);
63624       if( rc==SQLITE_DENY ){
63625         goto update_cleanup;
63626       }else if( rc==SQLITE_IGNORE ){
63627         aXRef[j] = -1;
63628       }
63629     }
63630 #endif
63631   }
63632
63633   /* Allocate memory for the array apIdx[] and fill it with pointers to every
63634   ** index that needs to be updated.  Indices only need updating if their
63635   ** key includes one of the columns named in pChanges or if the record
63636   ** number of the original table entry is changing.
63637   */
63638   for(nIdx=nIdxTotal=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdxTotal++){
63639     if( chngRowid ){
63640       i = 0;
63641     }else {
63642       for(i=0; i<pIdx->nColumn; i++){
63643         if( aXRef[pIdx->aiColumn[i]]>=0 ) break;
63644       }
63645     }
63646     if( i<pIdx->nColumn ) nIdx++;
63647   }
63648   if( nIdxTotal>0 ){
63649     apIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx + nIdxTotal );
63650     if( apIdx==0 ) goto update_cleanup;
63651     aIdxUsed = (char*)&apIdx[nIdx];
63652   }
63653   for(nIdx=j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
63654     if( chngRowid ){
63655       i = 0;
63656     }else{
63657       for(i=0; i<pIdx->nColumn; i++){
63658         if( aXRef[pIdx->aiColumn[i]]>=0 ) break;
63659       }
63660     }
63661     if( i<pIdx->nColumn ){
63662       apIdx[nIdx++] = pIdx;
63663       aIdxUsed[j] = 1;
63664     }else{
63665       aIdxUsed[j] = 0;
63666     }
63667   }
63668
63669   /* Begin generating code.
63670   */
63671   v = sqlite3GetVdbe(pParse);
63672   if( v==0 ) goto update_cleanup;
63673   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
63674   sqlite3BeginWriteOperation(pParse, 1, iDb);
63675   mem1 = pParse->nMem++;
63676
63677 #ifndef SQLITE_OMIT_VIRTUALTABLE
63678   /* Virtual tables must be handled separately */
63679   if( IsVirtual(pTab) ){
63680     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
63681                        pWhere);
63682     pWhere = 0;
63683     pTabList = 0;
63684     goto update_cleanup;
63685   }
63686 #endif
63687
63688   /* Resolve the column names in all the expressions in the
63689   ** WHERE clause.
63690   */
63691   if( sqlite3ExprResolveNames(&sNC, pWhere) ){
63692     goto update_cleanup;
63693   }
63694
63695   /* Start the view context
63696   */
63697   if( isView ){
63698     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
63699   }
63700
63701   /* If we are trying to update a view, realize that view into
63702   ** a ephemeral table.
63703   */
63704   if( isView ){
63705     Select *pView;
63706     pView = sqlite3SelectDup(db, pTab->pSelect);
63707     sqlite3Select(pParse, pView, SRT_EphemTab, iCur, 0, 0, 0, 0);
63708     sqlite3SelectDelete(pView);
63709   }
63710
63711   /* Begin the database scan
63712   */
63713   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
63714   if( pWInfo==0 ) goto update_cleanup;
63715
63716   /* Remember the rowid of every item to be updated.
63717   */
63718   sqlite3VdbeAddOp(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid, iCur, 0);
63719   sqlite3VdbeAddOp(v, OP_FifoWrite, 0, 0);
63720
63721   /* End the database scan loop.
63722   */
63723   sqlite3WhereEnd(pWInfo);
63724
63725   /* Initialize the count of updated rows
63726   */
63727   if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
63728     memCnt = pParse->nMem++;
63729     sqlite3VdbeAddOp(v, OP_MemInt, 0, memCnt);
63730   }
63731
63732   if( triggers_exist ){
63733     
63734     /* Create pseudo-tables for NEW and OLD
63735     */
63736     sqlite3VdbeAddOp(v, OP_OpenPseudo, oldIdx, 0);
63737     sqlite3VdbeAddOp(v, OP_SetNumColumns, oldIdx, pTab->nCol);
63738     sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
63739     sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
63740
63741     /* The top of the update loop for when there are triggers.
63742     */
63743     addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, 0);
63744     sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0);
63745     sqlite3VdbeAddOp(v, OP_MemStore, mem1, 0);
63746     
63747     if( !isView ){
63748       /* Open a cursor and make it point to the record that is
63749       ** being updated.
63750       */
63751       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
63752     }
63753     sqlite3VdbeAddOp(v, OP_NotExists, iCur, addr);
63754
63755     /* Generate the OLD table
63756     */
63757     sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
63758     sqlite3VdbeAddOp(v, OP_RowData, iCur, 0);
63759     sqlite3VdbeAddOp(v, OP_Insert, oldIdx, 0);
63760
63761     /* Generate the NEW table
63762     */
63763     if( chngRowid ){
63764       sqlite3ExprCodeAndCache(pParse, pRowidExpr);
63765     }else{
63766       sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
63767     }
63768     for(i=0; i<pTab->nCol; i++){
63769       if( i==pTab->iPKey ){
63770         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
63771         continue;
63772       }
63773       j = aXRef[i];
63774       if( j<0 ){
63775         sqlite3VdbeAddOp(v, OP_Column, iCur, i);
63776         sqlite3ColumnDefault(v, pTab, i);
63777       }else{
63778         sqlite3ExprCodeAndCache(pParse, pChanges->a[j].pExpr);
63779       }
63780     }
63781     sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
63782     if( !isView ){
63783       sqlite3TableAffinityStr(v, pTab);
63784     }
63785     if( pParse->nErr ) goto update_cleanup;
63786     sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
63787     if( !isView ){
63788       sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
63789     }
63790
63791     /* Fire the BEFORE and INSTEAD OF triggers
63792     */
63793     if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_BEFORE, pTab,
63794           newIdx, oldIdx, onError, addr) ){
63795       goto update_cleanup;
63796     }
63797     
63798     if( !isView ){
63799       sqlite3VdbeAddOp(v, OP_MemLoad, mem1, 0);
63800     }
63801   }
63802
63803   if( !isView && !IsVirtual(pTab) ){
63804     /* 
63805     ** Open every index that needs updating.  Note that if any
63806     ** index could potentially invoke a REPLACE conflict resolution 
63807     ** action, then we need to open all indices because we might need
63808     ** to be deleting some records.
63809     */
63810     sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
63811     if( onError==OE_Replace ){
63812       openAll = 1;
63813     }else{
63814       openAll = 0;
63815       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
63816         if( pIdx->onError==OE_Replace ){
63817           openAll = 1;
63818           break;
63819         }
63820       }
63821     }
63822     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
63823       if( openAll || aIdxUsed[i] ){
63824         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
63825         sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
63826         sqlite3VdbeOp3(v, OP_OpenWrite, iCur+i+1, pIdx->tnum,
63827                        (char*)pKey, P3_KEYINFO_HANDOFF);
63828         assert( pParse->nTab>iCur+i+1 );
63829       }
63830     }
63831
63832     /* Loop over every record that needs updating.  We have to load
63833     ** the old data for each record to be updated because some columns
63834     ** might not change and we will need to copy the old value.
63835     ** Also, the old data is needed to delete the old index entries.
63836     ** So make the cursor point at the old record.
63837     */
63838     if( !triggers_exist ){
63839       addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, 0);
63840       sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0);
63841       sqlite3VdbeAddOp(v, OP_MemStore, mem1, 0);
63842     }
63843     sqlite3VdbeAddOp(v, OP_NotExists, iCur, addr);
63844     sqlite3VdbeAddOp(v, OP_MemLoad, mem1, 0);
63845
63846     /* If the record number will change, push the record number as it
63847     ** will be after the update. (The old record number is currently
63848     ** on top of the stack.)
63849     */
63850     if( chngRowid ){
63851       sqlite3ExprCode(pParse, pRowidExpr);
63852       sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
63853     }
63854
63855     /* Compute new data for this record.  
63856     */
63857     for(i=0; i<pTab->nCol; i++){
63858       if( i==pTab->iPKey ){
63859         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
63860         continue;
63861       }
63862       j = aXRef[i];
63863       if( j<0 ){
63864         sqlite3VdbeAddOp(v, OP_Column, iCur, i);
63865         sqlite3ColumnDefault(v, pTab, i);
63866       }else{
63867         sqlite3ExprCode(pParse, pChanges->a[j].pExpr);
63868       }
63869     }
63870
63871     /* Do constraint checks
63872     */
63873     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, aIdxUsed, chngRowid, 1,
63874                                    onError, addr);
63875
63876     /* Delete the old indices for the current record.
63877     */
63878     sqlite3GenerateRowIndexDelete(v, pTab, iCur, aIdxUsed);
63879
63880     /* If changing the record number, delete the old record.
63881     */
63882     if( chngRowid ){
63883       sqlite3VdbeAddOp(v, OP_Delete, iCur, 0);
63884     }
63885
63886     /* Create the new index entries and the new record.
63887     */
63888     sqlite3CompleteInsertion(pParse, pTab, iCur, aIdxUsed, chngRowid, 1, -1, 0);
63889   }
63890
63891   /* Increment the row counter 
63892   */
63893   if( db->flags & SQLITE_CountRows && !pParse->trigStack){
63894     sqlite3VdbeAddOp(v, OP_MemIncr, 1, memCnt);
63895   }
63896
63897   /* If there are triggers, close all the cursors after each iteration
63898   ** through the loop.  The fire the after triggers.
63899   */
63900   if( triggers_exist ){
63901     if( !isView ){
63902       for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
63903         if( openAll || aIdxUsed[i] )
63904           sqlite3VdbeAddOp(v, OP_Close, iCur+i+1, 0);
63905       }
63906       sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
63907     }
63908     if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_AFTER, pTab, 
63909           newIdx, oldIdx, onError, addr) ){
63910       goto update_cleanup;
63911     }
63912   }
63913
63914   /* Repeat the above with the next record to be updated, until
63915   ** all record selected by the WHERE clause have been updated.
63916   */
63917   sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
63918   sqlite3VdbeJumpHere(v, addr);
63919
63920   /* Close all tables if there were no FOR EACH ROW triggers */
63921   if( !triggers_exist ){
63922     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
63923       if( openAll || aIdxUsed[i] ){
63924         sqlite3VdbeAddOp(v, OP_Close, iCur+i+1, 0);
63925       }
63926     }
63927     sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
63928   }else{
63929     sqlite3VdbeAddOp(v, OP_Close, newIdx, 0);
63930     sqlite3VdbeAddOp(v, OP_Close, oldIdx, 0);
63931   }
63932
63933   /*
63934   ** Return the number of rows that were changed. If this routine is 
63935   ** generating code because of a call to sqlite3NestedParse(), do not
63936   ** invoke the callback function.
63937   */
63938   if( db->flags & SQLITE_CountRows && !pParse->trigStack && pParse->nested==0 ){
63939     sqlite3VdbeAddOp(v, OP_MemLoad, memCnt, 0);
63940     sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
63941     sqlite3VdbeSetNumCols(v, 1);
63942     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", P3_STATIC);
63943   }
63944
63945 update_cleanup:
63946   sqlite3AuthContextPop(&sContext);
63947   sqlite3_free(apIdx);
63948   sqlite3_free(aXRef);
63949   sqlite3SrcListDelete(pTabList);
63950   sqlite3ExprListDelete(pChanges);
63951   sqlite3ExprDelete(pWhere);
63952   return;
63953 }
63954
63955 #ifndef SQLITE_OMIT_VIRTUALTABLE
63956 /*
63957 ** Generate code for an UPDATE of a virtual table.
63958 **
63959 ** The strategy is that we create an ephemerial table that contains
63960 ** for each row to be changed:
63961 **
63962 **   (A)  The original rowid of that row.
63963 **   (B)  The revised rowid for the row. (note1)
63964 **   (C)  The content of every column in the row.
63965 **
63966 ** Then we loop over this ephemeral table and for each row in
63967 ** the ephermeral table call VUpdate.
63968 **
63969 ** When finished, drop the ephemeral table.
63970 **
63971 ** (note1) Actually, if we know in advance that (A) is always the same
63972 ** as (B) we only store (A), then duplicate (A) when pulling
63973 ** it out of the ephemeral table before calling VUpdate.
63974 */
63975 static void updateVirtualTable(
63976   Parse *pParse,       /* The parsing context */
63977   SrcList *pSrc,       /* The virtual table to be modified */
63978   Table *pTab,         /* The virtual table */
63979   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
63980   Expr *pRowid,        /* Expression used to recompute the rowid */
63981   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
63982   Expr *pWhere         /* WHERE clause of the UPDATE statement */
63983 ){
63984   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
63985   ExprList *pEList = 0;     /* The result set of the SELECT statement */
63986   Select *pSelect = 0;      /* The SELECT statement */
63987   Expr *pExpr;              /* Temporary expression */
63988   int ephemTab;             /* Table holding the result of the SELECT */
63989   int i;                    /* Loop counter */
63990   int addr;                 /* Address of top of loop */
63991   sqlite3 *db = pParse->db; /* Database connection */
63992
63993   /* Construct the SELECT statement that will find the new values for
63994   ** all updated rows. 
63995   */
63996   pEList = sqlite3ExprListAppend(pParse, 0, 
63997                                  sqlite3CreateIdExpr(pParse, "_rowid_"), 0);
63998   if( pRowid ){
63999     pEList = sqlite3ExprListAppend(pParse, pEList,
64000                                    sqlite3ExprDup(db, pRowid), 0);
64001   }
64002   assert( pTab->iPKey<0 );
64003   for(i=0; i<pTab->nCol; i++){
64004     if( aXRef[i]>=0 ){
64005       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr);
64006     }else{
64007       pExpr = sqlite3CreateIdExpr(pParse, pTab->aCol[i].zName);
64008     }
64009     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr, 0);
64010   }
64011   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
64012   
64013   /* Create the ephemeral table into which the update results will
64014   ** be stored.
64015   */
64016   assert( v );
64017   ephemTab = pParse->nTab++;
64018   sqlite3VdbeAddOp(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
64019
64020   /* fill the ephemeral table 
64021   */
64022   sqlite3Select(pParse, pSelect, SRT_Table, ephemTab, 0, 0, 0, 0);
64023
64024   /*
64025   ** Generate code to scan the ephemeral table and call VDelete and
64026   ** VInsert
64027   */
64028   sqlite3VdbeAddOp(v, OP_Rewind, ephemTab, 0);
64029   addr = sqlite3VdbeCurrentAddr(v);
64030   sqlite3VdbeAddOp(v, OP_Column,  ephemTab, 0);
64031   if( pRowid ){
64032     sqlite3VdbeAddOp(v, OP_Column, ephemTab, 1);
64033   }else{
64034     sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
64035   }
64036   for(i=0; i<pTab->nCol; i++){
64037     sqlite3VdbeAddOp(v, OP_Column, ephemTab, i+1+(pRowid!=0));
64038   }
64039   pParse->pVirtualLock = pTab;
64040   sqlite3VdbeOp3(v, OP_VUpdate, 0, pTab->nCol+2, 
64041                      (const char*)pTab->pVtab, P3_VTAB);
64042   sqlite3VdbeAddOp(v, OP_Next, ephemTab, addr);
64043   sqlite3VdbeJumpHere(v, addr-1);
64044   sqlite3VdbeAddOp(v, OP_Close, ephemTab, 0);
64045
64046   /* Cleanup */
64047   sqlite3SelectDelete(pSelect);  
64048 }
64049 #endif /* SQLITE_OMIT_VIRTUALTABLE */
64050
64051 /************** End of update.c **********************************************/
64052 /************** Begin file vacuum.c ******************************************/
64053 /*
64054 ** 2003 April 6
64055 **
64056 ** The author disclaims copyright to this source code.  In place of
64057 ** a legal notice, here is a blessing:
64058 **
64059 **    May you do good and not evil.
64060 **    May you find forgiveness for yourself and forgive others.
64061 **    May you share freely, never taking more than you give.
64062 **
64063 *************************************************************************
64064 ** This file contains code used to implement the VACUUM command.
64065 **
64066 ** Most of the code in this file may be omitted by defining the
64067 ** SQLITE_OMIT_VACUUM macro.
64068 **
64069 ** $Id: vacuum.c,v 1.75 2007/12/05 01:38:24 drh Exp $
64070 */
64071
64072 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
64073 /*
64074 ** Execute zSql on database db. Return an error code.
64075 */
64076 static int execSql(sqlite3 *db, const char *zSql){
64077   sqlite3_stmt *pStmt;
64078   if( !zSql ){
64079     return SQLITE_NOMEM;
64080   }
64081   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
64082     return sqlite3_errcode(db);
64083   }
64084   while( SQLITE_ROW==sqlite3_step(pStmt) ){}
64085   return sqlite3_finalize(pStmt);
64086 }
64087
64088 /*
64089 ** Execute zSql on database db. The statement returns exactly
64090 ** one column. Execute this as SQL on the same database.
64091 */
64092 static int execExecSql(sqlite3 *db, const char *zSql){
64093   sqlite3_stmt *pStmt;
64094   int rc;
64095
64096   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
64097   if( rc!=SQLITE_OK ) return rc;
64098
64099   while( SQLITE_ROW==sqlite3_step(pStmt) ){
64100     rc = execSql(db, (char*)sqlite3_column_text(pStmt, 0));
64101     if( rc!=SQLITE_OK ){
64102       sqlite3_finalize(pStmt);
64103       return rc;
64104     }
64105   }
64106
64107   return sqlite3_finalize(pStmt);
64108 }
64109
64110 /*
64111 ** The non-standard VACUUM command is used to clean up the database,
64112 ** collapse free space, etc.  It is modelled after the VACUUM command
64113 ** in PostgreSQL.
64114 **
64115 ** In version 1.0.x of SQLite, the VACUUM command would call
64116 ** gdbm_reorganize() on all the database tables.  But beginning
64117 ** with 2.0.0, SQLite no longer uses GDBM so this command has
64118 ** become a no-op.
64119 */
64120 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
64121   Vdbe *v = sqlite3GetVdbe(pParse);
64122   if( v ){
64123     sqlite3VdbeAddOp(v, OP_Vacuum, 0, 0);
64124   }
64125   return;
64126 }
64127
64128 /*
64129 ** This routine implements the OP_Vacuum opcode of the VDBE.
64130 */
64131 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
64132   int rc = SQLITE_OK;     /* Return code from service routines */
64133   Btree *pMain;           /* The database being vacuumed */
64134   Btree *pTemp;           /* The temporary database we vacuum into */
64135   char *zSql = 0;         /* SQL statements */
64136   int saved_flags;        /* Saved value of the db->flags */
64137   Db *pDb = 0;            /* Database to detach at end of vacuum */
64138
64139   /* Save the current value of the write-schema flag before setting it. */
64140   saved_flags = db->flags;
64141   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
64142
64143   if( !db->autoCommit ){
64144     sqlite3SetString(pzErrMsg, "cannot VACUUM from within a transaction", 
64145        (char*)0);
64146     rc = SQLITE_ERROR;
64147     goto end_of_vacuum;
64148   }
64149   pMain = db->aDb[0].pBt;
64150
64151   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
64152   ** can be set to 'off' for this file, as it is not recovered if a crash
64153   ** occurs anyway. The integrity of the database is maintained by a
64154   ** (possibly synchronous) transaction opened on the main database before
64155   ** sqlite3BtreeCopyFile() is called.
64156   **
64157   ** An optimisation would be to use a non-journaled pager.
64158   */
64159   zSql = "ATTACH '' AS vacuum_db;";
64160   rc = execSql(db, zSql);
64161   if( rc!=SQLITE_OK ) goto end_of_vacuum;
64162   pDb = &db->aDb[db->nDb-1];
64163   assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
64164   pTemp = db->aDb[db->nDb-1].pBt;
64165   sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain),
64166      sqlite3BtreeGetReserve(pMain));
64167   if( db->mallocFailed ){
64168     rc = SQLITE_NOMEM;
64169     goto end_of_vacuum;
64170   }
64171   assert( sqlite3BtreeGetPageSize(pTemp)==sqlite3BtreeGetPageSize(pMain) );
64172   rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
64173   if( rc!=SQLITE_OK ){
64174     goto end_of_vacuum;
64175   }
64176
64177 #ifndef SQLITE_OMIT_AUTOVACUUM
64178   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
64179                                            sqlite3BtreeGetAutoVacuum(pMain));
64180 #endif
64181
64182   /* Begin a transaction */
64183   rc = execSql(db, "BEGIN EXCLUSIVE;");
64184   if( rc!=SQLITE_OK ) goto end_of_vacuum;
64185
64186   /* Query the schema of the main database. Create a mirror schema
64187   ** in the temporary database.
64188   */
64189   rc = execExecSql(db, 
64190       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
64191       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
64192       "   AND rootpage>0"
64193   );
64194   if( rc!=SQLITE_OK ) goto end_of_vacuum;
64195   rc = execExecSql(db, 
64196       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
64197       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
64198   if( rc!=SQLITE_OK ) goto end_of_vacuum;
64199   rc = execExecSql(db, 
64200       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
64201       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
64202   if( rc!=SQLITE_OK ) goto end_of_vacuum;
64203
64204   /* Loop through the tables in the main database. For each, do
64205   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM xxx;" to copy
64206   ** the contents to the temporary database.
64207   */
64208   rc = execExecSql(db, 
64209       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
64210       "|| ' SELECT * FROM ' || quote(name) || ';'"
64211       "FROM sqlite_master "
64212       "WHERE type = 'table' AND name!='sqlite_sequence' "
64213       "  AND rootpage>0"
64214
64215   );
64216   if( rc!=SQLITE_OK ) goto end_of_vacuum;
64217
64218   /* Copy over the sequence table
64219   */
64220   rc = execExecSql(db, 
64221       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
64222       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
64223   );
64224   if( rc!=SQLITE_OK ) goto end_of_vacuum;
64225   rc = execExecSql(db, 
64226       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
64227       "|| ' SELECT * FROM ' || quote(name) || ';' "
64228       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
64229   );
64230   if( rc!=SQLITE_OK ) goto end_of_vacuum;
64231
64232
64233   /* Copy the triggers, views, and virtual tables from the main database
64234   ** over to the temporary database.  None of these objects has any
64235   ** associated storage, so all we have to do is copy their entries
64236   ** from the SQLITE_MASTER table.
64237   */
64238   rc = execSql(db,
64239       "INSERT INTO vacuum_db.sqlite_master "
64240       "  SELECT type, name, tbl_name, rootpage, sql"
64241       "    FROM sqlite_master"
64242       "   WHERE type='view' OR type='trigger'"
64243       "      OR (type='table' AND rootpage=0)"
64244   );
64245   if( rc ) goto end_of_vacuum;
64246
64247   /* At this point, unless the main db was completely empty, there is now a
64248   ** transaction open on the vacuum database, but not on the main database.
64249   ** Open a btree level transaction on the main database. This allows a
64250   ** call to sqlite3BtreeCopyFile(). The main database btree level
64251   ** transaction is then committed, so the SQL level never knows it was
64252   ** opened for writing. This way, the SQL transaction used to create the
64253   ** temporary database never needs to be committed.
64254   */
64255   if( rc==SQLITE_OK ){
64256     u32 meta;
64257     int i;
64258
64259     /* This array determines which meta meta values are preserved in the
64260     ** vacuum.  Even entries are the meta value number and odd entries
64261     ** are an increment to apply to the meta value after the vacuum.
64262     ** The increment is used to increase the schema cookie so that other
64263     ** connections to the same database will know to reread the schema.
64264     */
64265     static const unsigned char aCopy[] = {
64266        1, 1,    /* Add one to the old schema cookie */
64267        3, 0,    /* Preserve the default page cache size */
64268        5, 0,    /* Preserve the default text encoding */
64269        6, 0,    /* Preserve the user version */
64270     };
64271
64272     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
64273     assert( 1==sqlite3BtreeIsInTrans(pMain) );
64274
64275     /* Copy Btree meta values */
64276     for(i=0; i<sizeof(aCopy)/sizeof(aCopy[0]); i+=2){
64277       rc = sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
64278       if( rc!=SQLITE_OK ) goto end_of_vacuum;
64279       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
64280       if( rc!=SQLITE_OK ) goto end_of_vacuum;
64281     }
64282
64283     rc = sqlite3BtreeCopyFile(pMain, pTemp);
64284     if( rc!=SQLITE_OK ) goto end_of_vacuum;
64285     rc = sqlite3BtreeCommit(pTemp);
64286     if( rc!=SQLITE_OK ) goto end_of_vacuum;
64287     rc = sqlite3BtreeCommit(pMain);
64288   }
64289
64290 end_of_vacuum:
64291   /* Restore the original value of db->flags */
64292   db->flags = saved_flags;
64293
64294   /* Currently there is an SQL level transaction open on the vacuum
64295   ** database. No locks are held on any other files (since the main file
64296   ** was committed at the btree level). So it safe to end the transaction
64297   ** by manually setting the autoCommit flag to true and detaching the
64298   ** vacuum database. The vacuum_db journal file is deleted when the pager
64299   ** is closed by the DETACH.
64300   */
64301   db->autoCommit = 1;
64302
64303   if( pDb ){
64304     sqlite3BtreeClose(pDb->pBt);
64305     pDb->pBt = 0;
64306     pDb->pSchema = 0;
64307   }
64308
64309   sqlite3ResetInternalSchema(db, 0);
64310
64311   return rc;
64312 }
64313 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
64314
64315 /************** End of vacuum.c **********************************************/
64316 /************** Begin file vtab.c ********************************************/
64317 /*
64318 ** 2006 June 10
64319 **
64320 ** The author disclaims copyright to this source code.  In place of
64321 ** a legal notice, here is a blessing:
64322 **
64323 **    May you do good and not evil.
64324 **    May you find forgiveness for yourself and forgive others.
64325 **    May you share freely, never taking more than you give.
64326 **
64327 *************************************************************************
64328 ** This file contains code used to help implement virtual tables.
64329 **
64330 ** $Id: vtab.c,v 1.59 2007/09/20 11:32:18 rse Exp $
64331 */
64332 #ifndef SQLITE_OMIT_VIRTUALTABLE
64333
64334 static int createModule(
64335   sqlite3 *db,                    /* Database in which module is registered */
64336   const char *zName,              /* Name assigned to this module */
64337   const sqlite3_module *pModule,  /* The definition of the module */
64338   void *pAux,                     /* Context pointer for xCreate/xConnect */
64339   void (*xDestroy)(void *)        /* Module destructor function */
64340 ) {
64341   int rc, nName;
64342   Module *pMod;
64343
64344   sqlite3_mutex_enter(db->mutex);
64345   nName = strlen(zName);
64346   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
64347   if( pMod ){
64348     char *zCopy = (char *)(&pMod[1]);
64349     memcpy(zCopy, zName, nName+1);
64350     pMod->zName = zCopy;
64351     pMod->pModule = pModule;
64352     pMod->pAux = pAux;
64353     pMod->xDestroy = xDestroy;
64354     pMod = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
64355     if( pMod && pMod->xDestroy ){
64356       pMod->xDestroy(pMod->pAux);
64357     }
64358     sqlite3_free(pMod);
64359     sqlite3ResetInternalSchema(db, 0);
64360   }
64361   rc = sqlite3ApiExit(db, SQLITE_OK);
64362   sqlite3_mutex_leave(db->mutex);
64363   return rc;
64364 }
64365
64366
64367 /*
64368 ** External API function used to create a new virtual-table module.
64369 */
64370 SQLITE_API int sqlite3_create_module(
64371   sqlite3 *db,                    /* Database in which module is registered */
64372   const char *zName,              /* Name assigned to this module */
64373   const sqlite3_module *pModule,  /* The definition of the module */
64374   void *pAux                      /* Context pointer for xCreate/xConnect */
64375 ){
64376   return createModule(db, zName, pModule, pAux, 0);
64377 }
64378
64379 /*
64380 ** External API function used to create a new virtual-table module.
64381 */
64382 SQLITE_API int sqlite3_create_module_v2(
64383   sqlite3 *db,                    /* Database in which module is registered */
64384   const char *zName,              /* Name assigned to this module */
64385   const sqlite3_module *pModule,  /* The definition of the module */
64386   void *pAux,                     /* Context pointer for xCreate/xConnect */
64387   void (*xDestroy)(void *)        /* Module destructor function */
64388 ){
64389   return createModule(db, zName, pModule, pAux, xDestroy);
64390 }
64391
64392 /*
64393 ** Lock the virtual table so that it cannot be disconnected.
64394 ** Locks nest.  Every lock should have a corresponding unlock.
64395 ** If an unlock is omitted, resources leaks will occur.  
64396 **
64397 ** If a disconnect is attempted while a virtual table is locked,
64398 ** the disconnect is deferred until all locks have been removed.
64399 */
64400 SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab *pVtab){
64401   pVtab->nRef++;
64402 }
64403
64404 /*
64405 ** Unlock a virtual table.  When the last lock is removed,
64406 ** disconnect the virtual table.
64407 */
64408 SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3 *db, sqlite3_vtab *pVtab){
64409   pVtab->nRef--;
64410   assert(db);
64411   assert(!sqlite3SafetyCheck(db));
64412   if( pVtab->nRef==0 ){
64413     if( db->magic==SQLITE_MAGIC_BUSY ){
64414       sqlite3SafetyOff(db);
64415       pVtab->pModule->xDisconnect(pVtab);
64416       sqlite3SafetyOn(db);
64417     } else {
64418       pVtab->pModule->xDisconnect(pVtab);
64419     }
64420   }
64421 }
64422
64423 /*
64424 ** Clear any and all virtual-table information from the Table record.
64425 ** This routine is called, for example, just before deleting the Table
64426 ** record.
64427 */
64428 SQLITE_PRIVATE void sqlite3VtabClear(Table *p){
64429   sqlite3_vtab *pVtab = p->pVtab;
64430   if( pVtab ){
64431     assert( p->pMod && p->pMod->pModule );
64432     sqlite3VtabUnlock(p->pSchema->db, pVtab);
64433     p->pVtab = 0;
64434   }
64435   if( p->azModuleArg ){
64436     int i;
64437     for(i=0; i<p->nModuleArg; i++){
64438       sqlite3_free(p->azModuleArg[i]);
64439     }
64440     sqlite3_free(p->azModuleArg);
64441   }
64442 }
64443
64444 /*
64445 ** Add a new module argument to pTable->azModuleArg[].
64446 ** The string is not copied - the pointer is stored.  The
64447 ** string will be freed automatically when the table is
64448 ** deleted.
64449 */
64450 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
64451   int i = pTable->nModuleArg++;
64452   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
64453   char **azModuleArg;
64454   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
64455   if( azModuleArg==0 ){
64456     int j;
64457     for(j=0; j<i; j++){
64458       sqlite3_free(pTable->azModuleArg[j]);
64459     }
64460     sqlite3_free(zArg);
64461     sqlite3_free(pTable->azModuleArg);
64462     pTable->nModuleArg = 0;
64463   }else{
64464     azModuleArg[i] = zArg;
64465     azModuleArg[i+1] = 0;
64466   }
64467   pTable->azModuleArg = azModuleArg;
64468 }
64469
64470 /*
64471 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
64472 ** statement.  The module name has been parsed, but the optional list
64473 ** of parameters that follow the module name are still pending.
64474 */
64475 SQLITE_PRIVATE void sqlite3VtabBeginParse(
64476   Parse *pParse,        /* Parsing context */
64477   Token *pName1,        /* Name of new table, or database name */
64478   Token *pName2,        /* Name of new table or NULL */
64479   Token *pModuleName    /* Name of the module for the virtual table */
64480 ){
64481   int iDb;              /* The database the table is being created in */
64482   Table *pTable;        /* The new virtual table */
64483   sqlite3 *db;          /* Database connection */
64484
64485   if( pParse->db->flags & SQLITE_SharedCache ){
64486     sqlite3ErrorMsg(pParse, "Cannot use virtual tables in shared-cache mode");
64487     return;
64488   }
64489
64490   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
64491   pTable = pParse->pNewTable;
64492   if( pTable==0 || pParse->nErr ) return;
64493   assert( 0==pTable->pIndex );
64494
64495   db = pParse->db;
64496   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
64497   assert( iDb>=0 );
64498
64499   pTable->isVirtual = 1;
64500   pTable->nModuleArg = 0;
64501   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
64502   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
64503   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
64504   pParse->sNameToken.n = pModuleName->z + pModuleName->n - pName1->z;
64505
64506 #ifndef SQLITE_OMIT_AUTHORIZATION
64507   /* Creating a virtual table invokes the authorization callback twice.
64508   ** The first invocation, to obtain permission to INSERT a row into the
64509   ** sqlite_master table, has already been made by sqlite3StartTable().
64510   ** The second call, to obtain permission to create the table, is made now.
64511   */
64512   if( pTable->azModuleArg ){
64513     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
64514             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
64515   }
64516 #endif
64517 }
64518
64519 /*
64520 ** This routine takes the module argument that has been accumulating
64521 ** in pParse->zArg[] and appends it to the list of arguments on the
64522 ** virtual table currently under construction in pParse->pTable.
64523 */
64524 static void addArgumentToVtab(Parse *pParse){
64525   if( pParse->sArg.z && pParse->pNewTable ){
64526     const char *z = (const char*)pParse->sArg.z;
64527     int n = pParse->sArg.n;
64528     sqlite3 *db = pParse->db;
64529     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
64530   }
64531 }
64532
64533 /*
64534 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
64535 ** has been completely parsed.
64536 */
64537 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
64538   Table *pTab;        /* The table being constructed */
64539   sqlite3 *db;        /* The database connection */
64540   char *zModule;      /* The module name of the table: USING modulename */
64541   Module *pMod = 0;
64542
64543   addArgumentToVtab(pParse);
64544   pParse->sArg.z = 0;
64545
64546   /* Lookup the module name. */
64547   pTab = pParse->pNewTable;
64548   if( pTab==0 ) return;
64549   db = pParse->db;
64550   if( pTab->nModuleArg<1 ) return;
64551   zModule = pTab->azModuleArg[0];
64552   pMod = (Module *)sqlite3HashFind(&db->aModule, zModule, strlen(zModule));
64553   pTab->pMod = pMod;
64554   
64555   /* If the CREATE VIRTUAL TABLE statement is being entered for the
64556   ** first time (in other words if the virtual table is actually being
64557   ** created now instead of just being read out of sqlite_master) then
64558   ** do additional initialization work and store the statement text
64559   ** in the sqlite_master table.
64560   */
64561   if( !db->init.busy ){
64562     char *zStmt;
64563     char *zWhere;
64564     int iDb;
64565     Vdbe *v;
64566
64567     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
64568     if( pEnd ){
64569       pParse->sNameToken.n = pEnd->z - pParse->sNameToken.z + pEnd->n;
64570     }
64571     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
64572
64573     /* A slot for the record has already been allocated in the 
64574     ** SQLITE_MASTER table.  We just need to update that slot with all
64575     ** the information we've collected.  
64576     **
64577     ** The top of the stack is the rootpage allocated by sqlite3StartTable().
64578     ** This value is always 0 and is ignored, a virtual table does not have a
64579     ** rootpage. The next entry on the stack is the rowid of the record
64580     ** in the sqlite_master table.
64581     */
64582     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
64583     sqlite3NestedParse(pParse,
64584       "UPDATE %Q.%s "
64585          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
64586        "WHERE rowid=#1",
64587       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
64588       pTab->zName,
64589       pTab->zName,
64590       zStmt
64591     );
64592     sqlite3_free(zStmt);
64593     v = sqlite3GetVdbe(pParse);
64594     sqlite3ChangeCookie(db, v, iDb);
64595
64596     sqlite3VdbeAddOp(v, OP_Expire, 0, 0);
64597     zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
64598     sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 1, zWhere, P3_DYNAMIC);
64599     sqlite3VdbeOp3(v, OP_VCreate, iDb, 0, pTab->zName, strlen(pTab->zName) + 1);
64600   }
64601
64602   /* If we are rereading the sqlite_master table create the in-memory
64603   ** record of the table. If the module has already been registered,
64604   ** also call the xConnect method here.
64605   */
64606   else {
64607     Table *pOld;
64608     Schema *pSchema = pTab->pSchema;
64609     const char *zName = pTab->zName;
64610     int nName = strlen(zName) + 1;
64611     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
64612     if( pOld ){
64613       db->mallocFailed = 1;
64614       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
64615       return;
64616     }
64617     pSchema->db = pParse->db;
64618     pParse->pNewTable = 0;
64619   }
64620 }
64621
64622 /*
64623 ** The parser calls this routine when it sees the first token
64624 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
64625 */
64626 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
64627   addArgumentToVtab(pParse);
64628   pParse->sArg.z = 0;
64629   pParse->sArg.n = 0;
64630 }
64631
64632 /*
64633 ** The parser calls this routine for each token after the first token
64634 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
64635 */
64636 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
64637   Token *pArg = &pParse->sArg;
64638   if( pArg->z==0 ){
64639     pArg->z = p->z;
64640     pArg->n = p->n;
64641   }else{
64642     assert(pArg->z < p->z);
64643     pArg->n = (p->z + p->n - pArg->z);
64644   }
64645 }
64646
64647 /*
64648 ** Invoke a virtual table constructor (either xCreate or xConnect). The
64649 ** pointer to the function to invoke is passed as the fourth parameter
64650 ** to this procedure.
64651 */
64652 static int vtabCallConstructor(
64653   sqlite3 *db, 
64654   Table *pTab,
64655   Module *pMod,
64656   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
64657   char **pzErr
64658 ){
64659   int rc;
64660   int rc2;
64661   sqlite3_vtab *pVtab = 0;
64662   const char *const*azArg = (const char *const*)pTab->azModuleArg;
64663   int nArg = pTab->nModuleArg;
64664   char *zErr = 0;
64665   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
64666
64667   if( !zModuleName ){
64668     return SQLITE_NOMEM;
64669   }
64670
64671   assert( !db->pVTab );
64672   assert( xConstruct );
64673
64674   db->pVTab = pTab;
64675   rc = sqlite3SafetyOff(db);
64676   assert( rc==SQLITE_OK );
64677   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVtab, &zErr);
64678   rc2 = sqlite3SafetyOn(db);
64679   if( rc==SQLITE_OK && pVtab ){
64680     pVtab->pModule = pMod->pModule;
64681     pVtab->nRef = 1;
64682     pTab->pVtab = pVtab;
64683   }
64684
64685   if( SQLITE_OK!=rc ){
64686     if( zErr==0 ){
64687       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
64688     }else {
64689       *pzErr = sqlite3MPrintf(db, "%s", zErr);
64690       sqlite3_free(zErr);
64691     }
64692   }else if( db->pVTab ){
64693     const char *zFormat = "vtable constructor did not declare schema: %s";
64694     *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
64695     rc = SQLITE_ERROR;
64696   } 
64697   if( rc==SQLITE_OK ){
64698     rc = rc2;
64699   }
64700   db->pVTab = 0;
64701   sqlite3_free(zModuleName);
64702
64703   /* If everything went according to plan, loop through the columns
64704   ** of the table to see if any of them contain the token "hidden".
64705   ** If so, set the Column.isHidden flag and remove the token from
64706   ** the type string.
64707   */
64708   if( rc==SQLITE_OK ){
64709     int iCol;
64710     for(iCol=0; iCol<pTab->nCol; iCol++){
64711       char *zType = pTab->aCol[iCol].zType;
64712       int nType;
64713       int i = 0;
64714       if( !zType ) continue;
64715       nType = strlen(zType);
64716       if( sqlite3StrNICmp("hidden", zType, 6) || (zType[6] && zType[6]!=' ') ){
64717         for(i=0; i<nType; i++){
64718           if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
64719            && (zType[i+7]=='\0' || zType[i+7]==' ')
64720           ){
64721             i++;
64722             break;
64723           }
64724         }
64725       }
64726       if( i<nType ){
64727         int j;
64728         int nDel = 6 + (zType[i+6] ? 1 : 0);
64729         for(j=i; (j+nDel)<=nType; j++){
64730           zType[j] = zType[j+nDel];
64731         }
64732         if( zType[i]=='\0' && i>0 ){
64733           assert(zType[i-1]==' ');
64734           zType[i-1] = '\0';
64735         }
64736         pTab->aCol[iCol].isHidden = 1;
64737       }
64738     }
64739   }
64740   return rc;
64741 }
64742
64743 /*
64744 ** This function is invoked by the parser to call the xConnect() method
64745 ** of the virtual table pTab. If an error occurs, an error code is returned 
64746 ** and an error left in pParse.
64747 **
64748 ** This call is a no-op if table pTab is not a virtual table.
64749 */
64750 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
64751   Module *pMod;
64752   int rc = SQLITE_OK;
64753
64754   if( !pTab || !pTab->isVirtual || pTab->pVtab ){
64755     return SQLITE_OK;
64756   }
64757
64758   pMod = pTab->pMod;
64759   if( !pMod ){
64760     const char *zModule = pTab->azModuleArg[0];
64761     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
64762     rc = SQLITE_ERROR;
64763   } else {
64764     char *zErr = 0;
64765     sqlite3 *db = pParse->db;
64766     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
64767     if( rc!=SQLITE_OK ){
64768       sqlite3ErrorMsg(pParse, "%s", zErr);
64769     }
64770     sqlite3_free(zErr);
64771   }
64772
64773   return rc;
64774 }
64775
64776 /*
64777 ** Add the virtual table pVtab to the array sqlite3.aVTrans[].
64778 */
64779 static int addToVTrans(sqlite3 *db, sqlite3_vtab *pVtab){
64780   const int ARRAY_INCR = 5;
64781
64782   /* Grow the sqlite3.aVTrans array if required */
64783   if( (db->nVTrans%ARRAY_INCR)==0 ){
64784     sqlite3_vtab **aVTrans;
64785     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
64786     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
64787     if( !aVTrans ){
64788       return SQLITE_NOMEM;
64789     }
64790     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
64791     db->aVTrans = aVTrans;
64792   }
64793
64794   /* Add pVtab to the end of sqlite3.aVTrans */
64795   db->aVTrans[db->nVTrans++] = pVtab;
64796   sqlite3VtabLock(pVtab);
64797   return SQLITE_OK;
64798 }
64799
64800 /*
64801 ** This function is invoked by the vdbe to call the xCreate method
64802 ** of the virtual table named zTab in database iDb. 
64803 **
64804 ** If an error occurs, *pzErr is set to point an an English language
64805 ** description of the error and an SQLITE_XXX error code is returned.
64806 ** In this case the caller must call sqlite3_free() on *pzErr.
64807 */
64808 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
64809   int rc = SQLITE_OK;
64810   Table *pTab;
64811   Module *pMod;
64812   const char *zModule;
64813
64814   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
64815   assert(pTab && pTab->isVirtual && !pTab->pVtab);
64816   pMod = pTab->pMod;
64817   zModule = pTab->azModuleArg[0];
64818
64819   /* If the module has been registered and includes a Create method, 
64820   ** invoke it now. If the module has not been registered, return an 
64821   ** error. Otherwise, do nothing.
64822   */
64823   if( !pMod ){
64824     *pzErr = sqlite3MPrintf(db, "no such module: %s", zModule);
64825     rc = SQLITE_ERROR;
64826   }else{
64827     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
64828   }
64829
64830   if( rc==SQLITE_OK && pTab->pVtab ){
64831       rc = addToVTrans(db, pTab->pVtab);
64832   }
64833
64834   return rc;
64835 }
64836
64837 /*
64838 ** This function is used to set the schema of a virtual table.  It is only
64839 ** valid to call this function from within the xCreate() or xConnect() of a
64840 ** virtual table module.
64841 */
64842 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
64843   Parse sParse;
64844
64845   int rc = SQLITE_OK;
64846   Table *pTab;
64847   char *zErr = 0;
64848
64849   sqlite3_mutex_enter(db->mutex);
64850   pTab = db->pVTab;
64851   if( !pTab ){
64852     sqlite3Error(db, SQLITE_MISUSE, 0);
64853     sqlite3_mutex_leave(db->mutex);
64854     return SQLITE_MISUSE;
64855   }
64856   assert(pTab->isVirtual && pTab->nCol==0 && pTab->aCol==0);
64857
64858   memset(&sParse, 0, sizeof(Parse));
64859   sParse.declareVtab = 1;
64860   sParse.db = db;
64861
64862   if( 
64863       SQLITE_OK == sqlite3RunParser(&sParse, zCreateTable, &zErr) && 
64864       sParse.pNewTable && 
64865       !sParse.pNewTable->pSelect && 
64866       !sParse.pNewTable->isVirtual 
64867   ){
64868     pTab->aCol = sParse.pNewTable->aCol;
64869     pTab->nCol = sParse.pNewTable->nCol;
64870     sParse.pNewTable->nCol = 0;
64871     sParse.pNewTable->aCol = 0;
64872     db->pVTab = 0;
64873   } else {
64874     sqlite3Error(db, SQLITE_ERROR, zErr);
64875     sqlite3_free(zErr);
64876     rc = SQLITE_ERROR;
64877   }
64878   sParse.declareVtab = 0;
64879
64880   sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
64881   sqlite3DeleteTable(sParse.pNewTable);
64882   sParse.pNewTable = 0;
64883
64884   assert( (rc&0xff)==rc );
64885   rc = sqlite3ApiExit(db, rc);
64886   sqlite3_mutex_leave(db->mutex);
64887   return rc;
64888 }
64889
64890 /*
64891 ** This function is invoked by the vdbe to call the xDestroy method
64892 ** of the virtual table named zTab in database iDb. This occurs
64893 ** when a DROP TABLE is mentioned.
64894 **
64895 ** This call is a no-op if zTab is not a virtual table.
64896 */
64897 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab)
64898 {
64899   int rc = SQLITE_OK;
64900   Table *pTab;
64901
64902   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
64903   assert(pTab);
64904   if( pTab->pVtab ){
64905     int (*xDestroy)(sqlite3_vtab *pVTab) = pTab->pMod->pModule->xDestroy;
64906     rc = sqlite3SafetyOff(db);
64907     assert( rc==SQLITE_OK );
64908     if( xDestroy ){
64909       rc = xDestroy(pTab->pVtab);
64910     }
64911     sqlite3SafetyOn(db);
64912     if( rc==SQLITE_OK ){
64913       pTab->pVtab = 0;
64914     }
64915   }
64916
64917   return rc;
64918 }
64919
64920 /*
64921 ** This function invokes either the xRollback or xCommit method
64922 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
64923 ** called is identified by the second argument, "offset", which is
64924 ** the offset of the method to call in the sqlite3_module structure.
64925 **
64926 ** The array is cleared after invoking the callbacks. 
64927 */
64928 static void callFinaliser(sqlite3 *db, int offset){
64929   int i;
64930   if( db->aVTrans ){
64931     for(i=0; i<db->nVTrans && db->aVTrans[i]; i++){
64932       sqlite3_vtab *pVtab = db->aVTrans[i];
64933       int (*x)(sqlite3_vtab *);
64934       x = *(int (**)(sqlite3_vtab *))((char *)pVtab->pModule + offset);
64935       if( x ) x(pVtab);
64936       sqlite3VtabUnlock(db, pVtab);
64937     }
64938     sqlite3_free(db->aVTrans);
64939     db->nVTrans = 0;
64940     db->aVTrans = 0;
64941   }
64942 }
64943
64944 /*
64945 ** If argument rc2 is not SQLITE_OK, then return it and do nothing. 
64946 ** Otherwise, invoke the xSync method of all virtual tables in the 
64947 ** sqlite3.aVTrans array. Return the error code for the first error 
64948 ** that occurs, or SQLITE_OK if all xSync operations are successful.
64949 */
64950 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, int rc2){
64951   int i;
64952   int rc = SQLITE_OK;
64953   int rcsafety;
64954   sqlite3_vtab **aVTrans = db->aVTrans;
64955   if( rc2!=SQLITE_OK ) return rc2;
64956
64957   rc = sqlite3SafetyOff(db);
64958   db->aVTrans = 0;
64959   for(i=0; rc==SQLITE_OK && i<db->nVTrans && aVTrans[i]; i++){
64960     sqlite3_vtab *pVtab = aVTrans[i];
64961     int (*x)(sqlite3_vtab *);
64962     x = pVtab->pModule->xSync;
64963     if( x ){
64964       rc = x(pVtab);
64965     }
64966   }
64967   db->aVTrans = aVTrans;
64968   rcsafety = sqlite3SafetyOn(db);
64969
64970   if( rc==SQLITE_OK ){
64971     rc = rcsafety;
64972   }
64973   return rc;
64974 }
64975
64976 /*
64977 ** Invoke the xRollback method of all virtual tables in the 
64978 ** sqlite3.aVTrans array. Then clear the array itself.
64979 */
64980 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
64981   callFinaliser(db, (int)(&((sqlite3_module *)0)->xRollback));
64982   return SQLITE_OK;
64983 }
64984
64985 /*
64986 ** Invoke the xCommit method of all virtual tables in the 
64987 ** sqlite3.aVTrans array. Then clear the array itself.
64988 */
64989 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
64990   callFinaliser(db, (int)(&((sqlite3_module *)0)->xCommit));
64991   return SQLITE_OK;
64992 }
64993
64994 /*
64995 ** If the virtual table pVtab supports the transaction interface
64996 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
64997 ** not currently open, invoke the xBegin method now.
64998 **
64999 ** If the xBegin call is successful, place the sqlite3_vtab pointer
65000 ** in the sqlite3.aVTrans array.
65001 */
65002 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, sqlite3_vtab *pVtab){
65003   int rc = SQLITE_OK;
65004   const sqlite3_module *pModule;
65005
65006   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
65007   ** than zero, then this function is being called from within a
65008   ** virtual module xSync() callback. It is illegal to write to 
65009   ** virtual module tables in this case, so return SQLITE_LOCKED.
65010   */
65011   if( 0==db->aVTrans && db->nVTrans>0 ){
65012     return SQLITE_LOCKED;
65013   }
65014   if( !pVtab ){
65015     return SQLITE_OK;
65016   } 
65017   pModule = pVtab->pModule;
65018
65019   if( pModule->xBegin ){
65020     int i;
65021
65022
65023     /* If pVtab is already in the aVTrans array, return early */
65024     for(i=0; (i<db->nVTrans) && 0!=db->aVTrans[i]; i++){
65025       if( db->aVTrans[i]==pVtab ){
65026         return SQLITE_OK;
65027       }
65028     }
65029
65030     /* Invoke the xBegin method */
65031     rc = pModule->xBegin(pVtab);
65032     if( rc!=SQLITE_OK ){
65033       return rc;
65034     }
65035
65036     rc = addToVTrans(db, pVtab);
65037   }
65038   return rc;
65039 }
65040
65041 /*
65042 ** The first parameter (pDef) is a function implementation.  The
65043 ** second parameter (pExpr) is the first argument to this function.
65044 ** If pExpr is a column in a virtual table, then let the virtual
65045 ** table implementation have an opportunity to overload the function.
65046 **
65047 ** This routine is used to allow virtual table implementations to
65048 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
65049 **
65050 ** Return either the pDef argument (indicating no change) or a 
65051 ** new FuncDef structure that is marked as ephemeral using the
65052 ** SQLITE_FUNC_EPHEM flag.
65053 */
65054 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
65055   sqlite3 *db,    /* Database connection for reporting malloc problems */
65056   FuncDef *pDef,  /* Function to possibly overload */
65057   int nArg,       /* Number of arguments to the function */
65058   Expr *pExpr     /* First argument to the function */
65059 ){
65060   Table *pTab;
65061   sqlite3_vtab *pVtab;
65062   sqlite3_module *pMod;
65063   void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
65064   void *pArg;
65065   FuncDef *pNew;
65066   int rc = 0;
65067   char *zLowerName;
65068   unsigned char *z;
65069
65070
65071   /* Check to see the left operand is a column in a virtual table */
65072   if( pExpr==0 ) return pDef;
65073   if( pExpr->op!=TK_COLUMN ) return pDef;
65074   pTab = pExpr->pTab;
65075   if( pTab==0 ) return pDef;
65076   if( !pTab->isVirtual ) return pDef;
65077   pVtab = pTab->pVtab;
65078   assert( pVtab!=0 );
65079   assert( pVtab->pModule!=0 );
65080   pMod = (sqlite3_module *)pVtab->pModule;
65081   if( pMod->xFindFunction==0 ) return pDef;
65082  
65083   /* Call the xFindFunction method on the virtual table implementation
65084   ** to see if the implementation wants to overload this function 
65085   */
65086   zLowerName = sqlite3DbStrDup(db, pDef->zName);
65087   if( zLowerName ){
65088     for(z=(unsigned char*)zLowerName; *z; z++){
65089       *z = sqlite3UpperToLower[*z];
65090     }
65091     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
65092     sqlite3_free(zLowerName);
65093   }
65094   if( rc==0 ){
65095     return pDef;
65096   }
65097
65098   /* Create a new ephemeral function definition for the overloaded
65099   ** function */
65100   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) + strlen(pDef->zName) );
65101   if( pNew==0 ){
65102     return pDef;
65103   }
65104   *pNew = *pDef;
65105   memcpy(pNew->zName, pDef->zName, strlen(pDef->zName)+1);
65106   pNew->xFunc = xFunc;
65107   pNew->pUserData = pArg;
65108   pNew->flags |= SQLITE_FUNC_EPHEM;
65109   return pNew;
65110 }
65111
65112 #endif /* SQLITE_OMIT_VIRTUALTABLE */
65113
65114 /************** End of vtab.c ************************************************/
65115 /************** Begin file where.c *******************************************/
65116 /*
65117 ** 2001 September 15
65118 **
65119 ** The author disclaims copyright to this source code.  In place of
65120 ** a legal notice, here is a blessing:
65121 **
65122 **    May you do good and not evil.
65123 **    May you find forgiveness for yourself and forgive others.
65124 **    May you share freely, never taking more than you give.
65125 **
65126 *************************************************************************
65127 ** This module contains C code that generates VDBE code used to process
65128 ** the WHERE clause of SQL statements.  This module is reponsible for
65129 ** generating the code that loops through a table looking for applicable
65130 ** rows.  Indices are selected and used to speed the search when doing
65131 ** so is applicable.  Because this module is responsible for selecting
65132 ** indices, you might also think of this module as the "query optimizer".
65133 **
65134 ** $Id: where.c,v 1.266 2007/12/12 17:42:53 danielk1977 Exp $
65135 */
65136
65137 /*
65138 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
65139 */
65140 #define BMS  (sizeof(Bitmask)*8)
65141
65142 /*
65143 ** Trace output macros
65144 */
65145 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
65146 SQLITE_API int sqlite3_where_trace = 0;
65147 # define WHERETRACE(X)  if(sqlite3_where_trace) sqlite3DebugPrintf X
65148 #else
65149 # define WHERETRACE(X)
65150 #endif
65151
65152 /* Forward reference
65153 */
65154 typedef struct WhereClause WhereClause;
65155 typedef struct ExprMaskSet ExprMaskSet;
65156
65157 /*
65158 ** The query generator uses an array of instances of this structure to
65159 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
65160 ** clause subexpression is separated from the others by an AND operator.
65161 **
65162 ** All WhereTerms are collected into a single WhereClause structure.  
65163 ** The following identity holds:
65164 **
65165 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
65166 **
65167 ** When a term is of the form:
65168 **
65169 **              X <op> <expr>
65170 **
65171 ** where X is a column name and <op> is one of certain operators,
65172 ** then WhereTerm.leftCursor and WhereTerm.leftColumn record the
65173 ** cursor number and column number for X.  WhereTerm.operator records
65174 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
65175 ** use of a bitmask encoding for the operator allows us to search
65176 ** quickly for terms that match any of several different operators.
65177 **
65178 ** prereqRight and prereqAll record sets of cursor numbers,
65179 ** but they do so indirectly.  A single ExprMaskSet structure translates
65180 ** cursor number into bits and the translated bit is stored in the prereq
65181 ** fields.  The translation is used in order to maximize the number of
65182 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
65183 ** spread out over the non-negative integers.  For example, the cursor
65184 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The ExprMaskSet
65185 ** translates these sparse cursor numbers into consecutive integers
65186 ** beginning with 0 in order to make the best possible use of the available
65187 ** bits in the Bitmask.  So, in the example above, the cursor numbers
65188 ** would be mapped into integers 0 through 7.
65189 */
65190 typedef struct WhereTerm WhereTerm;
65191 struct WhereTerm {
65192   Expr *pExpr;            /* Pointer to the subexpression */
65193   i16 iParent;            /* Disable pWC->a[iParent] when this term disabled */
65194   i16 leftCursor;         /* Cursor number of X in "X <op> <expr>" */
65195   i16 leftColumn;         /* Column number of X in "X <op> <expr>" */
65196   u16 eOperator;          /* A WO_xx value describing <op> */
65197   u8 flags;               /* Bit flags.  See below */
65198   u8 nChild;              /* Number of children that must disable us */
65199   WhereClause *pWC;       /* The clause this term is part of */
65200   Bitmask prereqRight;    /* Bitmask of tables used by pRight */
65201   Bitmask prereqAll;      /* Bitmask of tables referenced by p */
65202 };
65203
65204 /*
65205 ** Allowed values of WhereTerm.flags
65206 */
65207 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(pExpr) */
65208 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
65209 #define TERM_CODED      0x04   /* This term is already coded */
65210 #define TERM_COPIED     0x08   /* Has a child */
65211 #define TERM_OR_OK      0x10   /* Used during OR-clause processing */
65212
65213 /*
65214 ** An instance of the following structure holds all information about a
65215 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
65216 */
65217 struct WhereClause {
65218   Parse *pParse;           /* The parser context */
65219   ExprMaskSet *pMaskSet;   /* Mapping of table indices to bitmasks */
65220   int nTerm;               /* Number of terms */
65221   int nSlot;               /* Number of entries in a[] */
65222   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
65223   WhereTerm aStatic[10];   /* Initial static space for a[] */
65224 };
65225
65226 /*
65227 ** An instance of the following structure keeps track of a mapping
65228 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
65229 **
65230 ** The VDBE cursor numbers are small integers contained in 
65231 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
65232 ** clause, the cursor numbers might not begin with 0 and they might
65233 ** contain gaps in the numbering sequence.  But we want to make maximum
65234 ** use of the bits in our bitmasks.  This structure provides a mapping
65235 ** from the sparse cursor numbers into consecutive integers beginning
65236 ** with 0.
65237 **
65238 ** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
65239 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
65240 **
65241 ** For example, if the WHERE clause expression used these VDBE
65242 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  ExprMaskSet structure
65243 ** would map those cursor numbers into bits 0 through 5.
65244 **
65245 ** Note that the mapping is not necessarily ordered.  In the example
65246 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
65247 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
65248 ** does not really matter.  What is important is that sparse cursor
65249 ** numbers all get mapped into bit numbers that begin with 0 and contain
65250 ** no gaps.
65251 */
65252 struct ExprMaskSet {
65253   int n;                        /* Number of assigned cursor values */
65254   int ix[sizeof(Bitmask)*8];    /* Cursor assigned to each bit */
65255 };
65256
65257
65258 /*
65259 ** Bitmasks for the operators that indices are able to exploit.  An
65260 ** OR-ed combination of these values can be used when searching for
65261 ** terms in the where clause.
65262 */
65263 #define WO_IN     1
65264 #define WO_EQ     2
65265 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
65266 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
65267 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
65268 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
65269 #define WO_MATCH  64
65270 #define WO_ISNULL 128
65271
65272 /*
65273 ** Value for flags returned by bestIndex().  
65274 **
65275 ** The least significant byte is reserved as a mask for WO_ values above.
65276 ** The WhereLevel.flags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
65277 ** But if the table is the right table of a left join, WhereLevel.flags
65278 ** is set to WO_IN|WO_EQ.  The WhereLevel.flags field can then be used as
65279 ** the "op" parameter to findTerm when we are resolving equality constraints.
65280 ** ISNULL constraints will then not be used on the right table of a left
65281 ** join.  Tickets #2177 and #2189.
65282 */
65283 #define WHERE_ROWID_EQ     0x000100   /* rowid=EXPR or rowid IN (...) */
65284 #define WHERE_ROWID_RANGE  0x000200   /* rowid<EXPR and/or rowid>EXPR */
65285 #define WHERE_COLUMN_EQ    0x001000   /* x=EXPR or x IN (...) */
65286 #define WHERE_COLUMN_RANGE 0x002000   /* x<EXPR and/or x>EXPR */
65287 #define WHERE_COLUMN_IN    0x004000   /* x IN (...) */
65288 #define WHERE_TOP_LIMIT    0x010000   /* x<EXPR or x<=EXPR constraint */
65289 #define WHERE_BTM_LIMIT    0x020000   /* x>EXPR or x>=EXPR constraint */
65290 #define WHERE_IDX_ONLY     0x080000   /* Use index only - omit table */
65291 #define WHERE_ORDERBY      0x100000   /* Output will appear in correct order */
65292 #define WHERE_REVERSE      0x200000   /* Scan in reverse order */
65293 #define WHERE_UNIQUE       0x400000   /* Selects no more than one row */
65294 #define WHERE_VIRTUALTABLE 0x800000   /* Use virtual-table processing */
65295
65296 /*
65297 ** Initialize a preallocated WhereClause structure.
65298 */
65299 static void whereClauseInit(
65300   WhereClause *pWC,        /* The WhereClause to be initialized */
65301   Parse *pParse,           /* The parsing context */
65302   ExprMaskSet *pMaskSet    /* Mapping from table indices to bitmasks */
65303 ){
65304   pWC->pParse = pParse;
65305   pWC->pMaskSet = pMaskSet;
65306   pWC->nTerm = 0;
65307   pWC->nSlot = ArraySize(pWC->aStatic);
65308   pWC->a = pWC->aStatic;
65309 }
65310
65311 /*
65312 ** Deallocate a WhereClause structure.  The WhereClause structure
65313 ** itself is not freed.  This routine is the inverse of whereClauseInit().
65314 */
65315 static void whereClauseClear(WhereClause *pWC){
65316   int i;
65317   WhereTerm *a;
65318   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
65319     if( a->flags & TERM_DYNAMIC ){
65320       sqlite3ExprDelete(a->pExpr);
65321     }
65322   }
65323   if( pWC->a!=pWC->aStatic ){
65324     sqlite3_free(pWC->a);
65325   }
65326 }
65327
65328 /*
65329 ** Add a new entries to the WhereClause structure.  Increase the allocated
65330 ** space as necessary.
65331 **
65332 ** If the flags argument includes TERM_DYNAMIC, then responsibility
65333 ** for freeing the expression p is assumed by the WhereClause object.
65334 **
65335 ** WARNING:  This routine might reallocate the space used to store
65336 ** WhereTerms.  All pointers to WhereTerms should be invalided after
65337 ** calling this routine.  Such pointers may be reinitialized by referencing
65338 ** the pWC->a[] array.
65339 */
65340 static int whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
65341   WhereTerm *pTerm;
65342   int idx;
65343   if( pWC->nTerm>=pWC->nSlot ){
65344     WhereTerm *pOld = pWC->a;
65345     pWC->a = sqlite3_malloc( sizeof(pWC->a[0])*pWC->nSlot*2 );
65346     if( pWC->a==0 ){
65347       pWC->pParse->db->mallocFailed = 1;
65348       if( flags & TERM_DYNAMIC ){
65349         sqlite3ExprDelete(p);
65350       }
65351       pWC->a = pOld;
65352       return 0;
65353     }
65354     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
65355     if( pOld!=pWC->aStatic ){
65356       sqlite3_free(pOld);
65357     }
65358     pWC->nSlot *= 2;
65359   }
65360   pTerm = &pWC->a[idx = pWC->nTerm];
65361   pWC->nTerm++;
65362   pTerm->pExpr = p;
65363   pTerm->flags = flags;
65364   pTerm->pWC = pWC;
65365   pTerm->iParent = -1;
65366   return idx;
65367 }
65368
65369 /*
65370 ** This routine identifies subexpressions in the WHERE clause where
65371 ** each subexpression is separated by the AND operator or some other
65372 ** operator specified in the op parameter.  The WhereClause structure
65373 ** is filled with pointers to subexpressions.  For example:
65374 **
65375 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
65376 **           \________/     \_______________/     \________________/
65377 **            slot[0]            slot[1]               slot[2]
65378 **
65379 ** The original WHERE clause in pExpr is unaltered.  All this routine
65380 ** does is make slot[] entries point to substructure within pExpr.
65381 **
65382 ** In the previous sentence and in the diagram, "slot[]" refers to
65383 ** the WhereClause.a[] array.  This array grows as needed to contain
65384 ** all terms of the WHERE clause.
65385 */
65386 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
65387   if( pExpr==0 ) return;
65388   if( pExpr->op!=op ){
65389     whereClauseInsert(pWC, pExpr, 0);
65390   }else{
65391     whereSplit(pWC, pExpr->pLeft, op);
65392     whereSplit(pWC, pExpr->pRight, op);
65393   }
65394 }
65395
65396 /*
65397 ** Initialize an expression mask set
65398 */
65399 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
65400
65401 /*
65402 ** Return the bitmask for the given cursor number.  Return 0 if
65403 ** iCursor is not in the set.
65404 */
65405 static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
65406   int i;
65407   for(i=0; i<pMaskSet->n; i++){
65408     if( pMaskSet->ix[i]==iCursor ){
65409       return ((Bitmask)1)<<i;
65410     }
65411   }
65412   return 0;
65413 }
65414
65415 /*
65416 ** Create a new mask for cursor iCursor.
65417 **
65418 ** There is one cursor per table in the FROM clause.  The number of
65419 ** tables in the FROM clause is limited by a test early in the
65420 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
65421 ** array will never overflow.
65422 */
65423 static void createMask(ExprMaskSet *pMaskSet, int iCursor){
65424   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
65425   pMaskSet->ix[pMaskSet->n++] = iCursor;
65426 }
65427
65428 /*
65429 ** This routine walks (recursively) an expression tree and generates
65430 ** a bitmask indicating which tables are used in that expression
65431 ** tree.
65432 **
65433 ** In order for this routine to work, the calling function must have
65434 ** previously invoked sqlite3ExprResolveNames() on the expression.  See
65435 ** the header comment on that routine for additional information.
65436 ** The sqlite3ExprResolveNames() routines looks for column names and
65437 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
65438 ** the VDBE cursor number of the table.  This routine just has to
65439 ** translate the cursor numbers into bitmask values and OR all
65440 ** the bitmasks together.
65441 */
65442 static Bitmask exprListTableUsage(ExprMaskSet*, ExprList*);
65443 static Bitmask exprSelectTableUsage(ExprMaskSet*, Select*);
65444 static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
65445   Bitmask mask = 0;
65446   if( p==0 ) return 0;
65447   if( p->op==TK_COLUMN ){
65448     mask = getMask(pMaskSet, p->iTable);
65449     return mask;
65450   }
65451   mask = exprTableUsage(pMaskSet, p->pRight);
65452   mask |= exprTableUsage(pMaskSet, p->pLeft);
65453   mask |= exprListTableUsage(pMaskSet, p->pList);
65454   mask |= exprSelectTableUsage(pMaskSet, p->pSelect);
65455   return mask;
65456 }
65457 static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
65458   int i;
65459   Bitmask mask = 0;
65460   if( pList ){
65461     for(i=0; i<pList->nExpr; i++){
65462       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
65463     }
65464   }
65465   return mask;
65466 }
65467 static Bitmask exprSelectTableUsage(ExprMaskSet *pMaskSet, Select *pS){
65468   Bitmask mask = 0;
65469   while( pS ){
65470     mask |= exprListTableUsage(pMaskSet, pS->pEList);
65471     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
65472     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
65473     mask |= exprTableUsage(pMaskSet, pS->pWhere);
65474     mask |= exprTableUsage(pMaskSet, pS->pHaving);
65475     pS = pS->pPrior;
65476   }
65477   return mask;
65478 }
65479
65480 /*
65481 ** Return TRUE if the given operator is one of the operators that is
65482 ** allowed for an indexable WHERE clause term.  The allowed operators are
65483 ** "=", "<", ">", "<=", ">=", and "IN".
65484 */
65485 static int allowedOp(int op){
65486   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
65487   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
65488   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
65489   assert( TK_GE==TK_EQ+4 );
65490   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
65491 }
65492
65493 /*
65494 ** Swap two objects of type T.
65495 */
65496 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
65497
65498 /*
65499 ** Commute a comparision operator.  Expressions of the form "X op Y"
65500 ** are converted into "Y op X".
65501 **
65502 ** If a collation sequence is associated with either the left or right
65503 ** side of the comparison, it remains associated with the same side after
65504 ** the commutation. So "Y collate NOCASE op X" becomes 
65505 ** "X collate NOCASE op Y". This is because any collation sequence on
65506 ** the left hand side of a comparison overrides any collation sequence 
65507 ** attached to the right. For the same reason the EP_ExpCollate flag
65508 ** is not commuted.
65509 */
65510 static void exprCommute(Expr *pExpr){
65511   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
65512   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
65513   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
65514   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
65515   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
65516   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
65517   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
65518   if( pExpr->op>=TK_GT ){
65519     assert( TK_LT==TK_GT+2 );
65520     assert( TK_GE==TK_LE+2 );
65521     assert( TK_GT>TK_EQ );
65522     assert( TK_GT<TK_LE );
65523     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
65524     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
65525   }
65526 }
65527
65528 /*
65529 ** Translate from TK_xx operator to WO_xx bitmask.
65530 */
65531 static int operatorMask(int op){
65532   int c;
65533   assert( allowedOp(op) );
65534   if( op==TK_IN ){
65535     c = WO_IN;
65536   }else if( op==TK_ISNULL ){
65537     c = WO_ISNULL;
65538   }else{
65539     c = WO_EQ<<(op-TK_EQ);
65540   }
65541   assert( op!=TK_ISNULL || c==WO_ISNULL );
65542   assert( op!=TK_IN || c==WO_IN );
65543   assert( op!=TK_EQ || c==WO_EQ );
65544   assert( op!=TK_LT || c==WO_LT );
65545   assert( op!=TK_LE || c==WO_LE );
65546   assert( op!=TK_GT || c==WO_GT );
65547   assert( op!=TK_GE || c==WO_GE );
65548   return c;
65549 }
65550
65551 /*
65552 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
65553 ** where X is a reference to the iColumn of table iCur and <op> is one of
65554 ** the WO_xx operator codes specified by the op parameter.
65555 ** Return a pointer to the term.  Return 0 if not found.
65556 */
65557 static WhereTerm *findTerm(
65558   WhereClause *pWC,     /* The WHERE clause to be searched */
65559   int iCur,             /* Cursor number of LHS */
65560   int iColumn,          /* Column number of LHS */
65561   Bitmask notReady,     /* RHS must not overlap with this mask */
65562   u16 op,               /* Mask of WO_xx values describing operator */
65563   Index *pIdx           /* Must be compatible with this index, if not NULL */
65564 ){
65565   WhereTerm *pTerm;
65566   int k;
65567   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
65568     if( pTerm->leftCursor==iCur
65569        && (pTerm->prereqRight & notReady)==0
65570        && pTerm->leftColumn==iColumn
65571        && (pTerm->eOperator & op)!=0
65572     ){
65573       if( iCur>=0 && pIdx && pTerm->eOperator!=WO_ISNULL ){
65574         Expr *pX = pTerm->pExpr;
65575         CollSeq *pColl;
65576         char idxaff;
65577         int j;
65578         Parse *pParse = pWC->pParse;
65579
65580         idxaff = pIdx->pTable->aCol[iColumn].affinity;
65581         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
65582
65583         /* Figure out the collation sequence required from an index for
65584         ** it to be useful for optimising expression pX. Store this
65585         ** value in variable pColl.
65586         */
65587         assert(pX->pLeft);
65588         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
65589         if( !pColl ){
65590           pColl = pParse->db->pDfltColl;
65591         }
65592
65593         for(j=0; j<pIdx->nColumn && pIdx->aiColumn[j]!=iColumn; j++){}
65594         assert( j<pIdx->nColumn );
65595         if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
65596       }
65597       return pTerm;
65598     }
65599   }
65600   return 0;
65601 }
65602
65603 /* Forward reference */
65604 static void exprAnalyze(SrcList*, WhereClause*, int);
65605
65606 /*
65607 ** Call exprAnalyze on all terms in a WHERE clause.  
65608 **
65609 **
65610 */
65611 static void exprAnalyzeAll(
65612   SrcList *pTabList,       /* the FROM clause */
65613   WhereClause *pWC         /* the WHERE clause to be analyzed */
65614 ){
65615   int i;
65616   for(i=pWC->nTerm-1; i>=0; i--){
65617     exprAnalyze(pTabList, pWC, i);
65618   }
65619 }
65620
65621 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
65622 /*
65623 ** Check to see if the given expression is a LIKE or GLOB operator that
65624 ** can be optimized using inequality constraints.  Return TRUE if it is
65625 ** so and false if not.
65626 **
65627 ** In order for the operator to be optimizible, the RHS must be a string
65628 ** literal that does not begin with a wildcard.  
65629 */
65630 static int isLikeOrGlob(
65631   sqlite3 *db,      /* The database */
65632   Expr *pExpr,      /* Test this expression */
65633   int *pnPattern,   /* Number of non-wildcard prefix characters */
65634   int *pisComplete  /* True if the only wildcard is % in the last character */
65635 ){
65636   const char *z;
65637   Expr *pRight, *pLeft;
65638   ExprList *pList;
65639   int c, cnt;
65640   int noCase;
65641   char wc[3];
65642   CollSeq *pColl;
65643
65644   if( !sqlite3IsLikeFunction(db, pExpr, &noCase, wc) ){
65645     return 0;
65646   }
65647   pList = pExpr->pList;
65648   pRight = pList->a[0].pExpr;
65649   if( pRight->op!=TK_STRING ){
65650     return 0;
65651   }
65652   pLeft = pList->a[1].pExpr;
65653   if( pLeft->op!=TK_COLUMN ){
65654     return 0;
65655   }
65656   pColl = pLeft->pColl;
65657   if( pColl==0 ){
65658     /* TODO: Coverage testing doesn't get this case. Is it actually possible
65659     ** for an expression of type TK_COLUMN to not have an assigned collation 
65660     ** sequence at this point?
65661     */
65662     pColl = db->pDfltColl;
65663   }
65664   if( (pColl->type!=SQLITE_COLL_BINARY || noCase) &&
65665       (pColl->type!=SQLITE_COLL_NOCASE || !noCase) ){
65666     return 0;
65667   }
65668   sqlite3DequoteExpr(db, pRight);
65669   z = (char *)pRight->token.z;
65670   cnt = 0;
65671   if( z ){
65672     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ cnt++; }
65673   }
65674   if( cnt==0 || 255==(u8)z[cnt] ){
65675     return 0;
65676   }
65677   *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
65678   *pnPattern = cnt;
65679   return 1;
65680 }
65681 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
65682
65683
65684 #ifndef SQLITE_OMIT_VIRTUALTABLE
65685 /*
65686 ** Check to see if the given expression is of the form
65687 **
65688 **         column MATCH expr
65689 **
65690 ** If it is then return TRUE.  If not, return FALSE.
65691 */
65692 static int isMatchOfColumn(
65693   Expr *pExpr      /* Test this expression */
65694 ){
65695   ExprList *pList;
65696
65697   if( pExpr->op!=TK_FUNCTION ){
65698     return 0;
65699   }
65700   if( pExpr->token.n!=5 ||
65701        sqlite3StrNICmp((const char*)pExpr->token.z,"match",5)!=0 ){
65702     return 0;
65703   }
65704   pList = pExpr->pList;
65705   if( pList->nExpr!=2 ){
65706     return 0;
65707   }
65708   if( pList->a[1].pExpr->op != TK_COLUMN ){
65709     return 0;
65710   }
65711   return 1;
65712 }
65713 #endif /* SQLITE_OMIT_VIRTUALTABLE */
65714
65715 /*
65716 ** If the pBase expression originated in the ON or USING clause of
65717 ** a join, then transfer the appropriate markings over to derived.
65718 */
65719 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
65720   pDerived->flags |= pBase->flags & EP_FromJoin;
65721   pDerived->iRightJoinTable = pBase->iRightJoinTable;
65722 }
65723
65724 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
65725 /*
65726 ** Return TRUE if the given term of an OR clause can be converted
65727 ** into an IN clause.  The iCursor and iColumn define the left-hand
65728 ** side of the IN clause.
65729 **
65730 ** The context is that we have multiple OR-connected equality terms
65731 ** like this:
65732 **
65733 **           a=<expr1> OR  a=<expr2> OR b=<expr3>  OR ...
65734 **
65735 ** The pOrTerm input to this routine corresponds to a single term of
65736 ** this OR clause.  In order for the term to be a condidate for
65737 ** conversion to an IN operator, the following must be true:
65738 **
65739 **     *  The left-hand side of the term must be the column which
65740 **        is identified by iCursor and iColumn.
65741 **
65742 **     *  If the right-hand side is also a column, then the affinities
65743 **        of both right and left sides must be such that no type
65744 **        conversions are required on the right.  (Ticket #2249)
65745 **
65746 ** If both of these conditions are true, then return true.  Otherwise
65747 ** return false.
65748 */
65749 static int orTermIsOptCandidate(WhereTerm *pOrTerm, int iCursor, int iColumn){
65750   int affLeft, affRight;
65751   assert( pOrTerm->eOperator==WO_EQ );
65752   if( pOrTerm->leftCursor!=iCursor ){
65753     return 0;
65754   }
65755   if( pOrTerm->leftColumn!=iColumn ){
65756     return 0;
65757   }
65758   affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
65759   if( affRight==0 ){
65760     return 1;
65761   }
65762   affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
65763   if( affRight!=affLeft ){
65764     return 0;
65765   }
65766   return 1;
65767 }
65768
65769 /*
65770 ** Return true if the given term of an OR clause can be ignored during
65771 ** a check to make sure all OR terms are candidates for optimization.
65772 ** In other words, return true if a call to the orTermIsOptCandidate()
65773 ** above returned false but it is not necessary to disqualify the
65774 ** optimization.
65775 **
65776 ** Suppose the original OR phrase was this:
65777 **
65778 **           a=4  OR  a=11  OR  a=b
65779 **
65780 ** During analysis, the third term gets flipped around and duplicate
65781 ** so that we are left with this:
65782 **
65783 **           a=4  OR  a=11  OR  a=b  OR  b=a
65784 **
65785 ** Since the last two terms are duplicates, only one of them
65786 ** has to qualify in order for the whole phrase to qualify.  When
65787 ** this routine is called, we know that pOrTerm did not qualify.
65788 ** This routine merely checks to see if pOrTerm has a duplicate that
65789 ** might qualify.  If there is a duplicate that has not yet been
65790 ** disqualified, then return true.  If there are no duplicates, or
65791 ** the duplicate has also been disqualifed, return false.
65792 */
65793 static int orTermHasOkDuplicate(WhereClause *pOr, WhereTerm *pOrTerm){
65794   if( pOrTerm->flags & TERM_COPIED ){
65795     /* This is the original term.  The duplicate is to the left had
65796     ** has not yet been analyzed and thus has not yet been disqualified. */
65797     return 1;
65798   }
65799   if( (pOrTerm->flags & TERM_VIRTUAL)!=0
65800      && (pOr->a[pOrTerm->iParent].flags & TERM_OR_OK)!=0 ){
65801     /* This is a duplicate term.  The original qualified so this one
65802     ** does not have to. */
65803     return 1;
65804   }
65805   /* This is either a singleton term or else it is a duplicate for
65806   ** which the original did not qualify.  Either way we are done for. */
65807   return 0;
65808 }
65809 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
65810
65811 /*
65812 ** The input to this routine is an WhereTerm structure with only the
65813 ** "pExpr" field filled in.  The job of this routine is to analyze the
65814 ** subexpression and populate all the other fields of the WhereTerm
65815 ** structure.
65816 **
65817 ** If the expression is of the form "<expr> <op> X" it gets commuted
65818 ** to the standard form of "X <op> <expr>".  If the expression is of
65819 ** the form "X <op> Y" where both X and Y are columns, then the original
65820 ** expression is unchanged and a new virtual expression of the form
65821 ** "Y <op> X" is added to the WHERE clause and analyzed separately.
65822 */
65823 static void exprAnalyze(
65824   SrcList *pSrc,            /* the FROM clause */
65825   WhereClause *pWC,         /* the WHERE clause */
65826   int idxTerm               /* Index of the term to be analyzed */
65827 ){
65828   WhereTerm *pTerm;
65829   ExprMaskSet *pMaskSet;
65830   Expr *pExpr;
65831   Bitmask prereqLeft;
65832   Bitmask prereqAll;
65833   int nPattern;
65834   int isComplete;
65835   int op;
65836   Parse *pParse = pWC->pParse;
65837   sqlite3 *db = pParse->db;
65838
65839   if( db->mallocFailed ){
65840     return;
65841   }
65842   pTerm = &pWC->a[idxTerm];
65843   pMaskSet = pWC->pMaskSet;
65844   pExpr = pTerm->pExpr;
65845   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
65846   op = pExpr->op;
65847   if( op==TK_IN ){
65848     assert( pExpr->pRight==0 );
65849     pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->pList)
65850                           | exprSelectTableUsage(pMaskSet, pExpr->pSelect);
65851   }else if( op==TK_ISNULL ){
65852     pTerm->prereqRight = 0;
65853   }else{
65854     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
65855   }
65856   prereqAll = exprTableUsage(pMaskSet, pExpr);
65857   if( ExprHasProperty(pExpr, EP_FromJoin) ){
65858     prereqAll |= getMask(pMaskSet, pExpr->iRightJoinTable);
65859   }
65860   pTerm->prereqAll = prereqAll;
65861   pTerm->leftCursor = -1;
65862   pTerm->iParent = -1;
65863   pTerm->eOperator = 0;
65864   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
65865     Expr *pLeft = pExpr->pLeft;
65866     Expr *pRight = pExpr->pRight;
65867     if( pLeft->op==TK_COLUMN ){
65868       pTerm->leftCursor = pLeft->iTable;
65869       pTerm->leftColumn = pLeft->iColumn;
65870       pTerm->eOperator = operatorMask(op);
65871     }
65872     if( pRight && pRight->op==TK_COLUMN ){
65873       WhereTerm *pNew;
65874       Expr *pDup;
65875       if( pTerm->leftCursor>=0 ){
65876         int idxNew;
65877         pDup = sqlite3ExprDup(db, pExpr);
65878         if( db->mallocFailed ){
65879           sqlite3ExprDelete(pDup);
65880           return;
65881         }
65882         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
65883         if( idxNew==0 ) return;
65884         pNew = &pWC->a[idxNew];
65885         pNew->iParent = idxTerm;
65886         pTerm = &pWC->a[idxTerm];
65887         pTerm->nChild = 1;
65888         pTerm->flags |= TERM_COPIED;
65889       }else{
65890         pDup = pExpr;
65891         pNew = pTerm;
65892       }
65893       exprCommute(pDup);
65894       pLeft = pDup->pLeft;
65895       pNew->leftCursor = pLeft->iTable;
65896       pNew->leftColumn = pLeft->iColumn;
65897       pNew->prereqRight = prereqLeft;
65898       pNew->prereqAll = prereqAll;
65899       pNew->eOperator = operatorMask(pDup->op);
65900     }
65901   }
65902
65903 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
65904   /* If a term is the BETWEEN operator, create two new virtual terms
65905   ** that define the range that the BETWEEN implements.
65906   */
65907   else if( pExpr->op==TK_BETWEEN ){
65908     ExprList *pList = pExpr->pList;
65909     int i;
65910     static const u8 ops[] = {TK_GE, TK_LE};
65911     assert( pList!=0 );
65912     assert( pList->nExpr==2 );
65913     for(i=0; i<2; i++){
65914       Expr *pNewExpr;
65915       int idxNew;
65916       pNewExpr = sqlite3Expr(db, ops[i], sqlite3ExprDup(db, pExpr->pLeft),
65917                              sqlite3ExprDup(db, pList->a[i].pExpr), 0);
65918       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
65919       exprAnalyze(pSrc, pWC, idxNew);
65920       pTerm = &pWC->a[idxTerm];
65921       pWC->a[idxNew].iParent = idxTerm;
65922     }
65923     pTerm->nChild = 2;
65924   }
65925 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
65926
65927 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
65928   /* Attempt to convert OR-connected terms into an IN operator so that
65929   ** they can make use of indices.  Example:
65930   **
65931   **      x = expr1  OR  expr2 = x  OR  x = expr3
65932   **
65933   ** is converted into
65934   **
65935   **      x IN (expr1,expr2,expr3)
65936   **
65937   ** This optimization must be omitted if OMIT_SUBQUERY is defined because
65938   ** the compiler for the the IN operator is part of sub-queries.
65939   */
65940   else if( pExpr->op==TK_OR ){
65941     int ok;
65942     int i, j;
65943     int iColumn, iCursor;
65944     WhereClause sOr;
65945     WhereTerm *pOrTerm;
65946
65947     assert( (pTerm->flags & TERM_DYNAMIC)==0 );
65948     whereClauseInit(&sOr, pWC->pParse, pMaskSet);
65949     whereSplit(&sOr, pExpr, TK_OR);
65950     exprAnalyzeAll(pSrc, &sOr);
65951     assert( sOr.nTerm>=2 );
65952     j = 0;
65953     do{
65954       assert( j<sOr.nTerm );
65955       iColumn = sOr.a[j].leftColumn;
65956       iCursor = sOr.a[j].leftCursor;
65957       ok = iCursor>=0;
65958       for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
65959         if( pOrTerm->eOperator!=WO_EQ ){
65960           goto or_not_possible;
65961         }
65962         if( orTermIsOptCandidate(pOrTerm, iCursor, iColumn) ){
65963           pOrTerm->flags |= TERM_OR_OK;
65964         }else if( orTermHasOkDuplicate(&sOr, pOrTerm) ){
65965           pOrTerm->flags &= ~TERM_OR_OK;
65966         }else{
65967           ok = 0;
65968         }
65969       }
65970     }while( !ok && (sOr.a[j++].flags & TERM_COPIED)!=0 && j<2 );
65971     if( ok ){
65972       ExprList *pList = 0;
65973       Expr *pNew, *pDup;
65974       Expr *pLeft = 0;
65975       for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
65976         if( (pOrTerm->flags & TERM_OR_OK)==0 ) continue;
65977         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight);
65978         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup, 0);
65979         pLeft = pOrTerm->pExpr->pLeft;
65980       }
65981       assert( pLeft!=0 );
65982       pDup = sqlite3ExprDup(db, pLeft);
65983       pNew = sqlite3Expr(db, TK_IN, pDup, 0, 0);
65984       if( pNew ){
65985         int idxNew;
65986         transferJoinMarkings(pNew, pExpr);
65987         pNew->pList = pList;
65988         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
65989         exprAnalyze(pSrc, pWC, idxNew);
65990         pTerm = &pWC->a[idxTerm];
65991         pWC->a[idxNew].iParent = idxTerm;
65992         pTerm->nChild = 1;
65993       }else{
65994         sqlite3ExprListDelete(pList);
65995       }
65996     }
65997 or_not_possible:
65998     whereClauseClear(&sOr);
65999   }
66000 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
66001
66002 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
66003   /* Add constraints to reduce the search space on a LIKE or GLOB
66004   ** operator.
66005   */
66006   if( isLikeOrGlob(db, pExpr, &nPattern, &isComplete) ){
66007     Expr *pLeft, *pRight;
66008     Expr *pStr1, *pStr2;
66009     Expr *pNewExpr1, *pNewExpr2;
66010     int idxNew1, idxNew2;
66011
66012     pLeft = pExpr->pList->a[1].pExpr;
66013     pRight = pExpr->pList->a[0].pExpr;
66014     pStr1 = sqlite3PExpr(pParse, TK_STRING, 0, 0, 0);
66015     if( pStr1 ){
66016       sqlite3TokenCopy(db, &pStr1->token, &pRight->token);
66017       pStr1->token.n = nPattern;
66018       pStr1->flags = EP_Dequoted;
66019     }
66020     pStr2 = sqlite3ExprDup(db, pStr1);
66021     if( !db->mallocFailed ){
66022       assert( pStr2->token.dyn );
66023       ++*(u8*)&pStr2->token.z[nPattern-1];
66024     }
66025     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft), pStr1, 0);
66026     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
66027     exprAnalyze(pSrc, pWC, idxNew1);
66028     pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft), pStr2, 0);
66029     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
66030     exprAnalyze(pSrc, pWC, idxNew2);
66031     pTerm = &pWC->a[idxTerm];
66032     if( isComplete ){
66033       pWC->a[idxNew1].iParent = idxTerm;
66034       pWC->a[idxNew2].iParent = idxTerm;
66035       pTerm->nChild = 2;
66036     }
66037   }
66038 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
66039
66040 #ifndef SQLITE_OMIT_VIRTUALTABLE
66041   /* Add a WO_MATCH auxiliary term to the constraint set if the
66042   ** current expression is of the form:  column MATCH expr.
66043   ** This information is used by the xBestIndex methods of
66044   ** virtual tables.  The native query optimizer does not attempt
66045   ** to do anything with MATCH functions.
66046   */
66047   if( isMatchOfColumn(pExpr) ){
66048     int idxNew;
66049     Expr *pRight, *pLeft;
66050     WhereTerm *pNewTerm;
66051     Bitmask prereqColumn, prereqExpr;
66052
66053     pRight = pExpr->pList->a[0].pExpr;
66054     pLeft = pExpr->pList->a[1].pExpr;
66055     prereqExpr = exprTableUsage(pMaskSet, pRight);
66056     prereqColumn = exprTableUsage(pMaskSet, pLeft);
66057     if( (prereqExpr & prereqColumn)==0 ){
66058       Expr *pNewExpr;
66059       pNewExpr = sqlite3Expr(db, TK_MATCH, 0, sqlite3ExprDup(db, pRight), 0);
66060       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
66061       pNewTerm = &pWC->a[idxNew];
66062       pNewTerm->prereqRight = prereqExpr;
66063       pNewTerm->leftCursor = pLeft->iTable;
66064       pNewTerm->leftColumn = pLeft->iColumn;
66065       pNewTerm->eOperator = WO_MATCH;
66066       pNewTerm->iParent = idxTerm;
66067       pTerm = &pWC->a[idxTerm];
66068       pTerm->nChild = 1;
66069       pTerm->flags |= TERM_COPIED;
66070       pNewTerm->prereqAll = pTerm->prereqAll;
66071     }
66072   }
66073 #endif /* SQLITE_OMIT_VIRTUALTABLE */
66074 }
66075
66076 /*
66077 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
66078 ** a reference to any table other than the iBase table.
66079 */
66080 static int referencesOtherTables(
66081   ExprList *pList,          /* Search expressions in ths list */
66082   ExprMaskSet *pMaskSet,    /* Mapping from tables to bitmaps */
66083   int iFirst,               /* Be searching with the iFirst-th expression */
66084   int iBase                 /* Ignore references to this table */
66085 ){
66086   Bitmask allowed = ~getMask(pMaskSet, iBase);
66087   while( iFirst<pList->nExpr ){
66088     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
66089       return 1;
66090     }
66091   }
66092   return 0;
66093 }
66094
66095
66096 /*
66097 ** This routine decides if pIdx can be used to satisfy the ORDER BY
66098 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
66099 ** ORDER BY clause, this routine returns 0.
66100 **
66101 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
66102 ** left-most table in the FROM clause of that same SELECT statement and
66103 ** the table has a cursor number of "base".  pIdx is an index on pTab.
66104 **
66105 ** nEqCol is the number of columns of pIdx that are used as equality
66106 ** constraints.  Any of these columns may be missing from the ORDER BY
66107 ** clause and the match can still be a success.
66108 **
66109 ** All terms of the ORDER BY that match against the index must be either
66110 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
66111 ** index do not need to satisfy this constraint.)  The *pbRev value is
66112 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
66113 ** the ORDER BY clause is all ASC.
66114 */
66115 static int isSortingIndex(
66116   Parse *pParse,          /* Parsing context */
66117   ExprMaskSet *pMaskSet,  /* Mapping from table indices to bitmaps */
66118   Index *pIdx,            /* The index we are testing */
66119   int base,               /* Cursor number for the table to be sorted */
66120   ExprList *pOrderBy,     /* The ORDER BY clause */
66121   int nEqCol,             /* Number of index columns with == constraints */
66122   int *pbRev              /* Set to 1 if ORDER BY is DESC */
66123 ){
66124   int i, j;                       /* Loop counters */
66125   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
66126   int nTerm;                      /* Number of ORDER BY terms */
66127   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
66128   sqlite3 *db = pParse->db;
66129
66130   assert( pOrderBy!=0 );
66131   nTerm = pOrderBy->nExpr;
66132   assert( nTerm>0 );
66133
66134   /* Match terms of the ORDER BY clause against columns of
66135   ** the index.
66136   **
66137   ** Note that indices have pIdx->nColumn regular columns plus
66138   ** one additional column containing the rowid.  The rowid column
66139   ** of the index is also allowed to match against the ORDER BY
66140   ** clause.
66141   */
66142   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
66143     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
66144     CollSeq *pColl;    /* The collating sequence of pExpr */
66145     int termSortOrder; /* Sort order for this term */
66146     int iColumn;       /* The i-th column of the index.  -1 for rowid */
66147     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
66148     const char *zColl; /* Name of the collating sequence for i-th index term */
66149
66150     pExpr = pTerm->pExpr;
66151     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
66152       /* Can not use an index sort on anything that is not a column in the
66153       ** left-most table of the FROM clause */
66154       break;
66155     }
66156     pColl = sqlite3ExprCollSeq(pParse, pExpr);
66157     if( !pColl ){
66158       pColl = db->pDfltColl;
66159     }
66160     if( i<pIdx->nColumn ){
66161       iColumn = pIdx->aiColumn[i];
66162       if( iColumn==pIdx->pTable->iPKey ){
66163         iColumn = -1;
66164       }
66165       iSortOrder = pIdx->aSortOrder[i];
66166       zColl = pIdx->azColl[i];
66167     }else{
66168       iColumn = -1;
66169       iSortOrder = 0;
66170       zColl = pColl->zName;
66171     }
66172     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
66173       /* Term j of the ORDER BY clause does not match column i of the index */
66174       if( i<nEqCol ){
66175         /* If an index column that is constrained by == fails to match an
66176         ** ORDER BY term, that is OK.  Just ignore that column of the index
66177         */
66178         continue;
66179       }else{
66180         /* If an index column fails to match and is not constrained by ==
66181         ** then the index cannot satisfy the ORDER BY constraint.
66182         */
66183         return 0;
66184       }
66185     }
66186     assert( pIdx->aSortOrder!=0 );
66187     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
66188     assert( iSortOrder==0 || iSortOrder==1 );
66189     termSortOrder = iSortOrder ^ pTerm->sortOrder;
66190     if( i>nEqCol ){
66191       if( termSortOrder!=sortOrder ){
66192         /* Indices can only be used if all ORDER BY terms past the
66193         ** equality constraints are all either DESC or ASC. */
66194         return 0;
66195       }
66196     }else{
66197       sortOrder = termSortOrder;
66198     }
66199     j++;
66200     pTerm++;
66201     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
66202       /* If the indexed column is the primary key and everything matches
66203       ** so far and none of the ORDER BY terms to the right reference other
66204       ** tables in the join, then we are assured that the index can be used 
66205       ** to sort because the primary key is unique and so none of the other
66206       ** columns will make any difference
66207       */
66208       j = nTerm;
66209     }
66210   }
66211
66212   *pbRev = sortOrder!=0;
66213   if( j>=nTerm ){
66214     /* All terms of the ORDER BY clause are covered by this index so
66215     ** this index can be used for sorting. */
66216     return 1;
66217   }
66218   if( pIdx->onError!=OE_None && i==pIdx->nColumn
66219       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
66220     /* All terms of this index match some prefix of the ORDER BY clause
66221     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
66222     ** clause reference other tables in a join.  If this is all true then
66223     ** the order by clause is superfluous. */
66224     return 1;
66225   }
66226   return 0;
66227 }
66228
66229 /*
66230 ** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
66231 ** by sorting in order of ROWID.  Return true if so and set *pbRev to be
66232 ** true for reverse ROWID and false for forward ROWID order.
66233 */
66234 static int sortableByRowid(
66235   int base,               /* Cursor number for table to be sorted */
66236   ExprList *pOrderBy,     /* The ORDER BY clause */
66237   ExprMaskSet *pMaskSet,  /* Mapping from tables to bitmaps */
66238   int *pbRev              /* Set to 1 if ORDER BY is DESC */
66239 ){
66240   Expr *p;
66241
66242   assert( pOrderBy!=0 );
66243   assert( pOrderBy->nExpr>0 );
66244   p = pOrderBy->a[0].pExpr;
66245   if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1
66246     && !referencesOtherTables(pOrderBy, pMaskSet, 1, base) ){
66247     *pbRev = pOrderBy->a[0].sortOrder;
66248     return 1;
66249   }
66250   return 0;
66251 }
66252
66253 /*
66254 ** Prepare a crude estimate of the logarithm of the input value.
66255 ** The results need not be exact.  This is only used for estimating
66256 ** the total cost of performing operatings with O(logN) or O(NlogN)
66257 ** complexity.  Because N is just a guess, it is no great tragedy if
66258 ** logN is a little off.
66259 */
66260 static double estLog(double N){
66261   double logN = 1;
66262   double x = 10;
66263   while( N>x ){
66264     logN += 1;
66265     x *= 10;
66266   }
66267   return logN;
66268 }
66269
66270 /*
66271 ** Two routines for printing the content of an sqlite3_index_info
66272 ** structure.  Used for testing and debugging only.  If neither
66273 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
66274 ** are no-ops.
66275 */
66276 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
66277 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
66278   int i;
66279   if( !sqlite3_where_trace ) return;
66280   for(i=0; i<p->nConstraint; i++){
66281     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
66282        i,
66283        p->aConstraint[i].iColumn,
66284        p->aConstraint[i].iTermOffset,
66285        p->aConstraint[i].op,
66286        p->aConstraint[i].usable);
66287   }
66288   for(i=0; i<p->nOrderBy; i++){
66289     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
66290        i,
66291        p->aOrderBy[i].iColumn,
66292        p->aOrderBy[i].desc);
66293   }
66294 }
66295 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
66296   int i;
66297   if( !sqlite3_where_trace ) return;
66298   for(i=0; i<p->nConstraint; i++){
66299     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
66300        i,
66301        p->aConstraintUsage[i].argvIndex,
66302        p->aConstraintUsage[i].omit);
66303   }
66304   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
66305   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
66306   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
66307   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
66308 }
66309 #else
66310 #define TRACE_IDX_INPUTS(A)
66311 #define TRACE_IDX_OUTPUTS(A)
66312 #endif
66313
66314 #ifndef SQLITE_OMIT_VIRTUALTABLE
66315 /*
66316 ** Compute the best index for a virtual table.
66317 **
66318 ** The best index is computed by the xBestIndex method of the virtual
66319 ** table module.  This routine is really just a wrapper that sets up
66320 ** the sqlite3_index_info structure that is used to communicate with
66321 ** xBestIndex.
66322 **
66323 ** In a join, this routine might be called multiple times for the
66324 ** same virtual table.  The sqlite3_index_info structure is created
66325 ** and initialized on the first invocation and reused on all subsequent
66326 ** invocations.  The sqlite3_index_info structure is also used when
66327 ** code is generated to access the virtual table.  The whereInfoDelete() 
66328 ** routine takes care of freeing the sqlite3_index_info structure after
66329 ** everybody has finished with it.
66330 */
66331 static double bestVirtualIndex(
66332   Parse *pParse,                 /* The parsing context */
66333   WhereClause *pWC,              /* The WHERE clause */
66334   struct SrcList_item *pSrc,     /* The FROM clause term to search */
66335   Bitmask notReady,              /* Mask of cursors that are not available */
66336   ExprList *pOrderBy,            /* The order by clause */
66337   int orderByUsable,             /* True if we can potential sort */
66338   sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
66339 ){
66340   Table *pTab = pSrc->pTab;
66341   sqlite3_index_info *pIdxInfo;
66342   struct sqlite3_index_constraint *pIdxCons;
66343   struct sqlite3_index_orderby *pIdxOrderBy;
66344   struct sqlite3_index_constraint_usage *pUsage;
66345   WhereTerm *pTerm;
66346   int i, j;
66347   int nOrderBy;
66348   int rc;
66349
66350   /* If the sqlite3_index_info structure has not been previously
66351   ** allocated and initialized for this virtual table, then allocate
66352   ** and initialize it now
66353   */
66354   pIdxInfo = *ppIdxInfo;
66355   if( pIdxInfo==0 ){
66356     WhereTerm *pTerm;
66357     int nTerm;
66358     WHERETRACE(("Recomputing index info for %s...\n", pTab->zName));
66359
66360     /* Count the number of possible WHERE clause constraints referring
66361     ** to this virtual table */
66362     for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
66363       if( pTerm->leftCursor != pSrc->iCursor ) continue;
66364       if( pTerm->eOperator==WO_IN ) continue;
66365       if( pTerm->eOperator==WO_ISNULL ) continue;
66366       nTerm++;
66367     }
66368
66369     /* If the ORDER BY clause contains only columns in the current 
66370     ** virtual table then allocate space for the aOrderBy part of
66371     ** the sqlite3_index_info structure.
66372     */
66373     nOrderBy = 0;
66374     if( pOrderBy ){
66375       for(i=0; i<pOrderBy->nExpr; i++){
66376         Expr *pExpr = pOrderBy->a[i].pExpr;
66377         if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
66378       }
66379       if( i==pOrderBy->nExpr ){
66380         nOrderBy = pOrderBy->nExpr;
66381       }
66382     }
66383
66384     /* Allocate the sqlite3_index_info structure
66385     */
66386     pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
66387                              + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
66388                              + sizeof(*pIdxOrderBy)*nOrderBy );
66389     if( pIdxInfo==0 ){
66390       sqlite3ErrorMsg(pParse, "out of memory");
66391       return 0.0;
66392     }
66393     *ppIdxInfo = pIdxInfo;
66394
66395     /* Initialize the structure.  The sqlite3_index_info structure contains
66396     ** many fields that are declared "const" to prevent xBestIndex from
66397     ** changing them.  We have to do some funky casting in order to
66398     ** initialize those fields.
66399     */
66400     pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
66401     pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
66402     pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
66403     *(int*)&pIdxInfo->nConstraint = nTerm;
66404     *(int*)&pIdxInfo->nOrderBy = nOrderBy;
66405     *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
66406     *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
66407     *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
66408                                                                      pUsage;
66409
66410     for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
66411       if( pTerm->leftCursor != pSrc->iCursor ) continue;
66412       if( pTerm->eOperator==WO_IN ) continue;
66413       if( pTerm->eOperator==WO_ISNULL ) continue;
66414       pIdxCons[j].iColumn = pTerm->leftColumn;
66415       pIdxCons[j].iTermOffset = i;
66416       pIdxCons[j].op = pTerm->eOperator;
66417       /* The direct assignment in the previous line is possible only because
66418       ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
66419       ** following asserts verify this fact. */
66420       assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
66421       assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
66422       assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
66423       assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
66424       assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
66425       assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
66426       assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
66427       j++;
66428     }
66429     for(i=0; i<nOrderBy; i++){
66430       Expr *pExpr = pOrderBy->a[i].pExpr;
66431       pIdxOrderBy[i].iColumn = pExpr->iColumn;
66432       pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
66433     }
66434   }
66435
66436   /* At this point, the sqlite3_index_info structure that pIdxInfo points
66437   ** to will have been initialized, either during the current invocation or
66438   ** during some prior invocation.  Now we just have to customize the
66439   ** details of pIdxInfo for the current invocation and pass it to
66440   ** xBestIndex.
66441   */
66442
66443   /* The module name must be defined. Also, by this point there must
66444   ** be a pointer to an sqlite3_vtab structure. Otherwise
66445   ** sqlite3ViewGetColumnNames() would have picked up the error. 
66446   */
66447   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
66448   assert( pTab->pVtab );
66449 #if 0
66450   if( pTab->pVtab==0 ){
66451     sqlite3ErrorMsg(pParse, "undefined module %s for table %s",
66452         pTab->azModuleArg[0], pTab->zName);
66453     return 0.0;
66454   }
66455 #endif
66456
66457   /* Set the aConstraint[].usable fields and initialize all 
66458   ** output variables to zero.
66459   **
66460   ** aConstraint[].usable is true for constraints where the right-hand
66461   ** side contains only references to tables to the left of the current
66462   ** table.  In other words, if the constraint is of the form:
66463   **
66464   **           column = expr
66465   **
66466   ** and we are evaluating a join, then the constraint on column is 
66467   ** only valid if all tables referenced in expr occur to the left
66468   ** of the table containing column.
66469   **
66470   ** The aConstraints[] array contains entries for all constraints
66471   ** on the current table.  That way we only have to compute it once
66472   ** even though we might try to pick the best index multiple times.
66473   ** For each attempt at picking an index, the order of tables in the
66474   ** join might be different so we have to recompute the usable flag
66475   ** each time.
66476   */
66477   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
66478   pUsage = pIdxInfo->aConstraintUsage;
66479   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
66480     j = pIdxCons->iTermOffset;
66481     pTerm = &pWC->a[j];
66482     pIdxCons->usable =  (pTerm->prereqRight & notReady)==0;
66483   }
66484   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
66485   if( pIdxInfo->needToFreeIdxStr ){
66486     sqlite3_free(pIdxInfo->idxStr);
66487   }
66488   pIdxInfo->idxStr = 0;
66489   pIdxInfo->idxNum = 0;
66490   pIdxInfo->needToFreeIdxStr = 0;
66491   pIdxInfo->orderByConsumed = 0;
66492   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / 2.0;
66493   nOrderBy = pIdxInfo->nOrderBy;
66494   if( pIdxInfo->nOrderBy && !orderByUsable ){
66495     *(int*)&pIdxInfo->nOrderBy = 0;
66496   }
66497
66498   sqlite3SafetyOff(pParse->db);
66499   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
66500   TRACE_IDX_INPUTS(pIdxInfo);
66501   rc = pTab->pVtab->pModule->xBestIndex(pTab->pVtab, pIdxInfo);
66502   TRACE_IDX_OUTPUTS(pIdxInfo);
66503   if( rc!=SQLITE_OK ){
66504     if( rc==SQLITE_NOMEM ){
66505       pParse->db->mallocFailed = 1;
66506     }else {
66507       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
66508     }
66509     sqlite3SafetyOn(pParse->db);
66510   }else{
66511     rc = sqlite3SafetyOn(pParse->db);
66512   }
66513   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
66514
66515   return pIdxInfo->estimatedCost;
66516 }
66517 #endif /* SQLITE_OMIT_VIRTUALTABLE */
66518
66519 /*
66520 ** Find the best index for accessing a particular table.  Return a pointer
66521 ** to the index, flags that describe how the index should be used, the
66522 ** number of equality constraints, and the "cost" for this index.
66523 **
66524 ** The lowest cost index wins.  The cost is an estimate of the amount of
66525 ** CPU and disk I/O need to process the request using the selected index.
66526 ** Factors that influence cost include:
66527 **
66528 **    *  The estimated number of rows that will be retrieved.  (The
66529 **       fewer the better.)
66530 **
66531 **    *  Whether or not sorting must occur.
66532 **
66533 **    *  Whether or not there must be separate lookups in the
66534 **       index and in the main table.
66535 **
66536 */
66537 static double bestIndex(
66538   Parse *pParse,              /* The parsing context */
66539   WhereClause *pWC,           /* The WHERE clause */
66540   struct SrcList_item *pSrc,  /* The FROM clause term to search */
66541   Bitmask notReady,           /* Mask of cursors that are not available */
66542   ExprList *pOrderBy,         /* The order by clause */
66543   Index **ppIndex,            /* Make *ppIndex point to the best index */
66544   int *pFlags,                /* Put flags describing this choice in *pFlags */
66545   int *pnEq                   /* Put the number of == or IN constraints here */
66546 ){
66547   WhereTerm *pTerm;
66548   Index *bestIdx = 0;         /* Index that gives the lowest cost */
66549   double lowestCost;          /* The cost of using bestIdx */
66550   int bestFlags = 0;          /* Flags associated with bestIdx */
66551   int bestNEq = 0;            /* Best value for nEq */
66552   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
66553   Index *pProbe;              /* An index we are evaluating */
66554   int rev;                    /* True to scan in reverse order */
66555   int flags;                  /* Flags associated with pProbe */
66556   int nEq;                    /* Number of == or IN constraints */
66557   int eqTermMask;             /* Mask of valid equality operators */
66558   double cost;                /* Cost of using pProbe */
66559
66560   WHERETRACE(("bestIndex: tbl=%s notReady=%x\n", pSrc->pTab->zName, notReady));
66561   lowestCost = SQLITE_BIG_DBL;
66562   pProbe = pSrc->pTab->pIndex;
66563
66564   /* If the table has no indices and there are no terms in the where
66565   ** clause that refer to the ROWID, then we will never be able to do
66566   ** anything other than a full table scan on this table.  We might as
66567   ** well put it first in the join order.  That way, perhaps it can be
66568   ** referenced by other tables in the join.
66569   */
66570   if( pProbe==0 &&
66571      findTerm(pWC, iCur, -1, 0, WO_EQ|WO_IN|WO_LT|WO_LE|WO_GT|WO_GE,0)==0 &&
66572      (pOrderBy==0 || !sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev)) ){
66573     *pFlags = 0;
66574     *ppIndex = 0;
66575     *pnEq = 0;
66576     return 0.0;
66577   }
66578
66579   /* Check for a rowid=EXPR or rowid IN (...) constraints
66580   */
66581   pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
66582   if( pTerm ){
66583     Expr *pExpr;
66584     *ppIndex = 0;
66585     bestFlags = WHERE_ROWID_EQ;
66586     if( pTerm->eOperator & WO_EQ ){
66587       /* Rowid== is always the best pick.  Look no further.  Because only
66588       ** a single row is generated, output is always in sorted order */
66589       *pFlags = WHERE_ROWID_EQ | WHERE_UNIQUE;
66590       *pnEq = 1;
66591       WHERETRACE(("... best is rowid\n"));
66592       return 0.0;
66593     }else if( (pExpr = pTerm->pExpr)->pList!=0 ){
66594       /* Rowid IN (LIST): cost is NlogN where N is the number of list
66595       ** elements.  */
66596       lowestCost = pExpr->pList->nExpr;
66597       lowestCost *= estLog(lowestCost);
66598     }else{
66599       /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
66600       ** in the result of the inner select.  We have no way to estimate
66601       ** that value so make a wild guess. */
66602       lowestCost = 200;
66603     }
66604     WHERETRACE(("... rowid IN cost: %.9g\n", lowestCost));
66605   }
66606
66607   /* Estimate the cost of a table scan.  If we do not know how many
66608   ** entries are in the table, use 1 million as a guess.
66609   */
66610   cost = pProbe ? pProbe->aiRowEst[0] : 1000000;
66611   WHERETRACE(("... table scan base cost: %.9g\n", cost));
66612   flags = WHERE_ROWID_RANGE;
66613
66614   /* Check for constraints on a range of rowids in a table scan.
66615   */
66616   pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
66617   if( pTerm ){
66618     if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
66619       flags |= WHERE_TOP_LIMIT;
66620       cost /= 3;  /* Guess that rowid<EXPR eliminates two-thirds or rows */
66621     }
66622     if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
66623       flags |= WHERE_BTM_LIMIT;
66624       cost /= 3;  /* Guess that rowid>EXPR eliminates two-thirds of rows */
66625     }
66626     WHERETRACE(("... rowid range reduces cost to %.9g\n", cost));
66627   }else{
66628     flags = 0;
66629   }
66630
66631   /* If the table scan does not satisfy the ORDER BY clause, increase
66632   ** the cost by NlogN to cover the expense of sorting. */
66633   if( pOrderBy ){
66634     if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) ){
66635       flags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
66636       if( rev ){
66637         flags |= WHERE_REVERSE;
66638       }
66639     }else{
66640       cost += cost*estLog(cost);
66641       WHERETRACE(("... sorting increases cost to %.9g\n", cost));
66642     }
66643   }
66644   if( cost<lowestCost ){
66645     lowestCost = cost;
66646     bestFlags = flags;
66647   }
66648
66649   /* If the pSrc table is the right table of a LEFT JOIN then we may not
66650   ** use an index to satisfy IS NULL constraints on that table.  This is
66651   ** because columns might end up being NULL if the table does not match -
66652   ** a circumstance which the index cannot help us discover.  Ticket #2177.
66653   */
66654   if( (pSrc->jointype & JT_LEFT)!=0 ){
66655     eqTermMask = WO_EQ|WO_IN;
66656   }else{
66657     eqTermMask = WO_EQ|WO_IN|WO_ISNULL;
66658   }
66659
66660   /* Look at each index.
66661   */
66662   for(; pProbe; pProbe=pProbe->pNext){
66663     int i;                       /* Loop counter */
66664     double inMultiplier = 1;
66665
66666     WHERETRACE(("... index %s:\n", pProbe->zName));
66667
66668     /* Count the number of columns in the index that are satisfied
66669     ** by x=EXPR constraints or x IN (...) constraints.
66670     */
66671     flags = 0;
66672     for(i=0; i<pProbe->nColumn; i++){
66673       int j = pProbe->aiColumn[i];
66674       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pProbe);
66675       if( pTerm==0 ) break;
66676       flags |= WHERE_COLUMN_EQ;
66677       if( pTerm->eOperator & WO_IN ){
66678         Expr *pExpr = pTerm->pExpr;
66679         flags |= WHERE_COLUMN_IN;
66680         if( pExpr->pSelect!=0 ){
66681           inMultiplier *= 25;
66682         }else if( pExpr->pList!=0 ){
66683           inMultiplier *= pExpr->pList->nExpr + 1;
66684         }
66685       }
66686     }
66687     cost = pProbe->aiRowEst[i] * inMultiplier * estLog(inMultiplier);
66688     nEq = i;
66689     if( pProbe->onError!=OE_None && (flags & WHERE_COLUMN_IN)==0
66690          && nEq==pProbe->nColumn ){
66691       flags |= WHERE_UNIQUE;
66692     }
66693     WHERETRACE(("...... nEq=%d inMult=%.9g cost=%.9g\n",nEq,inMultiplier,cost));
66694
66695     /* Look for range constraints
66696     */
66697     if( nEq<pProbe->nColumn ){
66698       int j = pProbe->aiColumn[nEq];
66699       pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
66700       if( pTerm ){
66701         flags |= WHERE_COLUMN_RANGE;
66702         if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
66703           flags |= WHERE_TOP_LIMIT;
66704           cost /= 3;
66705         }
66706         if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
66707           flags |= WHERE_BTM_LIMIT;
66708           cost /= 3;
66709         }
66710         WHERETRACE(("...... range reduces cost to %.9g\n", cost));
66711       }
66712     }
66713
66714     /* Add the additional cost of sorting if that is a factor.
66715     */
66716     if( pOrderBy ){
66717       if( (flags & WHERE_COLUMN_IN)==0 &&
66718            isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev) ){
66719         if( flags==0 ){
66720           flags = WHERE_COLUMN_RANGE;
66721         }
66722         flags |= WHERE_ORDERBY;
66723         if( rev ){
66724           flags |= WHERE_REVERSE;
66725         }
66726       }else{
66727         cost += cost*estLog(cost);
66728         WHERETRACE(("...... orderby increases cost to %.9g\n", cost));
66729       }
66730     }
66731
66732     /* Check to see if we can get away with using just the index without
66733     ** ever reading the table.  If that is the case, then halve the
66734     ** cost of this index.
66735     */
66736     if( flags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
66737       Bitmask m = pSrc->colUsed;
66738       int j;
66739       for(j=0; j<pProbe->nColumn; j++){
66740         int x = pProbe->aiColumn[j];
66741         if( x<BMS-1 ){
66742           m &= ~(((Bitmask)1)<<x);
66743         }
66744       }
66745       if( m==0 ){
66746         flags |= WHERE_IDX_ONLY;
66747         cost /= 2;
66748         WHERETRACE(("...... idx-only reduces cost to %.9g\n", cost));
66749       }
66750     }
66751
66752     /* If this index has achieved the lowest cost so far, then use it.
66753     */
66754     if( flags && cost < lowestCost ){
66755       bestIdx = pProbe;
66756       lowestCost = cost;
66757       bestFlags = flags;
66758       bestNEq = nEq;
66759     }
66760   }
66761
66762   /* Report the best result
66763   */
66764   *ppIndex = bestIdx;
66765   WHERETRACE(("best index is %s, cost=%.9g, flags=%x, nEq=%d\n",
66766         bestIdx ? bestIdx->zName : "(none)", lowestCost, bestFlags, bestNEq));
66767   *pFlags = bestFlags | eqTermMask;
66768   *pnEq = bestNEq;
66769   return lowestCost;
66770 }
66771
66772
66773 /*
66774 ** Disable a term in the WHERE clause.  Except, do not disable the term
66775 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
66776 ** or USING clause of that join.
66777 **
66778 ** Consider the term t2.z='ok' in the following queries:
66779 **
66780 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
66781 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
66782 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
66783 **
66784 ** The t2.z='ok' is disabled in the in (2) because it originates
66785 ** in the ON clause.  The term is disabled in (3) because it is not part
66786 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
66787 **
66788 ** Disabling a term causes that term to not be tested in the inner loop
66789 ** of the join.  Disabling is an optimization.  When terms are satisfied
66790 ** by indices, we disable them to prevent redundant tests in the inner
66791 ** loop.  We would get the correct results if nothing were ever disabled,
66792 ** but joins might run a little slower.  The trick is to disable as much
66793 ** as we can without disabling too much.  If we disabled in (1), we'd get
66794 ** the wrong answer.  See ticket #813.
66795 */
66796 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
66797   if( pTerm
66798       && (pTerm->flags & TERM_CODED)==0
66799       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
66800   ){
66801     pTerm->flags |= TERM_CODED;
66802     if( pTerm->iParent>=0 ){
66803       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
66804       if( (--pOther->nChild)==0 ){
66805         disableTerm(pLevel, pOther);
66806       }
66807     }
66808   }
66809 }
66810
66811 /*
66812 ** Generate code that builds a probe for an index.
66813 **
66814 ** There should be nColumn values on the stack.  The index
66815 ** to be probed is pIdx.  Pop the values from the stack and
66816 ** replace them all with a single record that is the index
66817 ** problem.
66818 */
66819 static void buildIndexProbe(
66820   Vdbe *v,        /* Generate code into this VM */
66821   int nColumn,    /* The number of columns to check for NULL */
66822   Index *pIdx     /* Index that we will be searching */
66823 ){
66824   sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
66825   sqlite3IndexAffinityStr(v, pIdx);
66826 }
66827
66828
66829 /*
66830 ** Generate code for a single equality term of the WHERE clause.  An equality
66831 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
66832 ** coded.
66833 **
66834 ** The current value for the constraint is left on the top of the stack.
66835 **
66836 ** For a constraint of the form X=expr, the expression is evaluated and its
66837 ** result is left on the stack.  For constraints of the form X IN (...)
66838 ** this routine sets up a loop that will iterate over all values of X.
66839 */
66840 static void codeEqualityTerm(
66841   Parse *pParse,      /* The parsing context */
66842   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
66843   WhereLevel *pLevel  /* When level of the FROM clause we are working on */
66844 ){
66845   Expr *pX = pTerm->pExpr;
66846   Vdbe *v = pParse->pVdbe;
66847   if( pX->op==TK_EQ ){
66848     sqlite3ExprCode(pParse, pX->pRight);
66849   }else if( pX->op==TK_ISNULL ){
66850     sqlite3VdbeAddOp(v, OP_Null, 0, 0);
66851 #ifndef SQLITE_OMIT_SUBQUERY
66852   }else{
66853     int eType;
66854     int iTab;
66855     struct InLoop *pIn;
66856
66857     assert( pX->op==TK_IN );
66858     eType = sqlite3FindInIndex(pParse, pX, 1);
66859     iTab = pX->iTable;
66860     sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0);
66861     VdbeComment((v, "# %.*s", pX->span.n, pX->span.z));
66862     if( pLevel->nIn==0 ){
66863       pLevel->nxt = sqlite3VdbeMakeLabel(v);
66864     }
66865     pLevel->nIn++;
66866     pLevel->aInLoop = sqlite3DbReallocOrFree(pParse->db, pLevel->aInLoop,
66867                                     sizeof(pLevel->aInLoop[0])*pLevel->nIn);
66868     pIn = pLevel->aInLoop;
66869     if( pIn ){
66870       int op = ((eType==IN_INDEX_ROWID)?OP_Rowid:OP_Column);
66871       pIn += pLevel->nIn - 1;
66872       pIn->iCur = iTab;
66873       pIn->topAddr = sqlite3VdbeAddOp(v, op, iTab, 0);
66874       sqlite3VdbeAddOp(v, OP_IsNull, -1, 0);
66875     }else{
66876       pLevel->nIn = 0;
66877     }
66878 #endif
66879   }
66880   disableTerm(pLevel, pTerm);
66881 }
66882
66883 /*
66884 ** Generate code that will evaluate all == and IN constraints for an
66885 ** index.  The values for all constraints are left on the stack.
66886 **
66887 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
66888 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
66889 ** The index has as many as three equality constraints, but in this
66890 ** example, the third "c" value is an inequality.  So only two 
66891 ** constraints are coded.  This routine will generate code to evaluate
66892 ** a==5 and b IN (1,2,3).  The current values for a and b will be left
66893 ** on the stack - a is the deepest and b the shallowest.
66894 **
66895 ** In the example above nEq==2.  But this subroutine works for any value
66896 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
66897 ** The only thing it does is allocate the pLevel->iMem memory cell.
66898 **
66899 ** This routine always allocates at least one memory cell and puts
66900 ** the address of that memory cell in pLevel->iMem.  The code that
66901 ** calls this routine will use pLevel->iMem to store the termination
66902 ** key value of the loop.  If one or more IN operators appear, then
66903 ** this routine allocates an additional nEq memory cells for internal
66904 ** use.
66905 */
66906 static void codeAllEqualityTerms(
66907   Parse *pParse,        /* Parsing context */
66908   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
66909   WhereClause *pWC,     /* The WHERE clause */
66910   Bitmask notReady      /* Which parts of FROM have not yet been coded */
66911 ){
66912   int nEq = pLevel->nEq;        /* The number of == or IN constraints to code */
66913   int termsInMem = 0;           /* If true, store value in mem[] cells */
66914   Vdbe *v = pParse->pVdbe;      /* The virtual machine under construction */
66915   Index *pIdx = pLevel->pIdx;   /* The index being used for this loop */
66916   int iCur = pLevel->iTabCur;   /* The cursor of the table */
66917   WhereTerm *pTerm;             /* A single constraint term */
66918   int j;                        /* Loop counter */
66919
66920   /* Figure out how many memory cells we will need then allocate them.
66921   ** We always need at least one used to store the loop terminator
66922   ** value.  If there are IN operators we'll need one for each == or
66923   ** IN constraint.
66924   */
66925   pLevel->iMem = pParse->nMem++;
66926   if( pLevel->flags & WHERE_COLUMN_IN ){
66927     pParse->nMem += pLevel->nEq;
66928     termsInMem = 1;
66929   }
66930
66931   /* Evaluate the equality constraints
66932   */
66933   assert( pIdx->nColumn>=nEq );
66934   for(j=0; j<nEq; j++){
66935     int k = pIdx->aiColumn[j];
66936     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->flags, pIdx);
66937     if( pTerm==0 ) break;
66938     assert( (pTerm->flags & TERM_CODED)==0 );
66939     codeEqualityTerm(pParse, pTerm, pLevel);
66940     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
66941       sqlite3VdbeAddOp(v, OP_IsNull, termsInMem ? -1 : -(j+1), pLevel->brk);
66942     }
66943     if( termsInMem ){
66944       sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem+j+1, 1);
66945     }
66946   }
66947
66948   /* Make sure all the constraint values are on the top of the stack
66949   */
66950   if( termsInMem ){
66951     for(j=0; j<nEq; j++){
66952       sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem+j+1, 0);
66953     }
66954   }
66955 }
66956
66957 #if defined(SQLITE_TEST)
66958 /*
66959 ** The following variable holds a text description of query plan generated
66960 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
66961 ** overwrites the previous.  This information is used for testing and
66962 ** analysis only.
66963 */
66964 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
66965 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
66966
66967 #endif /* SQLITE_TEST */
66968
66969
66970 /*
66971 ** Free a WhereInfo structure
66972 */
66973 static void whereInfoFree(WhereInfo *pWInfo){
66974   if( pWInfo ){
66975     int i;
66976     for(i=0; i<pWInfo->nLevel; i++){
66977       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
66978       if( pInfo ){
66979         if( pInfo->needToFreeIdxStr ){
66980           /* Coverage: Don't think this can be reached. By the time this
66981           ** function is called, the index-strings have been passed
66982           ** to the vdbe layer for deletion.
66983           */
66984           sqlite3_free(pInfo->idxStr);
66985         }
66986         sqlite3_free(pInfo);
66987       }
66988     }
66989     sqlite3_free(pWInfo);
66990   }
66991 }
66992
66993
66994 /*
66995 ** Generate the beginning of the loop used for WHERE clause processing.
66996 ** The return value is a pointer to an opaque structure that contains
66997 ** information needed to terminate the loop.  Later, the calling routine
66998 ** should invoke sqlite3WhereEnd() with the return value of this function
66999 ** in order to complete the WHERE clause processing.
67000 **
67001 ** If an error occurs, this routine returns NULL.
67002 **
67003 ** The basic idea is to do a nested loop, one loop for each table in
67004 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
67005 ** same as a SELECT with only a single table in the FROM clause.)  For
67006 ** example, if the SQL is this:
67007 **
67008 **       SELECT * FROM t1, t2, t3 WHERE ...;
67009 **
67010 ** Then the code generated is conceptually like the following:
67011 **
67012 **      foreach row1 in t1 do       \    Code generated
67013 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
67014 **          foreach row3 in t3 do   /
67015 **            ...
67016 **          end                     \    Code generated
67017 **        end                        |-- by sqlite3WhereEnd()
67018 **      end                         /
67019 **
67020 ** Note that the loops might not be nested in the order in which they
67021 ** appear in the FROM clause if a different order is better able to make
67022 ** use of indices.  Note also that when the IN operator appears in
67023 ** the WHERE clause, it might result in additional nested loops for
67024 ** scanning through all values on the right-hand side of the IN.
67025 **
67026 ** There are Btree cursors associated with each table.  t1 uses cursor
67027 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
67028 ** And so forth.  This routine generates code to open those VDBE cursors
67029 ** and sqlite3WhereEnd() generates the code to close them.
67030 **
67031 ** The code that sqlite3WhereBegin() generates leaves the cursors named
67032 ** in pTabList pointing at their appropriate entries.  The [...] code
67033 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
67034 ** data from the various tables of the loop.
67035 **
67036 ** If the WHERE clause is empty, the foreach loops must each scan their
67037 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
67038 ** the tables have indices and there are terms in the WHERE clause that
67039 ** refer to those indices, a complete table scan can be avoided and the
67040 ** code will run much faster.  Most of the work of this routine is checking
67041 ** to see if there are indices that can be used to speed up the loop.
67042 **
67043 ** Terms of the WHERE clause are also used to limit which rows actually
67044 ** make it to the "..." in the middle of the loop.  After each "foreach",
67045 ** terms of the WHERE clause that use only terms in that loop and outer
67046 ** loops are evaluated and if false a jump is made around all subsequent
67047 ** inner loops (or around the "..." if the test occurs within the inner-
67048 ** most loop)
67049 **
67050 ** OUTER JOINS
67051 **
67052 ** An outer join of tables t1 and t2 is conceptally coded as follows:
67053 **
67054 **    foreach row1 in t1 do
67055 **      flag = 0
67056 **      foreach row2 in t2 do
67057 **        start:
67058 **          ...
67059 **          flag = 1
67060 **      end
67061 **      if flag==0 then
67062 **        move the row2 cursor to a null row
67063 **        goto start
67064 **      fi
67065 **    end
67066 **
67067 ** ORDER BY CLAUSE PROCESSING
67068 **
67069 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
67070 ** if there is one.  If there is no ORDER BY clause or if this routine
67071 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
67072 **
67073 ** If an index can be used so that the natural output order of the table
67074 ** scan is correct for the ORDER BY clause, then that index is used and
67075 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
67076 ** unnecessary sort of the result set if an index appropriate for the
67077 ** ORDER BY clause already exists.
67078 **
67079 ** If the where clause loops cannot be arranged to provide the correct
67080 ** output order, then the *ppOrderBy is unchanged.
67081 */
67082 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
67083   Parse *pParse,        /* The parser context */
67084   SrcList *pTabList,    /* A list of all tables to be scanned */
67085   Expr *pWhere,         /* The WHERE clause */
67086   ExprList **ppOrderBy  /* An ORDER BY clause, or NULL */
67087 ){
67088   int i;                     /* Loop counter */
67089   WhereInfo *pWInfo;         /* Will become the return value of this function */
67090   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
67091   int brk, cont = 0;         /* Addresses used during code generation */
67092   Bitmask notReady;          /* Cursors that are not yet positioned */
67093   WhereTerm *pTerm;          /* A single term in the WHERE clause */
67094   ExprMaskSet maskSet;       /* The expression mask set */
67095   WhereClause wc;            /* The WHERE clause is divided into these terms */
67096   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
67097   WhereLevel *pLevel;             /* A single level in the pWInfo list */
67098   int iFrom;                      /* First unused FROM clause element */
67099   int andFlags;              /* AND-ed combination of all wc.a[].flags */
67100   sqlite3 *db;               /* Database connection */
67101
67102   /* The number of tables in the FROM clause is limited by the number of
67103   ** bits in a Bitmask 
67104   */
67105   if( pTabList->nSrc>BMS ){
67106     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
67107     return 0;
67108   }
67109
67110   /* Split the WHERE clause into separate subexpressions where each
67111   ** subexpression is separated by an AND operator.
67112   */
67113   initMaskSet(&maskSet);
67114   whereClauseInit(&wc, pParse, &maskSet);
67115   whereSplit(&wc, pWhere, TK_AND);
67116     
67117   /* Allocate and initialize the WhereInfo structure that will become the
67118   ** return value.
67119   */
67120   db = pParse->db;
67121   pWInfo = sqlite3DbMallocZero(db,  
67122                       sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
67123   if( db->mallocFailed ){
67124     goto whereBeginNoMem;
67125   }
67126   pWInfo->nLevel = pTabList->nSrc;
67127   pWInfo->pParse = pParse;
67128   pWInfo->pTabList = pTabList;
67129   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
67130
67131   /* Special case: a WHERE clause that is constant.  Evaluate the
67132   ** expression and either jump over all of the code or fall thru.
67133   */
67134   if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
67135     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
67136     pWhere = 0;
67137   }
67138
67139   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
67140   ** add new virtual terms onto the end of the WHERE clause.  We do not
67141   ** want to analyze these virtual terms, so start analyzing at the end
67142   ** and work forward so that the added virtual terms are never processed.
67143   */
67144   for(i=0; i<pTabList->nSrc; i++){
67145     createMask(&maskSet, pTabList->a[i].iCursor);
67146   }
67147   exprAnalyzeAll(pTabList, &wc);
67148   if( db->mallocFailed ){
67149     goto whereBeginNoMem;
67150   }
67151
67152   /* Chose the best index to use for each table in the FROM clause.
67153   **
67154   ** This loop fills in the following fields:
67155   **
67156   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
67157   **   pWInfo->a[].flags     WHERE_xxx flags associated with pIdx
67158   **   pWInfo->a[].nEq       The number of == and IN constraints
67159   **   pWInfo->a[].iFrom     When term of the FROM clause is being coded
67160   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
67161   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
67162   **
67163   ** This loop also figures out the nesting order of tables in the FROM
67164   ** clause.
67165   */
67166   notReady = ~(Bitmask)0;
67167   pTabItem = pTabList->a;
67168   pLevel = pWInfo->a;
67169   andFlags = ~0;
67170   WHERETRACE(("*** Optimizer Start ***\n"));
67171   for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
67172     Index *pIdx;                /* Index for FROM table at pTabItem */
67173     int flags;                  /* Flags asssociated with pIdx */
67174     int nEq;                    /* Number of == or IN constraints */
67175     double cost;                /* The cost for pIdx */
67176     int j;                      /* For looping over FROM tables */
67177     Index *pBest = 0;           /* The best index seen so far */
67178     int bestFlags = 0;          /* Flags associated with pBest */
67179     int bestNEq = 0;            /* nEq associated with pBest */
67180     double lowestCost;          /* Cost of the pBest */
67181     int bestJ = 0;              /* The value of j */
67182     Bitmask m;                  /* Bitmask value for j or bestJ */
67183     int once = 0;               /* True when first table is seen */
67184     sqlite3_index_info *pIndex; /* Current virtual index */
67185
67186     lowestCost = SQLITE_BIG_DBL;
67187     for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
67188       int doNotReorder;  /* True if this table should not be reordered */
67189
67190       doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
67191       if( once && doNotReorder ) break;
67192       m = getMask(&maskSet, pTabItem->iCursor);
67193       if( (m & notReady)==0 ){
67194         if( j==iFrom ) iFrom++;
67195         continue;
67196       }
67197       assert( pTabItem->pTab );
67198 #ifndef SQLITE_OMIT_VIRTUALTABLE
67199       if( IsVirtual(pTabItem->pTab) ){
67200         sqlite3_index_info **ppIdxInfo = &pWInfo->a[j].pIdxInfo;
67201         cost = bestVirtualIndex(pParse, &wc, pTabItem, notReady,
67202                                 ppOrderBy ? *ppOrderBy : 0, i==0,
67203                                 ppIdxInfo);
67204         flags = WHERE_VIRTUALTABLE;
67205         pIndex = *ppIdxInfo;
67206         if( pIndex && pIndex->orderByConsumed ){
67207           flags = WHERE_VIRTUALTABLE | WHERE_ORDERBY;
67208         }
67209         pIdx = 0;
67210         nEq = 0;
67211         if( (SQLITE_BIG_DBL/2.0)<cost ){
67212           /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
67213           ** inital value of lowestCost in this loop. If it is, then
67214           ** the (cost<lowestCost) test below will never be true and
67215           ** pLevel->pBestIdx never set.
67216           */ 
67217           cost = (SQLITE_BIG_DBL/2.0);
67218         }
67219       }else 
67220 #endif
67221       {
67222         cost = bestIndex(pParse, &wc, pTabItem, notReady,
67223                          (i==0 && ppOrderBy) ? *ppOrderBy : 0,
67224                          &pIdx, &flags, &nEq);
67225         pIndex = 0;
67226       }
67227       if( cost<lowestCost ){
67228         once = 1;
67229         lowestCost = cost;
67230         pBest = pIdx;
67231         bestFlags = flags;
67232         bestNEq = nEq;
67233         bestJ = j;
67234         pLevel->pBestIdx = pIndex;
67235       }
67236       if( doNotReorder ) break;
67237     }
67238     WHERETRACE(("*** Optimizer choose table %d for loop %d\n", bestJ,
67239            pLevel-pWInfo->a));
67240     if( (bestFlags & WHERE_ORDERBY)!=0 ){
67241       *ppOrderBy = 0;
67242     }
67243     andFlags &= bestFlags;
67244     pLevel->flags = bestFlags;
67245     pLevel->pIdx = pBest;
67246     pLevel->nEq = bestNEq;
67247     pLevel->aInLoop = 0;
67248     pLevel->nIn = 0;
67249     if( pBest ){
67250       pLevel->iIdxCur = pParse->nTab++;
67251     }else{
67252       pLevel->iIdxCur = -1;
67253     }
67254     notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor);
67255     pLevel->iFrom = bestJ;
67256   }
67257   WHERETRACE(("*** Optimizer Finished ***\n"));
67258
67259   /* If the total query only selects a single row, then the ORDER BY
67260   ** clause is irrelevant.
67261   */
67262   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
67263     *ppOrderBy = 0;
67264   }
67265
67266   /* Open all tables in the pTabList and any indices selected for
67267   ** searching those tables.
67268   */
67269   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
67270   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
67271     Table *pTab;     /* Table to open */
67272     Index *pIx;      /* Index used to access pTab (if any) */
67273     int iDb;         /* Index of database containing table/index */
67274     int iIdxCur = pLevel->iIdxCur;
67275
67276 #ifndef SQLITE_OMIT_EXPLAIN
67277     if( pParse->explain==2 ){
67278       char *zMsg;
67279       struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
67280       zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
67281       if( pItem->zAlias ){
67282         zMsg = sqlite3MPrintf(db, "%z AS %s", zMsg, pItem->zAlias);
67283       }
67284       if( (pIx = pLevel->pIdx)!=0 ){
67285         zMsg = sqlite3MPrintf(db, "%z WITH INDEX %s", zMsg, pIx->zName);
67286       }else if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
67287         zMsg = sqlite3MPrintf(db, "%z USING PRIMARY KEY", zMsg);
67288       }
67289 #ifndef SQLITE_OMIT_VIRTUALTABLE
67290       else if( pLevel->pBestIdx ){
67291         sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
67292         zMsg = sqlite3MPrintf(db, "%z VIRTUAL TABLE INDEX %d:%s", zMsg,
67293                     pBestIdx->idxNum, pBestIdx->idxStr);
67294       }
67295 #endif
67296       if( pLevel->flags & WHERE_ORDERBY ){
67297         zMsg = sqlite3MPrintf(db, "%z ORDER BY", zMsg);
67298       }
67299       sqlite3VdbeOp3(v, OP_Explain, i, pLevel->iFrom, zMsg, P3_DYNAMIC);
67300     }
67301 #endif /* SQLITE_OMIT_EXPLAIN */
67302     pTabItem = &pTabList->a[pLevel->iFrom];
67303     pTab = pTabItem->pTab;
67304     iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
67305     if( pTab->isEphem || pTab->pSelect ) continue;
67306 #ifndef SQLITE_OMIT_VIRTUALTABLE
67307     if( pLevel->pBestIdx ){
67308       int iCur = pTabItem->iCursor;
67309       sqlite3VdbeOp3(v, OP_VOpen, iCur, 0, (const char*)pTab->pVtab, P3_VTAB);
67310     }else
67311 #endif
67312     if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
67313       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, OP_OpenRead);
67314       if( pTab->nCol<(sizeof(Bitmask)*8) ){
67315         Bitmask b = pTabItem->colUsed;
67316         int n = 0;
67317         for(; b; b=b>>1, n++){}
67318         sqlite3VdbeChangeP2(v, sqlite3VdbeCurrentAddr(v)-1, n);
67319         assert( n<=pTab->nCol );
67320       }
67321     }else{
67322       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
67323     }
67324     pLevel->iTabCur = pTabItem->iCursor;
67325     if( (pIx = pLevel->pIdx)!=0 ){
67326       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
67327       assert( pIx->pSchema==pTab->pSchema );
67328       sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
67329       VdbeComment((v, "# %s", pIx->zName));
67330       sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIx->tnum,
67331                      (char*)pKey, P3_KEYINFO_HANDOFF);
67332       sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1);
67333     }
67334     sqlite3CodeVerifySchema(pParse, iDb);
67335   }
67336   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
67337
67338   /* Generate the code to do the search.  Each iteration of the for
67339   ** loop below generates code for a single nested loop of the VM
67340   ** program.
67341   */
67342   notReady = ~(Bitmask)0;
67343   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
67344     int j;
67345     int iCur = pTabItem->iCursor;  /* The VDBE cursor for the table */
67346     Index *pIdx;       /* The index we will be using */
67347     int nxt;           /* Where to jump to continue with the next IN case */
67348     int iIdxCur;       /* The VDBE cursor for the index */
67349     int omitTable;     /* True if we use the index only */
67350     int bRev;          /* True if we need to scan in reverse order */
67351
67352     pTabItem = &pTabList->a[pLevel->iFrom];
67353     iCur = pTabItem->iCursor;
67354     pIdx = pLevel->pIdx;
67355     iIdxCur = pLevel->iIdxCur;
67356     bRev = (pLevel->flags & WHERE_REVERSE)!=0;
67357     omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
67358
67359     /* Create labels for the "break" and "continue" instructions
67360     ** for the current loop.  Jump to brk to break out of a loop.
67361     ** Jump to cont to go immediately to the next iteration of the
67362     ** loop.
67363     **
67364     ** When there is an IN operator, we also have a "nxt" label that
67365     ** means to continue with the next IN value combination.  When
67366     ** there are no IN operators in the constraints, the "nxt" label
67367     ** is the same as "brk".
67368     */
67369     brk = pLevel->brk = pLevel->nxt = sqlite3VdbeMakeLabel(v);
67370     cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
67371
67372     /* If this is the right table of a LEFT OUTER JOIN, allocate and
67373     ** initialize a memory cell that records if this table matches any
67374     ** row of the left table of the join.
67375     */
67376     if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
67377       if( !pParse->nMem ) pParse->nMem++;
67378       pLevel->iLeftJoin = pParse->nMem++;
67379       sqlite3VdbeAddOp(v, OP_MemInt, 0, pLevel->iLeftJoin);
67380       VdbeComment((v, "# init LEFT JOIN no-match flag"));
67381     }
67382
67383 #ifndef SQLITE_OMIT_VIRTUALTABLE
67384     if( pLevel->pBestIdx ){
67385       /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
67386       **          to access the data.
67387       */
67388       int j;
67389       sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
67390       int nConstraint = pBestIdx->nConstraint;
67391       struct sqlite3_index_constraint_usage *aUsage =
67392                                                   pBestIdx->aConstraintUsage;
67393       const struct sqlite3_index_constraint *aConstraint =
67394                                                   pBestIdx->aConstraint;
67395
67396       for(j=1; j<=nConstraint; j++){
67397         int k;
67398         for(k=0; k<nConstraint; k++){
67399           if( aUsage[k].argvIndex==j ){
67400             int iTerm = aConstraint[k].iTermOffset;
67401             sqlite3ExprCode(pParse, wc.a[iTerm].pExpr->pRight);
67402             break;
67403           }
67404         }
67405         if( k==nConstraint ) break;
67406       }
67407       sqlite3VdbeAddOp(v, OP_Integer, j-1, 0);
67408       sqlite3VdbeAddOp(v, OP_Integer, pBestIdx->idxNum, 0);
67409       sqlite3VdbeOp3(v, OP_VFilter, iCur, brk, pBestIdx->idxStr,
67410                       pBestIdx->needToFreeIdxStr ? P3_MPRINTF : P3_STATIC);
67411       pBestIdx->needToFreeIdxStr = 0;
67412       for(j=0; j<pBestIdx->nConstraint; j++){
67413         if( aUsage[j].omit ){
67414           int iTerm = aConstraint[j].iTermOffset;
67415           disableTerm(pLevel, &wc.a[iTerm]);
67416         }
67417       }
67418       pLevel->op = OP_VNext;
67419       pLevel->p1 = iCur;
67420       pLevel->p2 = sqlite3VdbeCurrentAddr(v);
67421     }else
67422 #endif /* SQLITE_OMIT_VIRTUALTABLE */
67423
67424     if( pLevel->flags & WHERE_ROWID_EQ ){
67425       /* Case 1:  We can directly reference a single row using an
67426       **          equality comparison against the ROWID field.  Or
67427       **          we reference multiple rows using a "rowid IN (...)"
67428       **          construct.
67429       */
67430       pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
67431       assert( pTerm!=0 );
67432       assert( pTerm->pExpr!=0 );
67433       assert( pTerm->leftCursor==iCur );
67434       assert( omitTable==0 );
67435       codeEqualityTerm(pParse, pTerm, pLevel);
67436       nxt = pLevel->nxt;
67437       sqlite3VdbeAddOp(v, OP_MustBeInt, 1, nxt);
67438       sqlite3VdbeAddOp(v, OP_NotExists, iCur, nxt);
67439       VdbeComment((v, "pk"));
67440       pLevel->op = OP_Noop;
67441     }else if( pLevel->flags & WHERE_ROWID_RANGE ){
67442       /* Case 2:  We have an inequality comparison against the ROWID field.
67443       */
67444       int testOp = OP_Noop;
67445       int start;
67446       WhereTerm *pStart, *pEnd;
67447
67448       assert( omitTable==0 );
67449       pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
67450       pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
67451       if( bRev ){
67452         pTerm = pStart;
67453         pStart = pEnd;
67454         pEnd = pTerm;
67455       }
67456       if( pStart ){
67457         Expr *pX;
67458         pX = pStart->pExpr;
67459         assert( pX!=0 );
67460         assert( pStart->leftCursor==iCur );
67461         sqlite3ExprCode(pParse, pX->pRight);
67462         sqlite3VdbeAddOp(v, OP_ForceInt, pX->op==TK_LE || pX->op==TK_GT, brk);
67463         sqlite3VdbeAddOp(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk);
67464         VdbeComment((v, "pk"));
67465         disableTerm(pLevel, pStart);
67466       }else{
67467         sqlite3VdbeAddOp(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
67468       }
67469       if( pEnd ){
67470         Expr *pX;
67471         pX = pEnd->pExpr;
67472         assert( pX!=0 );
67473         assert( pEnd->leftCursor==iCur );
67474         sqlite3ExprCode(pParse, pX->pRight);
67475         pLevel->iMem = pParse->nMem++;
67476         sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
67477         if( pX->op==TK_LT || pX->op==TK_GT ){
67478           testOp = bRev ? OP_Le : OP_Ge;
67479         }else{
67480           testOp = bRev ? OP_Lt : OP_Gt;
67481         }
67482         disableTerm(pLevel, pEnd);
67483       }
67484       start = sqlite3VdbeCurrentAddr(v);
67485       pLevel->op = bRev ? OP_Prev : OP_Next;
67486       pLevel->p1 = iCur;
67487       pLevel->p2 = start;
67488       if( testOp!=OP_Noop ){
67489         sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
67490         sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
67491         sqlite3VdbeAddOp(v, testOp, SQLITE_AFF_NUMERIC|0x100, brk);
67492       }
67493     }else if( pLevel->flags & WHERE_COLUMN_RANGE ){
67494       /* Case 3: The WHERE clause term that refers to the right-most
67495       **         column of the index is an inequality.  For example, if
67496       **         the index is on (x,y,z) and the WHERE clause is of the
67497       **         form "x=5 AND y<10" then this case is used.  Only the
67498       **         right-most column can be an inequality - the rest must
67499       **         use the "==" and "IN" operators.
67500       **
67501       **         This case is also used when there are no WHERE clause
67502       **         constraints but an index is selected anyway, in order
67503       **         to force the output order to conform to an ORDER BY.
67504       */
67505       int start;
67506       int nEq = pLevel->nEq;
67507       int topEq=0;        /* True if top limit uses ==. False is strictly < */
67508       int btmEq=0;        /* True if btm limit uses ==. False if strictly > */
67509       int topOp, btmOp;   /* Operators for the top and bottom search bounds */
67510       int testOp;
67511       int topLimit = (pLevel->flags & WHERE_TOP_LIMIT)!=0;
67512       int btmLimit = (pLevel->flags & WHERE_BTM_LIMIT)!=0;
67513
67514       /* Generate code to evaluate all constraint terms using == or IN
67515       ** and level the values of those terms on the stack.
67516       */
67517       codeAllEqualityTerms(pParse, pLevel, &wc, notReady);
67518
67519       /* Duplicate the equality term values because they will all be
67520       ** used twice: once to make the termination key and once to make the
67521       ** start key.
67522       */
67523       for(j=0; j<nEq; j++){
67524         sqlite3VdbeAddOp(v, OP_Dup, nEq-1, 0);
67525       }
67526
67527       /* Figure out what comparison operators to use for top and bottom 
67528       ** search bounds. For an ascending index, the bottom bound is a > or >=
67529       ** operator and the top bound is a < or <= operator.  For a descending
67530       ** index the operators are reversed.
67531       */
67532       if( pIdx->aSortOrder[nEq]==SQLITE_SO_ASC ){
67533         topOp = WO_LT|WO_LE;
67534         btmOp = WO_GT|WO_GE;
67535       }else{
67536         topOp = WO_GT|WO_GE;
67537         btmOp = WO_LT|WO_LE;
67538         SWAP(int, topLimit, btmLimit);
67539       }
67540
67541       /* Generate the termination key.  This is the key value that
67542       ** will end the search.  There is no termination key if there
67543       ** are no equality terms and no "X<..." term.
67544       **
67545       ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
67546       ** key computed here really ends up being the start key.
67547       */
67548       nxt = pLevel->nxt;
67549       if( topLimit ){
67550         Expr *pX;
67551         int k = pIdx->aiColumn[j];
67552         pTerm = findTerm(&wc, iCur, k, notReady, topOp, pIdx);
67553         assert( pTerm!=0 );
67554         pX = pTerm->pExpr;
67555         assert( (pTerm->flags & TERM_CODED)==0 );
67556         sqlite3ExprCode(pParse, pX->pRight);
67557         sqlite3VdbeAddOp(v, OP_IsNull, -(nEq*2+1), nxt);
67558         topEq = pTerm->eOperator & (WO_LE|WO_GE);
67559         disableTerm(pLevel, pTerm);
67560         testOp = OP_IdxGE;
67561       }else{
67562         testOp = nEq>0 ? OP_IdxGE : OP_Noop;
67563         topEq = 1;
67564       }
67565       if( testOp!=OP_Noop ){
67566         int nCol = nEq + topLimit;
67567         pLevel->iMem = pParse->nMem++;
67568         buildIndexProbe(v, nCol, pIdx);
67569         if( bRev ){
67570           int op = topEq ? OP_MoveLe : OP_MoveLt;
67571           sqlite3VdbeAddOp(v, op, iIdxCur, nxt);
67572         }else{
67573           sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
67574         }
67575       }else if( bRev ){
67576         sqlite3VdbeAddOp(v, OP_Last, iIdxCur, brk);
67577       }
67578
67579       /* Generate the start key.  This is the key that defines the lower
67580       ** bound on the search.  There is no start key if there are no
67581       ** equality terms and if there is no "X>..." term.  In
67582       ** that case, generate a "Rewind" instruction in place of the
67583       ** start key search.
67584       **
67585       ** 2002-Dec-04: In the case of a reverse-order search, the so-called
67586       ** "start" key really ends up being used as the termination key.
67587       */
67588       if( btmLimit ){
67589         Expr *pX;
67590         int k = pIdx->aiColumn[j];
67591         pTerm = findTerm(&wc, iCur, k, notReady, btmOp, pIdx);
67592         assert( pTerm!=0 );
67593         pX = pTerm->pExpr;
67594         assert( (pTerm->flags & TERM_CODED)==0 );
67595         sqlite3ExprCode(pParse, pX->pRight);
67596         sqlite3VdbeAddOp(v, OP_IsNull, -(nEq+1), nxt);
67597         btmEq = pTerm->eOperator & (WO_LE|WO_GE);
67598         disableTerm(pLevel, pTerm);
67599       }else{
67600         btmEq = 1;
67601       }
67602       if( nEq>0 || btmLimit ){
67603         int nCol = nEq + btmLimit;
67604         buildIndexProbe(v, nCol, pIdx);
67605         if( bRev ){
67606           pLevel->iMem = pParse->nMem++;
67607           sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
67608           testOp = OP_IdxLT;
67609         }else{
67610           int op = btmEq ? OP_MoveGe : OP_MoveGt;
67611           sqlite3VdbeAddOp(v, op, iIdxCur, nxt);
67612         }
67613       }else if( bRev ){
67614         testOp = OP_Noop;
67615       }else{
67616         sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, brk);
67617       }
67618
67619       /* Generate the the top of the loop.  If there is a termination
67620       ** key we have to test for that key and abort at the top of the
67621       ** loop.
67622       */
67623       start = sqlite3VdbeCurrentAddr(v);
67624       if( testOp!=OP_Noop ){
67625         sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
67626         sqlite3VdbeAddOp(v, testOp, iIdxCur, nxt);
67627         if( (topEq && !bRev) || (!btmEq && bRev) ){
67628           sqlite3VdbeChangeP3(v, -1, "+", P3_STATIC);
67629         }
67630       }
67631       if( topLimit | btmLimit ){
67632         sqlite3VdbeAddOp(v, OP_Column, iIdxCur, nEq);
67633         sqlite3VdbeAddOp(v, OP_IsNull, 1, cont);
67634       }
67635       if( !omitTable ){
67636         sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
67637         sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
67638       }
67639
67640       /* Record the instruction used to terminate the loop.
67641       */
67642       pLevel->op = bRev ? OP_Prev : OP_Next;
67643       pLevel->p1 = iIdxCur;
67644       pLevel->p2 = start;
67645     }else if( pLevel->flags & WHERE_COLUMN_EQ ){
67646       /* Case 4:  There is an index and all terms of the WHERE clause that
67647       **          refer to the index using the "==" or "IN" operators.
67648       */
67649       int start;
67650       int nEq = pLevel->nEq;
67651
67652       /* Generate code to evaluate all constraint terms using == or IN
67653       ** and leave the values of those terms on the stack.
67654       */
67655       codeAllEqualityTerms(pParse, pLevel, &wc, notReady);
67656       nxt = pLevel->nxt;
67657
67658       /* Generate a single key that will be used to both start and terminate
67659       ** the search
67660       */
67661       buildIndexProbe(v, nEq, pIdx);
67662       sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
67663
67664       /* Generate code (1) to move to the first matching element of the table.
67665       ** Then generate code (2) that jumps to "nxt" after the cursor is past
67666       ** the last matching element of the table.  The code (1) is executed
67667       ** once to initialize the search, the code (2) is executed before each
67668       ** iteration of the scan to see if the scan has finished. */
67669       if( bRev ){
67670         /* Scan in reverse order */
67671         sqlite3VdbeAddOp(v, OP_MoveLe, iIdxCur, nxt);
67672         start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
67673         sqlite3VdbeAddOp(v, OP_IdxLT, iIdxCur, nxt);
67674         pLevel->op = OP_Prev;
67675       }else{
67676         /* Scan in the forward order */
67677         sqlite3VdbeAddOp(v, OP_MoveGe, iIdxCur, nxt);
67678         start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
67679         sqlite3VdbeOp3(v, OP_IdxGE, iIdxCur, nxt, "+", P3_STATIC);
67680         pLevel->op = OP_Next;
67681       }
67682       if( !omitTable ){
67683         sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
67684         sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
67685       }
67686       pLevel->p1 = iIdxCur;
67687       pLevel->p2 = start;
67688     }else{
67689       /* Case 5:  There is no usable index.  We must do a complete
67690       **          scan of the entire table.
67691       */
67692       assert( omitTable==0 );
67693       assert( bRev==0 );
67694       pLevel->op = OP_Next;
67695       pLevel->p1 = iCur;
67696       pLevel->p2 = 1 + sqlite3VdbeAddOp(v, OP_Rewind, iCur, brk);
67697     }
67698     notReady &= ~getMask(&maskSet, iCur);
67699     sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0);
67700
67701     /* Insert code to test every subexpression that can be completely
67702     ** computed using the current set of tables.
67703     */
67704     for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
67705       Expr *pE;
67706       if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
67707       if( (pTerm->prereqAll & notReady)!=0 ) continue;
67708       pE = pTerm->pExpr;
67709       assert( pE!=0 );
67710       if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
67711         continue;
67712       }
67713       sqlite3ExprIfFalse(pParse, pE, cont, 1);
67714       pTerm->flags |= TERM_CODED;
67715     }
67716
67717     /* For a LEFT OUTER JOIN, generate code that will record the fact that
67718     ** at least one row of the right table has matched the left table.  
67719     */
67720     if( pLevel->iLeftJoin ){
67721       pLevel->top = sqlite3VdbeCurrentAddr(v);
67722       sqlite3VdbeAddOp(v, OP_MemInt, 1, pLevel->iLeftJoin);
67723       VdbeComment((v, "# record LEFT JOIN hit"));
67724       for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
67725         if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
67726         if( (pTerm->prereqAll & notReady)!=0 ) continue;
67727         assert( pTerm->pExpr );
67728         sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, 1);
67729         pTerm->flags |= TERM_CODED;
67730       }
67731     }
67732   }
67733
67734 #ifdef SQLITE_TEST  /* For testing and debugging use only */
67735   /* Record in the query plan information about the current table
67736   ** and the index used to access it (if any).  If the table itself
67737   ** is not used, its name is just '{}'.  If no index is used
67738   ** the index is listed as "{}".  If the primary key is used the
67739   ** index name is '*'.
67740   */
67741   for(i=0; i<pTabList->nSrc; i++){
67742     char *z;
67743     int n;
67744     pLevel = &pWInfo->a[i];
67745     pTabItem = &pTabList->a[pLevel->iFrom];
67746     z = pTabItem->zAlias;
67747     if( z==0 ) z = pTabItem->pTab->zName;
67748     n = strlen(z);
67749     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
67750       if( pLevel->flags & WHERE_IDX_ONLY ){
67751         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
67752         nQPlan += 2;
67753       }else{
67754         memcpy(&sqlite3_query_plan[nQPlan], z, n);
67755         nQPlan += n;
67756       }
67757       sqlite3_query_plan[nQPlan++] = ' ';
67758     }
67759     if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
67760       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
67761       nQPlan += 2;
67762     }else if( pLevel->pIdx==0 ){
67763       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
67764       nQPlan += 3;
67765     }else{
67766       n = strlen(pLevel->pIdx->zName);
67767       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
67768         memcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName, n);
67769         nQPlan += n;
67770         sqlite3_query_plan[nQPlan++] = ' ';
67771       }
67772     }
67773   }
67774   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
67775     sqlite3_query_plan[--nQPlan] = 0;
67776   }
67777   sqlite3_query_plan[nQPlan] = 0;
67778   nQPlan = 0;
67779 #endif /* SQLITE_TEST // Testing and debugging use only */
67780
67781   /* Record the continuation address in the WhereInfo structure.  Then
67782   ** clean up and return.
67783   */
67784   pWInfo->iContinue = cont;
67785   whereClauseClear(&wc);
67786   return pWInfo;
67787
67788   /* Jump here if malloc fails */
67789 whereBeginNoMem:
67790   whereClauseClear(&wc);
67791   whereInfoFree(pWInfo);
67792   return 0;
67793 }
67794
67795 /*
67796 ** Generate the end of the WHERE loop.  See comments on 
67797 ** sqlite3WhereBegin() for additional information.
67798 */
67799 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
67800   Vdbe *v = pWInfo->pParse->pVdbe;
67801   int i;
67802   WhereLevel *pLevel;
67803   SrcList *pTabList = pWInfo->pTabList;
67804
67805   /* Generate loop termination code.
67806   */
67807   for(i=pTabList->nSrc-1; i>=0; i--){
67808     pLevel = &pWInfo->a[i];
67809     sqlite3VdbeResolveLabel(v, pLevel->cont);
67810     if( pLevel->op!=OP_Noop ){
67811       sqlite3VdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
67812     }
67813     if( pLevel->nIn ){
67814       struct InLoop *pIn;
67815       int j;
67816       sqlite3VdbeResolveLabel(v, pLevel->nxt);
67817       for(j=pLevel->nIn, pIn=&pLevel->aInLoop[j-1]; j>0; j--, pIn--){
67818         sqlite3VdbeJumpHere(v, pIn->topAddr+1);
67819         sqlite3VdbeAddOp(v, OP_Next, pIn->iCur, pIn->topAddr);
67820         sqlite3VdbeJumpHere(v, pIn->topAddr-1);
67821       }
67822       sqlite3_free(pLevel->aInLoop);
67823     }
67824     sqlite3VdbeResolveLabel(v, pLevel->brk);
67825     if( pLevel->iLeftJoin ){
67826       int addr;
67827       addr = sqlite3VdbeAddOp(v, OP_IfMemPos, pLevel->iLeftJoin, 0);
67828       sqlite3VdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
67829       if( pLevel->iIdxCur>=0 ){
67830         sqlite3VdbeAddOp(v, OP_NullRow, pLevel->iIdxCur, 0);
67831       }
67832       sqlite3VdbeAddOp(v, OP_Goto, 0, pLevel->top);
67833       sqlite3VdbeJumpHere(v, addr);
67834     }
67835   }
67836
67837   /* The "break" point is here, just past the end of the outer loop.
67838   ** Set it.
67839   */
67840   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
67841
67842   /* Close all of the cursors that were opened by sqlite3WhereBegin.
67843   */
67844   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
67845     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
67846     Table *pTab = pTabItem->pTab;
67847     assert( pTab!=0 );
67848     if( pTab->isEphem || pTab->pSelect ) continue;
67849     if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
67850       sqlite3VdbeAddOp(v, OP_Close, pTabItem->iCursor, 0);
67851     }
67852     if( pLevel->pIdx!=0 ){
67853       sqlite3VdbeAddOp(v, OP_Close, pLevel->iIdxCur, 0);
67854     }
67855
67856     /* If this scan uses an index, make code substitutions to read data
67857     ** from the index in preference to the table. Sometimes, this means
67858     ** the table need never be read from. This is a performance boost,
67859     ** as the vdbe level waits until the table is read before actually
67860     ** seeking the table cursor to the record corresponding to the current
67861     ** position in the index.
67862     ** 
67863     ** Calls to the code generator in between sqlite3WhereBegin and
67864     ** sqlite3WhereEnd will have created code that references the table
67865     ** directly.  This loop scans all that code looking for opcodes
67866     ** that reference the table and converts them into opcodes that
67867     ** reference the index.
67868     */
67869     if( pLevel->pIdx ){
67870       int k, j, last;
67871       VdbeOp *pOp;
67872       Index *pIdx = pLevel->pIdx;
67873       int useIndexOnly = pLevel->flags & WHERE_IDX_ONLY;
67874
67875       assert( pIdx!=0 );
67876       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
67877       last = sqlite3VdbeCurrentAddr(v);
67878       for(k=pWInfo->iTop; k<last; k++, pOp++){
67879         if( pOp->p1!=pLevel->iTabCur ) continue;
67880         if( pOp->opcode==OP_Column ){
67881           for(j=0; j<pIdx->nColumn; j++){
67882             if( pOp->p2==pIdx->aiColumn[j] ){
67883               pOp->p2 = j;
67884               pOp->p1 = pLevel->iIdxCur;
67885               break;
67886             }
67887           }
67888           assert(!useIndexOnly || j<pIdx->nColumn);
67889         }else if( pOp->opcode==OP_Rowid ){
67890           pOp->p1 = pLevel->iIdxCur;
67891           pOp->opcode = OP_IdxRowid;
67892         }else if( pOp->opcode==OP_NullRow && useIndexOnly ){
67893           pOp->opcode = OP_Noop;
67894         }
67895       }
67896     }
67897   }
67898
67899   /* Final cleanup
67900   */
67901   whereInfoFree(pWInfo);
67902   return;
67903 }
67904
67905 /************** End of where.c ***********************************************/
67906 /************** Begin file parse.c *******************************************/
67907 /* Driver template for the LEMON parser generator.
67908 ** The author disclaims copyright to this source code.
67909 */
67910 /* First off, code is include which follows the "include" declaration
67911 ** in the input file. */
67912
67913
67914 /*
67915 ** An instance of this structure holds information about the
67916 ** LIMIT clause of a SELECT statement.
67917 */
67918 struct LimitVal {
67919   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
67920   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
67921 };
67922
67923 /*
67924 ** An instance of this structure is used to store the LIKE,
67925 ** GLOB, NOT LIKE, and NOT GLOB operators.
67926 */
67927 struct LikeOp {
67928   Token eOperator;  /* "like" or "glob" or "regexp" */
67929   int not;         /* True if the NOT keyword is present */
67930 };
67931
67932 /*
67933 ** An instance of the following structure describes the event of a
67934 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
67935 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
67936 **
67937 **      UPDATE ON (a,b,c)
67938 **
67939 ** Then the "b" IdList records the list "a,b,c".
67940 */
67941 struct TrigEvent { int a; IdList * b; };
67942
67943 /*
67944 ** An instance of this structure holds the ATTACH key and the key type.
67945 */
67946 struct AttachKey { int type;  Token key; };
67947
67948 /* Next is all token values, in a form suitable for use by makeheaders.
67949 ** This section will be null unless lemon is run with the -m switch.
67950 */
67951 /* 
67952 ** These constants (all generated automatically by the parser generator)
67953 ** specify the various kinds of tokens (terminals) that the parser
67954 ** understands. 
67955 **
67956 ** Each symbol here is a terminal symbol in the grammar.
67957 */
67958 /* Make sure the INTERFACE macro is defined.
67959 */
67960 #ifndef INTERFACE
67961 # define INTERFACE 1
67962 #endif
67963 /* The next thing included is series of defines which control
67964 ** various aspects of the generated parser.
67965 **    YYCODETYPE         is the data type used for storing terminal
67966 **                       and nonterminal numbers.  "unsigned char" is
67967 **                       used if there are fewer than 250 terminals
67968 **                       and nonterminals.  "int" is used otherwise.
67969 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
67970 **                       to no legal terminal or nonterminal number.  This
67971 **                       number is used to fill in empty slots of the hash 
67972 **                       table.
67973 **    YYFALLBACK         If defined, this indicates that one or more tokens
67974 **                       have fall-back values which should be used if the
67975 **                       original value of the token will not parse.
67976 **    YYACTIONTYPE       is the data type used for storing terminal
67977 **                       and nonterminal numbers.  "unsigned char" is
67978 **                       used if there are fewer than 250 rules and
67979 **                       states combined.  "int" is used otherwise.
67980 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
67981 **                       directly to the parser from the tokenizer.
67982 **    YYMINORTYPE        is the data type used for all minor tokens.
67983 **                       This is typically a union of many types, one of
67984 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
67985 **                       for base tokens is called "yy0".
67986 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
67987 **                       zero the stack is dynamically sized using realloc()
67988 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
67989 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
67990 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
67991 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
67992 **    YYNSTATE           the combined number of states.
67993 **    YYNRULE            the number of rules in the grammar
67994 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
67995 **                       defined, then do no error processing.
67996 */
67997 #define YYCODETYPE unsigned char
67998 #define YYNOCODE 248
67999 #define YYACTIONTYPE unsigned short int
68000 #define YYWILDCARD 59
68001 #define sqlite3ParserTOKENTYPE Token
68002 typedef union {
68003   sqlite3ParserTOKENTYPE yy0;
68004   int yy46;
68005   struct LikeOp yy72;
68006   Expr* yy172;
68007   ExprList* yy174;
68008   Select* yy219;
68009   struct LimitVal yy234;
68010   TriggerStep* yy243;
68011   struct TrigEvent yy370;
68012   SrcList* yy373;
68013   Expr * yy386;
68014   struct {int value; int mask;} yy405;
68015   Token yy410;
68016   IdList* yy432;
68017   int yy495;
68018 } YYMINORTYPE;
68019 #ifndef YYSTACKDEPTH
68020 #define YYSTACKDEPTH 100
68021 #endif
68022 #define sqlite3ParserARG_SDECL Parse *pParse;
68023 #define sqlite3ParserARG_PDECL ,Parse *pParse
68024 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
68025 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
68026 #define YYNSTATE 588
68027 #define YYNRULE 312
68028 #define YYERRORSYMBOL 138
68029 #define YYERRSYMDT yy495
68030 #define YYFALLBACK 1
68031 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
68032 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
68033 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
68034
68035 /* Next are that tables used to determine what action to take based on the
68036 ** current state and lookahead token.  These tables are used to implement
68037 ** functions that take a state number and lookahead value and return an
68038 ** action integer.  
68039 **
68040 ** Suppose the action integer is N.  Then the action is determined as
68041 ** follows
68042 **
68043 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
68044 **                                      token onto the stack and goto state N.
68045 **
68046 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
68047 **
68048 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
68049 **
68050 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
68051 **
68052 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
68053 **                                      slots in the yy_action[] table.
68054 **
68055 ** The action table is constructed as a single large table named yy_action[].
68056 ** Given state S and lookahead X, the action is computed as
68057 **
68058 **      yy_action[ yy_shift_ofst[S] + X ]
68059 **
68060 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
68061 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
68062 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
68063 ** and that yy_default[S] should be used instead.  
68064 **
68065 ** The formula above is for computing the action when the lookahead is
68066 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
68067 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
68068 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
68069 ** YY_SHIFT_USE_DFLT.
68070 **
68071 ** The following are the tables generated in this section:
68072 **
68073 **  yy_action[]        A single table containing all actions.
68074 **  yy_lookahead[]     A table containing the lookahead for each entry in
68075 **                     yy_action.  Used to detect hash collisions.
68076 **  yy_shift_ofst[]    For each state, the offset into yy_action for
68077 **                     shifting terminals.
68078 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
68079 **                     shifting non-terminals after a reduce.
68080 **  yy_default[]       Default action for each state.
68081 */
68082 static const YYACTIONTYPE yy_action[] = {
68083  /*     0 */   299,  901,  124,  587,  416,  174,    2,  425,   61,   61,
68084  /*    10 */    61,   61,  297,   63,   63,   63,   63,   64,   64,   65,
68085  /*    20 */    65,   65,   66,  212,  454,  214,  432,  438,   68,   63,
68086  /*    30 */    63,   63,   63,   64,   64,   65,   65,   65,   66,  212,
68087  /*    40 */   398,  395,  403,  458,   60,   59,  304,  442,  443,  439,
68088  /*    50 */   439,   62,   62,   61,   61,   61,   61,  265,   63,   63,
68089  /*    60 */    63,   63,   64,   64,   65,   65,   65,   66,  212,  299,
68090  /*    70 */   500,  501,  425,  496,  210,   82,   67,  427,   69,  156,
68091  /*    80 */    63,   63,   63,   63,   64,   64,   65,   65,   65,   66,
68092  /*    90 */   212,   67,  469,   69,  156,  432,  438,  573,  266,   58,
68093  /*   100 */    64,   64,   65,   65,   65,   66,  212,  404,  405,  429,
68094  /*   110 */   429,  429,  299,   60,   59,  304,  442,  443,  439,  439,
68095  /*   120 */    62,   62,   61,   61,   61,   61,  324,   63,   63,   63,
68096  /*   130 */    63,   64,   64,   65,   65,   65,   66,  212,  432,  438,
68097  /*   140 */    94,   65,   65,   65,   66,  212,  403,  212,  421,   34,
68098  /*   150 */    56,  305,  449,  450,  417,  481,   60,   59,  304,  442,
68099  /*   160 */   443,  439,  439,   62,   62,   61,   61,   61,   61,  495,
68100  /*   170 */    63,   63,   63,   63,   64,   64,   65,   65,   65,   66,
68101  /*   180 */   212,  299,  259,  524,  203,  571,  113,  415,  522,  458,
68102  /*   190 */   338,  324,  414,   20,  241,  347,  297,  403,  471,  531,
68103  /*   200 */   292,  454,  214,  570,  569,  472,  530,  432,  438,  151,
68104  /*   210 */   152,  404,  405,  421,   41,  213,  153,  533,  422,  496,
68105  /*   220 */   263,  568,  261,  427,  299,   60,   59,  304,  442,  443,
68106  /*   230 */   439,  439,   62,   62,   61,   61,   61,   61,  324,   63,
68107  /*   240 */    63,   63,   63,   64,   64,   65,   65,   65,   66,  212,
68108  /*   250 */   432,  438,  454,  340,  217,  429,  429,  429,  219,  550,
68109  /*   260 */   421,   41,  404,  405,  490,  567,  213,  299,   60,   59,
68110  /*   270 */   304,  442,  443,  439,  439,   62,   62,   61,   61,   61,
68111  /*   280 */    61,  652,   63,   63,   63,   63,   64,   64,   65,   65,
68112  /*   290 */    65,   66,  212,  432,  438,  103,  652,  549,  524,  519,
68113  /*   300 */   652,  216,  652,   67,  231,   69,  156,  534,   20,   66,
68114  /*   310 */   212,   60,   59,  304,  442,  443,  439,  439,   62,   62,
68115  /*   320 */    61,   61,   61,   61,  265,   63,   63,   63,   63,   64,
68116  /*   330 */    64,   65,   65,   65,   66,  212,  654,  324,  288,   77,
68117  /*   340 */   299,  456,  523,  170,  491,  155,  232,  380,  271,  270,
68118  /*   350 */   327,  654,  445,  445,  485,  654,  485,  654,  210,  421,
68119  /*   360 */    27,  456,  330,  170,  652,  391,  432,  438,  497,  425,
68120  /*   370 */   652,  652,  652,  652,  652,  652,  652,  252,  654,  422,
68121  /*   380 */   581,  291,   80,  652,   60,   59,  304,  442,  443,  439,
68122  /*   390 */   439,   62,   62,   61,   61,   61,   61,  210,   63,   63,
68123  /*   400 */    63,   63,   64,   64,   65,   65,   65,   66,  212,  299,
68124  /*   410 */   379,  585,  892,  494,  892,  306,  393,  368,  324,  654,
68125  /*   420 */    21,  324,  307,  324,  425,  654,  654,  654,  654,  654,
68126  /*   430 */   654,  654,  571,  654,  425,  432,  438,  532,  654,  654,
68127  /*   440 */   421,   49,  485,  421,   35,  421,   49,  329,  449,  450,
68128  /*   450 */   570,  582,  348,   60,   59,  304,  442,  443,  439,  439,
68129  /*   460 */    62,   62,   61,   61,   61,   61,  655,   63,   63,   63,
68130  /*   470 */    63,   64,   64,   65,   65,   65,   66,  212,  299,  420,
68131  /*   480 */   198,  655,  509,  419,  324,  655,  315,  655,  653,  425,
68132  /*   490 */   223,  316,  653,  525,  653,  238,  166,  118,  245,  350,
68133  /*   500 */   250,  351,  178,  314,  432,  438,  421,   34,  655,  254,
68134  /*   510 */   239,  213,  389,  213,  422,  653,  588,  398,  395,  406,
68135  /*   520 */   407,  408,   60,   59,  304,  442,  443,  439,  439,   62,
68136  /*   530 */    62,   61,   61,   61,   61,  335,   63,   63,   63,   63,
68137  /*   540 */    64,   64,   65,   65,   65,   66,  212,  299,  342,  655,
68138  /*   550 */   307,  257,  463,  547,  501,  655,  655,  655,  655,  655,
68139  /*   560 */   655,  655,  653,  655,  464,  653,  653,  653,  655,  655,
68140  /*   570 */   653,  161,  498,  432,  438,  653,  653,  465,    1,  502,
68141  /*   580 */   544,  418,  403,  585,  891,  176,  891,  343,  174,  503,
68142  /*   590 */   425,   60,   59,  304,  442,  443,  439,  439,   62,   62,
68143  /*   600 */    61,   61,   61,   61,  240,   63,   63,   63,   63,   64,
68144  /*   610 */    64,   65,   65,   65,   66,  212,  299,  381,  223,  422,
68145  /*   620 */     9,   93,  377,  582,  403,  118,  245,  350,  250,  351,
68146  /*   630 */   178,  177,  162,  325,  403,  183,  345,  254,  352,  355,
68147  /*   640 */   356,  227,  432,  438,  446,  320,  399,  404,  405,  357,
68148  /*   650 */   459,  209,  540,  367,  540,  425,  546,  302,  202,  299,
68149  /*   660 */    60,   59,  304,  442,  443,  439,  439,   62,   62,   61,
68150  /*   670 */    61,   61,   61,  402,   63,   63,   63,   63,   64,   64,
68151  /*   680 */    65,   65,   65,   66,  212,  432,  438,  225,  524,  404,
68152  /*   690 */   405,  489,  422,  397,   18,  824,    2,  578,   20,  404,
68153  /*   700 */   405,  194,  299,   60,   59,  304,  442,  443,  439,  439,
68154  /*   710 */    62,   62,   61,   61,   61,   61,  386,   63,   63,   63,
68155  /*   720 */    63,   64,   64,   65,   65,   65,   66,  212,  432,  438,
68156  /*   730 */   327,  370,  445,  445,  481,  422,  327,  373,  445,  445,
68157  /*   740 */   275,  519,  519,    8,  394,  299,   60,   70,  304,  442,
68158  /*   750 */   443,  439,  439,   62,   62,   61,   61,   61,   61,  378,
68159  /*   760 */    63,   63,   63,   63,   64,   64,   65,   65,   65,   66,
68160  /*   770 */   212,  432,  438,  243,  211,  167,  310,  224,  278,  196,
68161  /*   780 */   276,   55,  374,  519,  180,  181,  182,  519,  299,  119,
68162  /*   790 */    59,  304,  442,  443,  439,  439,   62,   62,   61,   61,
68163  /*   800 */    61,   61,  646,   63,   63,   63,   63,   64,   64,   65,
68164  /*   810 */    65,   65,   66,  212,  432,  438,  403,  646,  311,  253,
68165  /*   820 */   253,  646,  312,  646,  327,    5,  445,  445,  481,  542,
68166  /*   830 */   154,  519,  474,  541,  304,  442,  443,  439,  439,   62,
68167  /*   840 */    62,   61,   61,   61,   61,  369,   63,   63,   63,   63,
68168  /*   850 */    64,   64,   65,   65,   65,   66,  212,   72,  331,  277,
68169  /*   860 */     4,  253,  377,  428,  303,  253,  313,  487,  622,  173,
68170  /*   870 */   162,  455,  328,   72,  331,  265,    4,  265,   84,  158,
68171  /*   880 */   303,  404,  405,  265,   67,  646,   69,  156,  328,  333,
68172  /*   890 */   360,  646,  646,  646,  646,  646,  646,  646,  183,  458,
68173  /*   900 */   185,  352,  355,  356,  646,  333,  388,  477,  188,  253,
68174  /*   910 */   433,  434,  357,  422,  463,  458,  557,  179,  559,   75,
68175  /*   920 */    74,  336,  403,  147,  560,  210,  464,  226,   73,  322,
68176  /*   930 */   323,  436,  437,  427,  422,   75,   74,  488,  387,  465,
68177  /*   940 */   475,  334,  422,  512,   73,  322,  323,   72,  331,  427,
68178  /*   950 */     4,  210,  467,  324,  303,  318,  123,   19,  480,  144,
68179  /*   960 */   435,  157,  328,  513,  484,  429,  429,  429,  430,  431,
68180  /*   970 */    11,  346,  301,  452,  452,  421,   34,  254,  324,  333,
68181  /*   980 */   251,  429,  429,  429,  430,  431,   11,  404,  405,  458,
68182  /*   990 */   265,  164,  293,  421,    3,  422,  228,  229,  230,  104,
68183  /*  1000 */   421,   28,  324,  403,  294,  324,  265,  265,  265,   75,
68184  /*  1010 */    74,  656,  207,  478,  283,  309,  179,  338,   73,  322,
68185  /*  1020 */   323,  284,  337,  427,  421,   23,  656,  421,   32,  324,
68186  /*  1030 */   656,  561,  656,  205,  420,  549,  326,  526,  419,  204,
68187  /*  1040 */   324,  128,  206,  324,  476,  511,  510,  279,  385,  281,
68188  /*  1050 */   514,  421,   53,  656,  515,  429,  429,  429,  430,  431,
68189  /*  1060 */    11,  649,  421,   52,  258,  421,   98,  324,  404,  405,
68190  /*  1070 */   183,  301,  260,  352,  355,  356,  649,   76,  650,   78,
68191  /*  1080 */   649,  246,  649,  262,  357,  384,  280,  270,  264,  421,
68192  /*  1090 */    96,  300,  247,  650,  656,  324,  210,  650,  191,  650,
68193  /*  1100 */   656,  656,  656,  656,  656,  656,  656,  653,  656,  324,
68194  /*  1110 */   364,  160,  440,  656,  656,  324,  295,  421,  101,  324,
68195  /*  1120 */   390,  583,  653,  324,  269,  324,  653,  447,  653,   22,
68196  /*  1130 */   372,  421,  102,  412,  375,  324,  476,  421,  112,  376,
68197  /*  1140 */   272,  421,  114,  324,  649,  421,   16,  421,   99,  653,
68198  /*  1150 */   649,  649,  649,  649,  649,  649,  649,  421,   33,  324,
68199  /*  1160 */   584,  650,  324,  649,  273,  421,   97,  650,  650,  650,
68200  /*  1170 */   650,  650,  650,  650,  483,  274,  175,  506,  507,  556,
68201  /*  1180 */   650,  421,   24,  324,  421,   54,  566,  516,  324,  128,
68202  /*  1190 */   653,  324,  256,  359,  128,  128,  653,  653,  653,  653,
68203  /*  1200 */   653,  653,  653,  324,  653,  421,  115,  146,  324,  653,
68204  /*  1210 */   421,  116,  282,  421,  117,  324,  545,  324,  128,  285,
68205  /*  1220 */   553,  324,  175,  324,  233,  421,   25,  554,  324,   91,
68206  /*  1230 */   421,   36,  324,  286,  324,  577,  426,  421,   37,  421,
68207  /*  1240 */    26,  324,  451,  421,   38,  421,   39,  324,  332,  324,
68208  /*  1250 */   421,   40,  324,  453,  421,   42,  421,   43,  564,  292,
68209  /*  1260 */    91,  324,  470,  421,   44,  324,  580,  324,  290,  421,
68210  /*  1270 */    29,  421,   30,  324,  421,   45,  324,  518,  298,  324,
68211  /*  1280 */   473,  248,  517,  421,   46,  324,  354,  421,   47,  421,
68212  /*  1290 */    48,  520,  552,  563,  165,  421,   31,  401,  421,   10,
68213  /*  1300 */     7,  421,   50,  409,  410,  411,  321,  421,   51,   84,
68214  /*  1310 */   423,  341,  237,   83,  339,   57,  234,   79,  235,  215,
68215  /*  1320 */   236,  172,   85,  424,  349,  344,  468,  125,  505,  308,
68216  /*  1330 */   295,  242,  499,  482,  244,  504,  486,  249,  508,  296,
68217  /*  1340 */   105,  221,  521,  149,  361,  150,  365,  527,  528,  529,
68218  /*  1350 */   186,   88,  121,  535,  187,  132,  363,  189,  142,  220,
68219  /*  1360 */   222,  383,  141,  190,  537,  192,  548,  371,  195,  267,
68220  /*  1370 */   382,  538,  133,  555,  562,  317,  134,  135,  136,   92,
68221  /*  1380 */   574,  138,   95,  575,  576,  579,  111,  100,  400,  319,
68222  /*  1390 */   122,   17,  413,  623,  624,  168,  169,  441,  444,   71,
68223  /*  1400 */   460,  448,  457,  143,  159,  171,  461,    6,  462,  479,
68224  /*  1410 */   466,   13,  126,   81,   12,  127,  163,  492,  493,  218,
68225  /*  1420 */    86,  353,  106,  358,  255,  107,  120,   87,  108,  184,
68226  /*  1430 */   247,  362,  145,  536,  175,  129,  366,  193,  109,  268,
68227  /*  1440 */   289,  551,  131,   14,  130,  197,   89,  539,  199,  201,
68228  /*  1450 */   543,  200,  139,  558,  137,  565,  110,   15,  287,  572,
68229  /*  1460 */   140,  208,  148,  396,  392,  586,  902,  902,  902,  902,
68230  /*  1470 */    90,
68231 };
68232 static const YYCODETYPE yy_lookahead[] = {
68233  /*     0 */    16,  139,  140,  141,  168,   21,  144,   23,   69,   70,
68234  /*    10 */    71,   72,  176,   74,   75,   76,   77,   78,   79,   80,
68235  /*    20 */    81,   82,   83,   84,   78,   79,   42,   43,   73,   74,
68236  /*    30 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   84,
68237  /*    40 */     1,    2,   23,   58,   60,   61,   62,   63,   64,   65,
68238  /*    50 */    66,   67,   68,   69,   70,   71,   72,  147,   74,   75,
68239  /*    60 */    76,   77,   78,   79,   80,   81,   82,   83,   84,   16,
68240  /*    70 */   185,  186,   88,   88,  110,   22,  217,   92,  219,  220,
68241  /*    80 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
68242  /*    90 */    84,  217,  218,  219,  220,   42,   43,  238,  188,   46,
68243  /*   100 */    78,   79,   80,   81,   82,   83,   84,   88,   89,  124,
68244  /*   110 */   125,  126,   16,   60,   61,   62,   63,   64,   65,   66,
68245  /*   120 */    67,   68,   69,   70,   71,   72,  147,   74,   75,   76,
68246  /*   130 */    77,   78,   79,   80,   81,   82,   83,   84,   42,   43,
68247  /*   140 */    44,   80,   81,   82,   83,   84,   23,   84,  169,  170,
68248  /*   150 */    19,  164,  165,  166,   23,  161,   60,   61,   62,   63,
68249  /*   160 */    64,   65,   66,   67,   68,   69,   70,   71,   72,  169,
68250  /*   170 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
68251  /*   180 */    84,   16,   14,  147,  155,  147,   21,  167,  168,   58,
68252  /*   190 */   211,  147,  156,  157,  200,  216,  176,   23,   27,  176,
68253  /*   200 */   177,   78,   79,  165,  166,   34,  183,   42,   43,   78,
68254  /*   210 */    79,   88,   89,  169,  170,  228,  180,  181,  189,   88,
68255  /*   220 */    52,   98,   54,   92,   16,   60,   61,   62,   63,   64,
68256  /*   230 */    65,   66,   67,   68,   69,   70,   71,   72,  147,   74,
68257  /*   240 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   84,
68258  /*   250 */    42,   43,   78,  209,  210,  124,  125,  126,  175,   11,
68259  /*   260 */   169,  170,   88,   89,   20,  227,  228,   16,   60,   61,
68260  /*   270 */    62,   63,   64,   65,   66,   67,   68,   69,   70,   71,
68261  /*   280 */    72,    1,   74,   75,   76,   77,   78,   79,   80,   81,
68262  /*   290 */    82,   83,   84,   42,   43,  175,   16,   49,  147,  147,
68263  /*   300 */    20,  210,   22,  217,  153,  219,  220,  156,  157,   83,
68264  /*   310 */    84,   60,   61,   62,   63,   64,   65,   66,   67,   68,
68265  /*   320 */    69,   70,   71,   72,  147,   74,   75,   76,   77,   78,
68266  /*   330 */    79,   80,   81,   82,   83,   84,    1,  147,  158,  131,
68267  /*   340 */    16,  161,  162,  163,   20,  155,  190,   99,  100,  101,
68268  /*   350 */   106,   16,  108,  109,  147,   20,  147,   22,  110,  169,
68269  /*   360 */   170,  161,  162,  163,   84,  188,   42,   43,  169,   23,
68270  /*   370 */    90,   91,   92,   93,   94,   95,   96,  225,   43,  189,
68271  /*   380 */   244,  245,  131,  103,   60,   61,   62,   63,   64,   65,
68272  /*   390 */    66,   67,   68,   69,   70,   71,   72,  110,   74,   75,
68273  /*   400 */    76,   77,   78,   79,   80,   81,   82,   83,   84,   16,
68274  /*   410 */   123,   19,   20,   20,   22,  208,  239,  208,  147,   84,
68275  /*   420 */    19,  147,   16,  147,   23,   90,   91,   92,   93,   94,
68276  /*   430 */    95,   96,  147,   98,   88,   42,   43,  181,  103,  104,
68277  /*   440 */   169,  170,  147,  169,  170,  169,  170,  164,  165,  166,
68278  /*   450 */   165,   59,   80,   60,   61,   62,   63,   64,   65,   66,
68279  /*   460 */    67,   68,   69,   70,   71,   72,    1,   74,   75,   76,
68280  /*   470 */    77,   78,   79,   80,   81,   82,   83,   84,   16,  107,
68281  /*   480 */   155,   16,   20,  111,  147,   20,  215,   22,   16,   88,
68282  /*   490 */    84,  215,   20,  181,   22,  221,   90,   91,   92,   93,
68283  /*   500 */    94,   95,   96,  208,   42,   43,  169,  170,   43,  103,
68284  /*   510 */   147,  228,  227,  228,  189,   43,    0,    1,    2,    7,
68285  /*   520 */     8,    9,   60,   61,   62,   63,   64,   65,   66,   67,
68286  /*   530 */    68,   69,   70,   71,   72,  186,   74,   75,   76,   77,
68287  /*   540 */    78,   79,   80,   81,   82,   83,   84,   16,  211,   84,
68288  /*   550 */    16,   20,   12,  185,  186,   90,   91,   92,   93,   94,
68289  /*   560 */    95,   96,   90,   98,   24,   93,   94,   95,  103,  104,
68290  /*   570 */    98,  147,  160,   42,   43,  103,  104,   37,   19,   39,
68291  /*   580 */    18,  169,   23,   19,   20,  155,   22,  147,   21,   49,
68292  /*   590 */    23,   60,   61,   62,   63,   64,   65,   66,   67,   68,
68293  /*   600 */    69,   70,   71,   72,  147,   74,   75,   76,   77,   78,
68294  /*   610 */    79,   80,   81,   82,   83,   84,   16,   55,   84,  189,
68295  /*   620 */    19,   21,  147,   59,   23,   91,   92,   93,   94,   95,
68296  /*   630 */    96,  201,  202,  147,   23,   90,  206,  103,   93,   94,
68297  /*   640 */    95,  145,   42,   43,   20,  142,  143,   88,   89,  104,
68298  /*   650 */    20,  148,   99,  100,  101,   88,   94,  150,  155,   16,
68299  /*   660 */    60,   61,   62,   63,   64,   65,   66,   67,   68,   69,
68300  /*   670 */    70,   71,   72,  147,   74,   75,   76,   77,   78,   79,
68301  /*   680 */    80,   81,   82,   83,   84,   42,   43,  212,  147,   88,
68302  /*   690 */    89,   80,  189,  141,   19,  133,  144,  156,  157,   88,
68303  /*   700 */    89,  155,   16,   60,   61,   62,   63,   64,   65,   66,
68304  /*   710 */    67,   68,   69,   70,   71,   72,  213,   74,   75,   76,
68305  /*   720 */    77,   78,   79,   80,   81,   82,   83,   84,   42,   43,
68306  /*   730 */   106,  224,  108,  109,  161,  189,  106,  230,  108,  109,
68307  /*   740 */    14,  147,  147,   68,  241,   16,   60,   61,   62,   63,
68308  /*   750 */    64,   65,   66,   67,   68,   69,   70,   71,   72,  213,
68309  /*   760 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
68310  /*   770 */    84,   42,   43,  200,  192,   19,  182,  182,   52,   22,
68311  /*   780 */    54,  199,  236,  147,   99,  100,  101,  147,   16,  147,
68312  /*   790 */    61,   62,   63,   64,   65,   66,   67,   68,   69,   70,
68313  /*   800 */    71,   72,    1,   74,   75,   76,   77,   78,   79,   80,
68314  /*   810 */    81,   82,   83,   84,   42,   43,   23,   16,  182,  225,
68315  /*   820 */   225,   20,  182,   22,  106,  191,  108,  109,  161,   25,
68316  /*   830 */    22,  147,   22,   29,   62,   63,   64,   65,   66,   67,
68317  /*   840 */    68,   69,   70,   71,   72,   41,   74,   75,   76,   77,
68318  /*   850 */    78,   79,   80,   81,   82,   83,   84,   16,   17,  133,
68319  /*   860 */    19,  225,  147,  147,   23,  225,  182,  200,  112,  201,
68320  /*   870 */   202,  161,   31,   16,   17,  147,   19,  147,  121,  155,
68321  /*   880 */    23,   88,   89,  147,  217,   84,  219,  220,   31,   48,
68322  /*   890 */    16,   90,   91,   92,   93,   94,   95,   96,   90,   58,
68323  /*   900 */   155,   93,   94,   95,  103,   48,   91,  114,  155,  225,
68324  /*   910 */    42,   43,  104,  189,   12,   58,  188,   43,  188,   78,
68325  /*   920 */    79,  147,   23,  113,  188,  110,   24,  212,   87,   88,
68326  /*   930 */    89,   63,   64,   92,  189,   78,   79,   80,  123,   37,
68327  /*   940 */   203,   39,  189,   30,   87,   88,   89,   16,   17,   92,
68328  /*   950 */    19,  110,  147,  147,   23,  242,  243,   19,  147,   21,
68329  /*   960 */    92,  155,   31,   50,  147,  124,  125,  126,  127,  128,
68330  /*   970 */   129,  147,   98,  124,  125,  169,  170,  103,  147,   48,
68331  /*   980 */   147,  124,  125,  126,  127,  128,  129,   88,   89,   58,
68332  /*   990 */   147,    5,  147,  169,  170,  189,   10,   11,   12,   13,
68333  /*  1000 */   169,  170,  147,   23,  178,  147,  147,  147,  147,   78,
68334  /*  1010 */    79,    1,   26,  114,   28,  102,   43,  211,   87,   88,
68335  /*  1020 */    89,   35,  216,   92,  169,  170,   16,  169,  170,  147,
68336  /*  1030 */    20,  188,   22,   47,  107,   49,   16,  147,  111,   53,
68337  /*  1040 */   147,   22,   56,  147,   22,   91,   92,  188,  188,  188,
68338  /*  1050 */   178,  169,  170,   43,  178,  124,  125,  126,  127,  128,
68339  /*  1060 */   129,    1,  169,  170,  147,  169,  170,  147,   88,   89,
68340  /*  1070 */    90,   98,  147,   93,   94,   95,   16,  130,    1,  132,
68341  /*  1080 */    20,   92,   22,  147,  104,   99,  100,  101,  147,  169,
68342  /*  1090 */   170,  105,  103,   16,   84,  147,  110,   20,  232,   22,
68343  /*  1100 */    90,   91,   92,   93,   94,   95,   96,    1,   98,  147,
68344  /*  1110 */   233,   89,   92,  103,  104,  147,   97,  169,  170,  147,
68345  /*  1120 */   134,   20,   16,  147,  147,  147,   20,   20,   22,   22,
68346  /*  1130 */   147,  169,  170,  149,  147,  147,  114,  169,  170,  147,
68347  /*  1140 */   147,  169,  170,  147,   84,  169,  170,  169,  170,   43,
68348  /*  1150 */    90,   91,   92,   93,   94,   95,   96,  169,  170,  147,
68349  /*  1160 */    59,   84,  147,  103,  147,  169,  170,   90,   91,   92,
68350  /*  1170 */    93,   94,   95,   96,   20,  147,   22,    7,    8,  147,
68351  /*  1180 */   103,  169,  170,  147,  169,  170,  147,   20,  147,   22,
68352  /*  1190 */    84,  147,   20,   20,   22,   22,   90,   91,   92,   93,
68353  /*  1200 */    94,   95,   96,  147,   98,  169,  170,  191,  147,  103,
68354  /*  1210 */   169,  170,  147,  169,  170,  147,   20,  147,   22,  147,
68355  /*  1220 */    20,  147,   22,  147,  193,  169,  170,   20,  147,   22,
68356  /*  1230 */   169,  170,  147,  147,  147,  147,  161,  169,  170,  169,
68357  /*  1240 */   170,  147,  229,  169,  170,  169,  170,  147,  223,  147,
68358  /*  1250 */   169,  170,  147,  229,  169,  170,  169,  170,   20,  177,
68359  /*  1260 */    22,  147,  172,  169,  170,  147,   20,  147,   22,  169,
68360  /*  1270 */   170,  169,  170,  147,  169,  170,  147,  161,  161,  147,
68361  /*  1280 */   172,  172,  172,  169,  170,  147,  173,  169,  170,  169,
68362  /*  1290 */   170,  172,  194,  194,    6,  169,  170,  146,  169,  170,
68363  /*  1300 */    22,  169,  170,  146,  146,  146,  154,  169,  170,  121,
68364  /*  1310 */   189,  118,  197,  119,  116,  120,  194,  130,  195,  222,
68365  /*  1320 */   196,  112,   98,  198,   98,  115,  152,  152,  179,   40,
68366  /*  1330 */    97,  204,  171,  205,  204,  171,  205,  171,  173,  171,
68367  /*  1340 */    19,   84,  179,  174,   15,  174,   38,  171,  171,  171,
68368  /*  1350 */   151,  130,   60,  152,  151,   19,  152,  151,  214,  226,
68369  /*  1360 */   226,   15,  214,  152,  152,  151,  184,  152,  184,  234,
68370  /*  1370 */   152,  235,  187,  194,  194,  152,  187,  187,  187,  237,
68371  /*  1380 */    33,  184,  237,  152,  152,  137,  240,  159,    1,  246,
68372  /*  1390 */   243,  231,   20,  112,  112,  112,  112,   92,  107,   19,
68373  /*  1400 */    11,   20,   20,   19,   19,   22,   20,  117,   20,  114,
68374  /*  1410 */    20,  117,   19,   22,   22,   20,  112,   20,   20,   44,
68375  /*  1420 */    19,   44,   19,   44,   20,   19,   32,   19,   19,   96,
68376  /*  1430 */   103,   16,   21,   17,   22,   98,   36,   98,   19,  133,
68377  /*  1440 */     5,    1,  102,   19,   45,  122,   68,   51,  113,  115,
68378  /*  1450 */    45,   14,  102,   17,  113,  123,   14,   19,  136,   20,
68379  /*  1460 */   122,  135,   19,    3,   57,    4,  247,  247,  247,  247,
68380  /*  1470 */    68,
68381 };
68382 #define YY_SHIFT_USE_DFLT (-62)
68383 #define YY_SHIFT_MAX 396
68384 static const short yy_shift_ofst[] = {
68385  /*     0 */    39,  841,  986,  -16,  841,  931,  931,  980,  123,  -36,
68386  /*    10 */    96,  931,  931,  931,  931,  931,  -45,  248,  174,   19,
68387  /*    20 */   346,  -54,  -54,   53,  165,  208,  251,  324,  393,  462,
68388  /*    30 */   531,  600,  643,  686,  643,  643,  643,  643,  643,  643,
68389  /*    40 */   643,  643,  643,  643,  643,  643,  643,  643,  643,  643,
68390  /*    50 */   643,  643,  729,  772,  772,  857,  931,  931,  931,  931,
68391  /*    60 */   931,  931,  931,  931,  931,  931,  931,  931,  931,  931,
68392  /*    70 */   931,  931,  931,  931,  931,  931,  931,  931,  931,  931,
68393  /*    80 */   931,  931,  931,  931,  931,  931,  931,  931,  931,  931,
68394  /*    90 */   931,  931,  931,  931,  931,  931,  -61,  -61,    6,    6,
68395  /*   100 */   406,   22,   61,  874,  562,   19,   19,   19,   19,   19,
68396  /*   110 */    19,   19,  226,  346,   63,  -62,  -62,  -62,  131,  534,
68397  /*   120 */   540,  540,  392,  564,  516,  567,   19,  567,   19,   19,
68398  /*   130 */    19,   19,   19,   19,   19,   19,   19,   19,   19,   19,
68399  /*   140 */    19,  815,  287,  -36,  -36,  -36,  -62,  -62,  -62, 1106,
68400  /*   150 */   472,  -15,  -15,  808,  545,  244,  559,  624,  630,  902,
68401  /*   160 */   793,  899,  601,  611,  512,   19,   19,  372,   19,   19,
68402  /*   170 */   401,   19,   19, 1022,   19,   19,  718, 1022,   19,   19,
68403  /*   180 */   913,  913,  913,   19,   19,  718,   19,   19,  718,   19,
68404  /*   190 */   804,  553,   19,   19,  718,   19,   19,   19,  718,   19,
68405  /*   200 */    19,   19,  718,  718,   19,   19,   19,   19,   19,  938,
68406  /*   210 */   927,  810,  346,  849,  849,  947,  171,  171,  171,  973,
68407  /*   220 */   171,  346,  171,  346, 1019,  757,  757, 1288, 1288, 1288,
68408  /*   230 */  1288, 1278,  -36, 1188, 1193, 1194, 1198, 1195, 1187, 1209,
68409  /*   240 */  1209, 1224, 1210, 1224, 1210, 1226, 1226, 1289, 1226, 1233,
68410  /*   250 */  1226, 1321, 1257, 1257, 1289, 1226, 1226, 1226, 1321, 1329,
68411  /*   260 */  1209, 1329, 1209, 1329, 1209, 1209, 1308, 1221, 1329, 1209,
68412  /*   270 */  1292, 1292, 1336, 1188, 1209, 1346, 1346, 1346, 1346, 1188,
68413  /*   280 */  1292, 1336, 1209, 1347, 1347, 1209, 1209, 1248,  -62,  -62,
68414  /*   290 */   -62,  -62,  335,  465, 1010,  280,  801, 1060, 1077,  868,
68415  /*   300 */   726,  685,  168,  756, 1020, 1107, 1154,  989, 1170,  954,
68416  /*   310 */  1167, 1172, 1173, 1196, 1200, 1207, 1238,  675, 1246, 1101,
68417  /*   320 */  1387, 1372, 1281, 1282, 1283, 1284, 1305, 1291, 1380, 1381,
68418  /*   330 */  1382, 1384, 1389, 1385, 1386, 1383, 1388, 1390, 1391, 1290,
68419  /*   340 */  1392, 1294, 1391, 1295, 1393, 1395, 1304, 1397, 1398, 1394,
68420  /*   350 */  1375, 1401, 1377, 1403, 1404, 1406, 1408, 1379, 1409, 1333,
68421  /*   360 */  1327, 1415, 1416, 1411, 1337, 1400, 1396, 1399, 1412, 1405,
68422  /*   370 */  1306, 1339, 1419, 1435, 1440, 1340, 1378, 1402, 1323, 1424,
68423  /*   380 */  1335, 1437, 1334, 1436, 1341, 1350, 1338, 1438, 1332, 1439,
68424  /*   390 */  1442, 1407, 1326, 1322, 1443, 1460, 1461,
68425 };
68426 #define YY_REDUCE_USE_DFLT (-165)
68427 #define YY_REDUCE_MAX 291
68428 static const short yy_reduce_ofst[] = {
68429  /*     0 */  -138,  806,  503,  667,  190,  -21,   44,   36,   38,  430,
68430  /*    10 */  -141,  274,   91,  337,  271,  276, -126,  546,  285,  151,
68431  /*    20 */   180,  -13,  283,   86,   86,   86,   86,   86,   86,   86,
68432  /*    30 */    86,   86,   86,   86,   86,   86,   86,   86,   86,   86,
68433  /*    40 */    86,   86,   86,   86,   86,   86,   86,   86,   86,   86,
68434  /*    50 */    86,   86,   86,   86,   86,  824,  831,  855,  858,  882,
68435  /*    60 */   893,  896,  920,  948,  962,  968,  972,  976,  978,  988,
68436  /*    70 */   996, 1012, 1015, 1036, 1041, 1044, 1056, 1061, 1068, 1070,
68437  /*    80 */  1074, 1076, 1081, 1085, 1087, 1094, 1100, 1102, 1105, 1114,
68438  /*    90 */  1118, 1120, 1126, 1129, 1132, 1138,   86,   86,   86,   86,
68439  /*   100 */    20,   86,   86,   23,  507,  594,  595,  636,  640,  684,
68440  /*   110 */   177,  541,   86,  200,   86,   86,   86,   86,  412, -164,
68441  /*   120 */  -115,  368,  136,  136,  552,   -6,  207,  573,  152,  -90,
68442  /*   130 */   209,  475,  295,  728,  730,  736,  843,  859,  860,  715,
68443  /*   140 */   861,   29,  325,  724,  745,  753,  582,  668,  713,   83,
68444  /*   150 */   120,    0,  199,  256,  312,  156,  363,  156,  156,  349,
68445  /*   160 */   424,  440,  457,  486,  496,  526,  642,  634,  486,  716,
68446  /*   170 */   710,  774,  805,  737,  811,  817,  156,  737,  833,  845,
68447  /*   180 */   826,  872,  876,  890,  917,  156,  925,  936,  156,  941,
68448  /*   190 */   866,  877,  977,  983,  156,  987,  992,  993,  156, 1017,
68449  /*   200 */  1028, 1032,  156,  156, 1039, 1065, 1072, 1086, 1088,  984,
68450  /*   210 */  1016, 1031, 1075, 1013, 1024, 1025, 1090, 1108, 1109, 1082,
68451  /*   220 */  1110, 1116, 1119, 1117, 1113, 1098, 1099, 1151, 1157, 1158,
68452  /*   230 */  1159, 1152, 1121, 1122, 1123, 1124, 1115, 1125, 1097, 1174,
68453  /*   240 */  1175, 1127, 1128, 1130, 1131, 1161, 1164, 1149, 1166, 1165,
68454  /*   250 */  1168, 1169, 1133, 1134, 1163, 1176, 1177, 1178, 1171, 1199,
68455  /*   260 */  1201, 1203, 1204, 1206, 1211, 1212, 1135, 1136, 1214, 1215,
68456  /*   270 */  1182, 1184, 1144, 1179, 1218, 1185, 1189, 1190, 1191, 1180,
68457  /*   280 */  1197, 1148, 1223, 1142, 1145, 1231, 1232, 1146, 1228, 1160,
68458  /*   290 */  1147, 1143,
68459 };
68460 static const YYACTIONTYPE yy_default[] = {
68461  /*     0 */   594,  819,  900,  709,  900,  819,  900,  900,  846,  713,
68462  /*    10 */   875,  817,  900,  900,  900,  900,  791,  900,  846,  900,
68463  /*    20 */   625,  846,  846,  742,  900,  900,  900,  900,  900,  900,
68464  /*    30 */   900,  900,  743,  900,  821,  816,  812,  814,  813,  820,
68465  /*    40 */   744,  733,  740,  747,  725,  859,  749,  750,  756,  757,
68466  /*    50 */   876,  874,  779,  778,  797,  900,  900,  900,  900,  900,
68467  /*    60 */   900,  900,  900,  900,  900,  900,  900,  900,  900,  900,
68468  /*    70 */   900,  900,  900,  900,  900,  900,  900,  900,  900,  900,
68469  /*    80 */   900,  900,  900,  900,  900,  900,  900,  900,  900,  900,
68470  /*    90 */   900,  900,  900,  900,  900,  900,  781,  803,  780,  790,
68471  /*   100 */   618,  782,  783,  678,  613,  900,  900,  900,  900,  900,
68472  /*   110 */   900,  900,  784,  900,  785,  798,  799,  800,  900,  900,
68473  /*   120 */   900,  900,  900,  900,  594,  709,  900,  709,  900,  900,
68474  /*   130 */   900,  900,  900,  900,  900,  900,  900,  900,  900,  900,
68475  /*   140 */   900,  900,  900,  900,  900,  900,  703,  713,  893,  900,
68476  /*   150 */   900,  900,  900,  669,  900,  900,  900,  900,  900,  900,
68477  /*   160 */   900,  900,  900,  900,  601,  599,  900,  701,  900,  900,
68478  /*   170 */   627,  900,  900,  711,  900,  900,  716,  717,  900,  900,
68479  /*   180 */   900,  900,  900,  900,  900,  615,  900,  900,  690,  900,
68480  /*   190 */   852,  900,  900,  900,  866,  900,  900,  900,  864,  900,
68481  /*   200 */   900,  900,  692,  752,  833,  900,  879,  881,  900,  900,
68482  /*   210 */   701,  710,  900,  900,  900,  815,  736,  736,  736,  648,
68483  /*   220 */   736,  900,  736,  900,  651,  746,  746,  598,  598,  598,
68484  /*   230 */   598,  668,  900,  746,  737,  739,  729,  741,  900,  718,
68485  /*   240 */   718,  726,  728,  726,  728,  680,  680,  665,  680,  651,
68486  /*   250 */   680,  825,  830,  830,  665,  680,  680,  680,  825,  610,
68487  /*   260 */   718,  610,  718,  610,  718,  718,  856,  858,  610,  718,
68488  /*   270 */   682,  682,  758,  746,  718,  689,  689,  689,  689,  746,
68489  /*   280 */   682,  758,  718,  878,  878,  718,  718,  886,  635,  861,
68490  /*   290 */   893,  898,  900,  900,  900,  900,  900,  900,  900,  900,
68491  /*   300 */   900,  900,  900,  765,  900,  900,  900,  900,  900,  900,
68492  /*   310 */   900,  900,  900,  900,  900,  900,  900,  839,  900,  900,
68493  /*   320 */   900,  900,  770,  766,  900,  767,  900,  695,  900,  900,
68494  /*   330 */   900,  900,  900,  900,  900,  900,  900,  900,  818,  900,
68495  /*   340 */   730,  900,  738,  900,  900,  900,  900,  900,  900,  900,
68496  /*   350 */   900,  900,  900,  900,  900,  900,  900,  900,  900,  900,
68497  /*   360 */   900,  900,  900,  900,  900,  900,  900,  854,  855,  900,
68498  /*   370 */   900,  900,  900,  900,  900,  900,  900,  900,  900,  900,
68499  /*   380 */   900,  900,  900,  900,  900,  900,  900,  900,  900,  900,
68500  /*   390 */   900,  885,  900,  900,  888,  595,  900,  589,  592,  591,
68501  /*   400 */   593,  597,  600,  622,  623,  624,  602,  603,  604,  605,
68502  /*   410 */   606,  607,  608,  614,  616,  634,  636,  620,  638,  699,
68503  /*   420 */   700,  762,  693,  694,  698,  621,  773,  764,  768,  769,
68504  /*   430 */   771,  772,  786,  787,  789,  795,  802,  805,  788,  793,
68505  /*   440 */   794,  796,  801,  804,  696,  697,  808,  628,  629,  632,
68506  /*   450 */   633,  842,  844,  843,  845,  631,  630,  774,  777,  810,
68507  /*   460 */   811,  867,  868,  869,  870,  871,  806,  719,  809,  792,
68508  /*   470 */   731,  734,  735,  732,  702,  712,  721,  722,  723,  724,
68509  /*   480 */   707,  708,  714,  727,  760,  761,  715,  704,  705,  706,
68510  /*   490 */   807,  763,  775,  776,  639,  640,  770,  641,  642,  643,
68511  /*   500 */   681,  684,  685,  686,  644,  663,  666,  667,  645,  647,
68512  /*   510 */   659,  660,  661,  662,  657,  658,  826,  827,  831,  829,
68513  /*   520 */   828,  664,  637,  626,  619,  670,  673,  674,  675,  676,
68514  /*   530 */   677,  679,  671,  672,  617,  609,  611,  720,  848,  857,
68515  /*   540 */   853,  849,  850,  851,  612,  822,  823,  683,  754,  755,
68516  /*   550 */   847,  860,  862,  759,  863,  865,  890,  687,  688,  691,
68517  /*   560 */   832,  872,  745,  748,  751,  753,  834,  835,  836,  837,
68518  /*   570 */   840,  841,  838,  873,  877,  880,  882,  883,  884,  887,
68519  /*   580 */   889,  894,  895,  896,  899,  897,  596,  590,
68520 };
68521 #define YY_SZ_ACTTAB (int)(sizeof(yy_action)/sizeof(yy_action[0]))
68522
68523 /* The next table maps tokens into fallback tokens.  If a construct
68524 ** like the following:
68525 ** 
68526 **      %fallback ID X Y Z.
68527 **
68528 ** appears in the grammer, then ID becomes a fallback token for X, Y,
68529 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
68530 ** but it does not parse, the type of the token is changed to ID and
68531 ** the parse is retried before an error is thrown.
68532 */
68533 #ifdef YYFALLBACK
68534 static const YYCODETYPE yyFallback[] = {
68535     0,  /*          $ => nothing */
68536     0,  /*       SEMI => nothing */
68537    23,  /*    EXPLAIN => ID */
68538    23,  /*      QUERY => ID */
68539    23,  /*       PLAN => ID */
68540    23,  /*      BEGIN => ID */
68541     0,  /* TRANSACTION => nothing */
68542    23,  /*   DEFERRED => ID */
68543    23,  /*  IMMEDIATE => ID */
68544    23,  /*  EXCLUSIVE => ID */
68545     0,  /*     COMMIT => nothing */
68546    23,  /*        END => ID */
68547     0,  /*   ROLLBACK => nothing */
68548     0,  /*     CREATE => nothing */
68549     0,  /*      TABLE => nothing */
68550    23,  /*         IF => ID */
68551     0,  /*        NOT => nothing */
68552     0,  /*     EXISTS => nothing */
68553    23,  /*       TEMP => ID */
68554     0,  /*         LP => nothing */
68555     0,  /*         RP => nothing */
68556     0,  /*         AS => nothing */
68557     0,  /*      COMMA => nothing */
68558     0,  /*         ID => nothing */
68559    23,  /*      ABORT => ID */
68560    23,  /*      AFTER => ID */
68561    23,  /*    ANALYZE => ID */
68562    23,  /*        ASC => ID */
68563    23,  /*     ATTACH => ID */
68564    23,  /*     BEFORE => ID */
68565    23,  /*    CASCADE => ID */
68566    23,  /*       CAST => ID */
68567    23,  /*   CONFLICT => ID */
68568    23,  /*   DATABASE => ID */
68569    23,  /*       DESC => ID */
68570    23,  /*     DETACH => ID */
68571    23,  /*       EACH => ID */
68572    23,  /*       FAIL => ID */
68573    23,  /*        FOR => ID */
68574    23,  /*     IGNORE => ID */
68575    23,  /*  INITIALLY => ID */
68576    23,  /*    INSTEAD => ID */
68577    23,  /*    LIKE_KW => ID */
68578    23,  /*      MATCH => ID */
68579    23,  /*        KEY => ID */
68580    23,  /*         OF => ID */
68581    23,  /*     OFFSET => ID */
68582    23,  /*     PRAGMA => ID */
68583    23,  /*      RAISE => ID */
68584    23,  /*    REPLACE => ID */
68585    23,  /*   RESTRICT => ID */
68586    23,  /*        ROW => ID */
68587    23,  /*    TRIGGER => ID */
68588    23,  /*     VACUUM => ID */
68589    23,  /*       VIEW => ID */
68590    23,  /*    VIRTUAL => ID */
68591    23,  /*    REINDEX => ID */
68592    23,  /*     RENAME => ID */
68593    23,  /*   CTIME_KW => ID */
68594     0,  /*        ANY => nothing */
68595     0,  /*         OR => nothing */
68596     0,  /*        AND => nothing */
68597     0,  /*         IS => nothing */
68598     0,  /*    BETWEEN => nothing */
68599     0,  /*         IN => nothing */
68600     0,  /*     ISNULL => nothing */
68601     0,  /*    NOTNULL => nothing */
68602     0,  /*         NE => nothing */
68603     0,  /*         EQ => nothing */
68604     0,  /*         GT => nothing */
68605     0,  /*         LE => nothing */
68606     0,  /*         LT => nothing */
68607     0,  /*         GE => nothing */
68608     0,  /*     ESCAPE => nothing */
68609     0,  /*     BITAND => nothing */
68610     0,  /*      BITOR => nothing */
68611     0,  /*     LSHIFT => nothing */
68612     0,  /*     RSHIFT => nothing */
68613     0,  /*       PLUS => nothing */
68614     0,  /*      MINUS => nothing */
68615     0,  /*       STAR => nothing */
68616     0,  /*      SLASH => nothing */
68617     0,  /*        REM => nothing */
68618     0,  /*     CONCAT => nothing */
68619     0,  /*    COLLATE => nothing */
68620     0,  /*     UMINUS => nothing */
68621     0,  /*      UPLUS => nothing */
68622     0,  /*     BITNOT => nothing */
68623     0,  /*     STRING => nothing */
68624     0,  /*    JOIN_KW => nothing */
68625     0,  /* CONSTRAINT => nothing */
68626     0,  /*    DEFAULT => nothing */
68627     0,  /*       NULL => nothing */
68628     0,  /*    PRIMARY => nothing */
68629     0,  /*     UNIQUE => nothing */
68630     0,  /*      CHECK => nothing */
68631     0,  /* REFERENCES => nothing */
68632     0,  /*   AUTOINCR => nothing */
68633     0,  /*         ON => nothing */
68634     0,  /*     DELETE => nothing */
68635     0,  /*     UPDATE => nothing */
68636     0,  /*     INSERT => nothing */
68637     0,  /*        SET => nothing */
68638     0,  /* DEFERRABLE => nothing */
68639     0,  /*    FOREIGN => nothing */
68640     0,  /*       DROP => nothing */
68641     0,  /*      UNION => nothing */
68642     0,  /*        ALL => nothing */
68643     0,  /*     EXCEPT => nothing */
68644     0,  /*  INTERSECT => nothing */
68645     0,  /*     SELECT => nothing */
68646     0,  /*   DISTINCT => nothing */
68647     0,  /*        DOT => nothing */
68648     0,  /*       FROM => nothing */
68649     0,  /*       JOIN => nothing */
68650     0,  /*      USING => nothing */
68651     0,  /*      ORDER => nothing */
68652     0,  /*         BY => nothing */
68653     0,  /*      GROUP => nothing */
68654     0,  /*     HAVING => nothing */
68655     0,  /*      LIMIT => nothing */
68656     0,  /*      WHERE => nothing */
68657     0,  /*       INTO => nothing */
68658     0,  /*     VALUES => nothing */
68659     0,  /*    INTEGER => nothing */
68660     0,  /*      FLOAT => nothing */
68661     0,  /*       BLOB => nothing */
68662     0,  /*   REGISTER => nothing */
68663     0,  /*   VARIABLE => nothing */
68664     0,  /*       CASE => nothing */
68665     0,  /*       WHEN => nothing */
68666     0,  /*       THEN => nothing */
68667     0,  /*       ELSE => nothing */
68668     0,  /*      INDEX => nothing */
68669     0,  /*      ALTER => nothing */
68670     0,  /*         TO => nothing */
68671     0,  /*        ADD => nothing */
68672     0,  /*   COLUMNKW => nothing */
68673 };
68674 #endif /* YYFALLBACK */
68675
68676 /* The following structure represents a single element of the
68677 ** parser's stack.  Information stored includes:
68678 **
68679 **   +  The state number for the parser at this level of the stack.
68680 **
68681 **   +  The value of the token stored at this level of the stack.
68682 **      (In other words, the "major" token.)
68683 **
68684 **   +  The semantic value stored at this level of the stack.  This is
68685 **      the information used by the action routines in the grammar.
68686 **      It is sometimes called the "minor" token.
68687 */
68688 struct yyStackEntry {
68689   int stateno;       /* The state-number */
68690   int major;         /* The major token value.  This is the code
68691                      ** number for the token at this stack level */
68692   YYMINORTYPE minor; /* The user-supplied minor token value.  This
68693                      ** is the value of the token  */
68694 };
68695 typedef struct yyStackEntry yyStackEntry;
68696
68697 /* The state of the parser is completely contained in an instance of
68698 ** the following structure */
68699 struct yyParser {
68700   int yyidx;                    /* Index of top element in stack */
68701   int yyerrcnt;                 /* Shifts left before out of the error */
68702   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
68703 #if YYSTACKDEPTH<=0
68704   int yystksz;                  /* Current side of the stack */
68705   yyStackEntry *yystack;        /* The parser's stack */
68706 #else
68707   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
68708 #endif
68709 };
68710 typedef struct yyParser yyParser;
68711
68712 #ifndef NDEBUG
68713 static FILE *yyTraceFILE = 0;
68714 static char *yyTracePrompt = 0;
68715 #endif /* NDEBUG */
68716
68717 #ifndef NDEBUG
68718 /* 
68719 ** Turn parser tracing on by giving a stream to which to write the trace
68720 ** and a prompt to preface each trace message.  Tracing is turned off
68721 ** by making either argument NULL 
68722 **
68723 ** Inputs:
68724 ** <ul>
68725 ** <li> A FILE* to which trace output should be written.
68726 **      If NULL, then tracing is turned off.
68727 ** <li> A prefix string written at the beginning of every
68728 **      line of trace output.  If NULL, then tracing is
68729 **      turned off.
68730 ** </ul>
68731 **
68732 ** Outputs:
68733 ** None.
68734 */
68735 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
68736   yyTraceFILE = TraceFILE;
68737   yyTracePrompt = zTracePrompt;
68738   if( yyTraceFILE==0 ) yyTracePrompt = 0;
68739   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
68740 }
68741 #endif /* NDEBUG */
68742
68743 #ifndef NDEBUG
68744 /* For tracing shifts, the names of all terminals and nonterminals
68745 ** are required.  The following table supplies these names */
68746 static const char *const yyTokenName[] = { 
68747   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
68748   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
68749   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
68750   "ROLLBACK",      "CREATE",        "TABLE",         "IF",          
68751   "NOT",           "EXISTS",        "TEMP",          "LP",          
68752   "RP",            "AS",            "COMMA",         "ID",          
68753   "ABORT",         "AFTER",         "ANALYZE",       "ASC",         
68754   "ATTACH",        "BEFORE",        "CASCADE",       "CAST",        
68755   "CONFLICT",      "DATABASE",      "DESC",          "DETACH",      
68756   "EACH",          "FAIL",          "FOR",           "IGNORE",      
68757   "INITIALLY",     "INSTEAD",       "LIKE_KW",       "MATCH",       
68758   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
68759   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
68760   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
68761   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
68762   "OR",            "AND",           "IS",            "BETWEEN",     
68763   "IN",            "ISNULL",        "NOTNULL",       "NE",          
68764   "EQ",            "GT",            "LE",            "LT",          
68765   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
68766   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
68767   "STAR",          "SLASH",         "REM",           "CONCAT",      
68768   "COLLATE",       "UMINUS",        "UPLUS",         "BITNOT",      
68769   "STRING",        "JOIN_KW",       "CONSTRAINT",    "DEFAULT",     
68770   "NULL",          "PRIMARY",       "UNIQUE",        "CHECK",       
68771   "REFERENCES",    "AUTOINCR",      "ON",            "DELETE",      
68772   "UPDATE",        "INSERT",        "SET",           "DEFERRABLE",  
68773   "FOREIGN",       "DROP",          "UNION",         "ALL",         
68774   "EXCEPT",        "INTERSECT",     "SELECT",        "DISTINCT",    
68775   "DOT",           "FROM",          "JOIN",          "USING",       
68776   "ORDER",         "BY",            "GROUP",         "HAVING",      
68777   "LIMIT",         "WHERE",         "INTO",          "VALUES",      
68778   "INTEGER",       "FLOAT",         "BLOB",          "REGISTER",    
68779   "VARIABLE",      "CASE",          "WHEN",          "THEN",        
68780   "ELSE",          "INDEX",         "ALTER",         "TO",          
68781   "ADD",           "COLUMNKW",      "error",         "input",       
68782   "cmdlist",       "ecmd",          "cmdx",          "cmd",         
68783   "explain",       "transtype",     "trans_opt",     "nm",          
68784   "create_table",  "create_table_args",  "temp",          "ifnotexists", 
68785   "dbnm",          "columnlist",    "conslist_opt",  "select",      
68786   "column",        "columnid",      "type",          "carglist",    
68787   "id",            "ids",           "typetoken",     "typename",    
68788   "signed",        "plus_num",      "minus_num",     "carg",        
68789   "ccons",         "term",          "expr",          "onconf",      
68790   "sortorder",     "autoinc",       "idxlist_opt",   "refargs",     
68791   "defer_subclause",  "refarg",        "refact",        "init_deferred_pred_opt",
68792   "conslist",      "tcons",         "idxlist",       "defer_subclause_opt",
68793   "orconf",        "resolvetype",   "raisetype",     "ifexists",    
68794   "fullname",      "oneselect",     "multiselect_op",  "distinct",    
68795   "selcollist",    "from",          "where_opt",     "groupby_opt", 
68796   "having_opt",    "orderby_opt",   "limit_opt",     "sclp",        
68797   "as",            "seltablist",    "stl_prefix",    "joinop",      
68798   "on_opt",        "using_opt",     "seltablist_paren",  "joinop2",     
68799   "inscollist",    "sortlist",      "sortitem",      "nexprlist",   
68800   "setlist",       "insert_cmd",    "inscollist_opt",  "itemlist",    
68801   "exprlist",      "likeop",        "escape",        "between_op",  
68802   "in_op",         "case_operand",  "case_exprlist",  "case_else",   
68803   "uniqueflag",    "idxitem",       "collate",       "nmnum",       
68804   "plus_opt",      "number",        "trigger_decl",  "trigger_cmd_list",
68805   "trigger_time",  "trigger_event",  "foreach_clause",  "when_clause", 
68806   "trigger_cmd",   "database_kw_opt",  "key_opt",       "add_column_fullname",
68807   "kwcolumn_opt",  "create_vtab",   "vtabarglist",   "vtabarg",     
68808   "vtabargtoken",  "lp",            "anylist",     
68809 };
68810 #endif /* NDEBUG */
68811
68812 #ifndef NDEBUG
68813 /* For tracing reduce actions, the names of all rules are required.
68814 */
68815 static const char *const yyRuleName[] = {
68816  /*   0 */ "input ::= cmdlist",
68817  /*   1 */ "cmdlist ::= cmdlist ecmd",
68818  /*   2 */ "cmdlist ::= ecmd",
68819  /*   3 */ "cmdx ::= cmd",
68820  /*   4 */ "ecmd ::= SEMI",
68821  /*   5 */ "ecmd ::= explain cmdx SEMI",
68822  /*   6 */ "explain ::=",
68823  /*   7 */ "explain ::= EXPLAIN",
68824  /*   8 */ "explain ::= EXPLAIN QUERY PLAN",
68825  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
68826  /*  10 */ "trans_opt ::=",
68827  /*  11 */ "trans_opt ::= TRANSACTION",
68828  /*  12 */ "trans_opt ::= TRANSACTION nm",
68829  /*  13 */ "transtype ::=",
68830  /*  14 */ "transtype ::= DEFERRED",
68831  /*  15 */ "transtype ::= IMMEDIATE",
68832  /*  16 */ "transtype ::= EXCLUSIVE",
68833  /*  17 */ "cmd ::= COMMIT trans_opt",
68834  /*  18 */ "cmd ::= END trans_opt",
68835  /*  19 */ "cmd ::= ROLLBACK trans_opt",
68836  /*  20 */ "cmd ::= create_table create_table_args",
68837  /*  21 */ "create_table ::= CREATE temp TABLE ifnotexists nm dbnm",
68838  /*  22 */ "ifnotexists ::=",
68839  /*  23 */ "ifnotexists ::= IF NOT EXISTS",
68840  /*  24 */ "temp ::= TEMP",
68841  /*  25 */ "temp ::=",
68842  /*  26 */ "create_table_args ::= LP columnlist conslist_opt RP",
68843  /*  27 */ "create_table_args ::= AS select",
68844  /*  28 */ "columnlist ::= columnlist COMMA column",
68845  /*  29 */ "columnlist ::= column",
68846  /*  30 */ "column ::= columnid type carglist",
68847  /*  31 */ "columnid ::= nm",
68848  /*  32 */ "id ::= ID",
68849  /*  33 */ "ids ::= ID|STRING",
68850  /*  34 */ "nm ::= ID",
68851  /*  35 */ "nm ::= STRING",
68852  /*  36 */ "nm ::= JOIN_KW",
68853  /*  37 */ "type ::=",
68854  /*  38 */ "type ::= typetoken",
68855  /*  39 */ "typetoken ::= typename",
68856  /*  40 */ "typetoken ::= typename LP signed RP",
68857  /*  41 */ "typetoken ::= typename LP signed COMMA signed RP",
68858  /*  42 */ "typename ::= ids",
68859  /*  43 */ "typename ::= typename ids",
68860  /*  44 */ "signed ::= plus_num",
68861  /*  45 */ "signed ::= minus_num",
68862  /*  46 */ "carglist ::= carglist carg",
68863  /*  47 */ "carglist ::=",
68864  /*  48 */ "carg ::= CONSTRAINT nm ccons",
68865  /*  49 */ "carg ::= ccons",
68866  /*  50 */ "ccons ::= DEFAULT term",
68867  /*  51 */ "ccons ::= DEFAULT LP expr RP",
68868  /*  52 */ "ccons ::= DEFAULT PLUS term",
68869  /*  53 */ "ccons ::= DEFAULT MINUS term",
68870  /*  54 */ "ccons ::= DEFAULT id",
68871  /*  55 */ "ccons ::= NULL onconf",
68872  /*  56 */ "ccons ::= NOT NULL onconf",
68873  /*  57 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
68874  /*  58 */ "ccons ::= UNIQUE onconf",
68875  /*  59 */ "ccons ::= CHECK LP expr RP",
68876  /*  60 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
68877  /*  61 */ "ccons ::= defer_subclause",
68878  /*  62 */ "ccons ::= COLLATE ids",
68879  /*  63 */ "autoinc ::=",
68880  /*  64 */ "autoinc ::= AUTOINCR",
68881  /*  65 */ "refargs ::=",
68882  /*  66 */ "refargs ::= refargs refarg",
68883  /*  67 */ "refarg ::= MATCH nm",
68884  /*  68 */ "refarg ::= ON DELETE refact",
68885  /*  69 */ "refarg ::= ON UPDATE refact",
68886  /*  70 */ "refarg ::= ON INSERT refact",
68887  /*  71 */ "refact ::= SET NULL",
68888  /*  72 */ "refact ::= SET DEFAULT",
68889  /*  73 */ "refact ::= CASCADE",
68890  /*  74 */ "refact ::= RESTRICT",
68891  /*  75 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
68892  /*  76 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
68893  /*  77 */ "init_deferred_pred_opt ::=",
68894  /*  78 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
68895  /*  79 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
68896  /*  80 */ "conslist_opt ::=",
68897  /*  81 */ "conslist_opt ::= COMMA conslist",
68898  /*  82 */ "conslist ::= conslist COMMA tcons",
68899  /*  83 */ "conslist ::= conslist tcons",
68900  /*  84 */ "conslist ::= tcons",
68901  /*  85 */ "tcons ::= CONSTRAINT nm",
68902  /*  86 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
68903  /*  87 */ "tcons ::= UNIQUE LP idxlist RP onconf",
68904  /*  88 */ "tcons ::= CHECK LP expr RP onconf",
68905  /*  89 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
68906  /*  90 */ "defer_subclause_opt ::=",
68907  /*  91 */ "defer_subclause_opt ::= defer_subclause",
68908  /*  92 */ "onconf ::=",
68909  /*  93 */ "onconf ::= ON CONFLICT resolvetype",
68910  /*  94 */ "orconf ::=",
68911  /*  95 */ "orconf ::= OR resolvetype",
68912  /*  96 */ "resolvetype ::= raisetype",
68913  /*  97 */ "resolvetype ::= IGNORE",
68914  /*  98 */ "resolvetype ::= REPLACE",
68915  /*  99 */ "cmd ::= DROP TABLE ifexists fullname",
68916  /* 100 */ "ifexists ::= IF EXISTS",
68917  /* 101 */ "ifexists ::=",
68918  /* 102 */ "cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select",
68919  /* 103 */ "cmd ::= DROP VIEW ifexists fullname",
68920  /* 104 */ "cmd ::= select",
68921  /* 105 */ "select ::= oneselect",
68922  /* 106 */ "select ::= select multiselect_op oneselect",
68923  /* 107 */ "multiselect_op ::= UNION",
68924  /* 108 */ "multiselect_op ::= UNION ALL",
68925  /* 109 */ "multiselect_op ::= EXCEPT|INTERSECT",
68926  /* 110 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
68927  /* 111 */ "distinct ::= DISTINCT",
68928  /* 112 */ "distinct ::= ALL",
68929  /* 113 */ "distinct ::=",
68930  /* 114 */ "sclp ::= selcollist COMMA",
68931  /* 115 */ "sclp ::=",
68932  /* 116 */ "selcollist ::= sclp expr as",
68933  /* 117 */ "selcollist ::= sclp STAR",
68934  /* 118 */ "selcollist ::= sclp nm DOT STAR",
68935  /* 119 */ "as ::= AS nm",
68936  /* 120 */ "as ::= ids",
68937  /* 121 */ "as ::=",
68938  /* 122 */ "from ::=",
68939  /* 123 */ "from ::= FROM seltablist",
68940  /* 124 */ "stl_prefix ::= seltablist joinop",
68941  /* 125 */ "stl_prefix ::=",
68942  /* 126 */ "seltablist ::= stl_prefix nm dbnm as on_opt using_opt",
68943  /* 127 */ "seltablist ::= stl_prefix LP seltablist_paren RP as on_opt using_opt",
68944  /* 128 */ "seltablist_paren ::= select",
68945  /* 129 */ "seltablist_paren ::= seltablist",
68946  /* 130 */ "dbnm ::=",
68947  /* 131 */ "dbnm ::= DOT nm",
68948  /* 132 */ "fullname ::= nm dbnm",
68949  /* 133 */ "joinop ::= COMMA|JOIN",
68950  /* 134 */ "joinop ::= JOIN_KW JOIN",
68951  /* 135 */ "joinop ::= JOIN_KW nm JOIN",
68952  /* 136 */ "joinop ::= JOIN_KW nm nm JOIN",
68953  /* 137 */ "on_opt ::= ON expr",
68954  /* 138 */ "on_opt ::=",
68955  /* 139 */ "using_opt ::= USING LP inscollist RP",
68956  /* 140 */ "using_opt ::=",
68957  /* 141 */ "orderby_opt ::=",
68958  /* 142 */ "orderby_opt ::= ORDER BY sortlist",
68959  /* 143 */ "sortlist ::= sortlist COMMA sortitem sortorder",
68960  /* 144 */ "sortlist ::= sortitem sortorder",
68961  /* 145 */ "sortitem ::= expr",
68962  /* 146 */ "sortorder ::= ASC",
68963  /* 147 */ "sortorder ::= DESC",
68964  /* 148 */ "sortorder ::=",
68965  /* 149 */ "groupby_opt ::=",
68966  /* 150 */ "groupby_opt ::= GROUP BY nexprlist",
68967  /* 151 */ "having_opt ::=",
68968  /* 152 */ "having_opt ::= HAVING expr",
68969  /* 153 */ "limit_opt ::=",
68970  /* 154 */ "limit_opt ::= LIMIT expr",
68971  /* 155 */ "limit_opt ::= LIMIT expr OFFSET expr",
68972  /* 156 */ "limit_opt ::= LIMIT expr COMMA expr",
68973  /* 157 */ "cmd ::= DELETE FROM fullname where_opt",
68974  /* 158 */ "where_opt ::=",
68975  /* 159 */ "where_opt ::= WHERE expr",
68976  /* 160 */ "cmd ::= UPDATE orconf fullname SET setlist where_opt",
68977  /* 161 */ "setlist ::= setlist COMMA nm EQ expr",
68978  /* 162 */ "setlist ::= nm EQ expr",
68979  /* 163 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
68980  /* 164 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
68981  /* 165 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
68982  /* 166 */ "insert_cmd ::= INSERT orconf",
68983  /* 167 */ "insert_cmd ::= REPLACE",
68984  /* 168 */ "itemlist ::= itemlist COMMA expr",
68985  /* 169 */ "itemlist ::= expr",
68986  /* 170 */ "inscollist_opt ::=",
68987  /* 171 */ "inscollist_opt ::= LP inscollist RP",
68988  /* 172 */ "inscollist ::= inscollist COMMA nm",
68989  /* 173 */ "inscollist ::= nm",
68990  /* 174 */ "expr ::= term",
68991  /* 175 */ "expr ::= LP expr RP",
68992  /* 176 */ "term ::= NULL",
68993  /* 177 */ "expr ::= ID",
68994  /* 178 */ "expr ::= JOIN_KW",
68995  /* 179 */ "expr ::= nm DOT nm",
68996  /* 180 */ "expr ::= nm DOT nm DOT nm",
68997  /* 181 */ "term ::= INTEGER|FLOAT|BLOB",
68998  /* 182 */ "term ::= STRING",
68999  /* 183 */ "expr ::= REGISTER",
69000  /* 184 */ "expr ::= VARIABLE",
69001  /* 185 */ "expr ::= expr COLLATE ids",
69002  /* 186 */ "expr ::= CAST LP expr AS typetoken RP",
69003  /* 187 */ "expr ::= ID LP distinct exprlist RP",
69004  /* 188 */ "expr ::= ID LP STAR RP",
69005  /* 189 */ "term ::= CTIME_KW",
69006  /* 190 */ "expr ::= expr AND expr",
69007  /* 191 */ "expr ::= expr OR expr",
69008  /* 192 */ "expr ::= expr LT|GT|GE|LE expr",
69009  /* 193 */ "expr ::= expr EQ|NE expr",
69010  /* 194 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
69011  /* 195 */ "expr ::= expr PLUS|MINUS expr",
69012  /* 196 */ "expr ::= expr STAR|SLASH|REM expr",
69013  /* 197 */ "expr ::= expr CONCAT expr",
69014  /* 198 */ "likeop ::= LIKE_KW",
69015  /* 199 */ "likeop ::= NOT LIKE_KW",
69016  /* 200 */ "likeop ::= MATCH",
69017  /* 201 */ "likeop ::= NOT MATCH",
69018  /* 202 */ "escape ::= ESCAPE expr",
69019  /* 203 */ "escape ::=",
69020  /* 204 */ "expr ::= expr likeop expr escape",
69021  /* 205 */ "expr ::= expr ISNULL|NOTNULL",
69022  /* 206 */ "expr ::= expr IS NULL",
69023  /* 207 */ "expr ::= expr NOT NULL",
69024  /* 208 */ "expr ::= expr IS NOT NULL",
69025  /* 209 */ "expr ::= NOT expr",
69026  /* 210 */ "expr ::= BITNOT expr",
69027  /* 211 */ "expr ::= MINUS expr",
69028  /* 212 */ "expr ::= PLUS expr",
69029  /* 213 */ "between_op ::= BETWEEN",
69030  /* 214 */ "between_op ::= NOT BETWEEN",
69031  /* 215 */ "expr ::= expr between_op expr AND expr",
69032  /* 216 */ "in_op ::= IN",
69033  /* 217 */ "in_op ::= NOT IN",
69034  /* 218 */ "expr ::= expr in_op LP exprlist RP",
69035  /* 219 */ "expr ::= LP select RP",
69036  /* 220 */ "expr ::= expr in_op LP select RP",
69037  /* 221 */ "expr ::= expr in_op nm dbnm",
69038  /* 222 */ "expr ::= EXISTS LP select RP",
69039  /* 223 */ "expr ::= CASE case_operand case_exprlist case_else END",
69040  /* 224 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
69041  /* 225 */ "case_exprlist ::= WHEN expr THEN expr",
69042  /* 226 */ "case_else ::= ELSE expr",
69043  /* 227 */ "case_else ::=",
69044  /* 228 */ "case_operand ::= expr",
69045  /* 229 */ "case_operand ::=",
69046  /* 230 */ "exprlist ::= nexprlist",
69047  /* 231 */ "exprlist ::=",
69048  /* 232 */ "nexprlist ::= nexprlist COMMA expr",
69049  /* 233 */ "nexprlist ::= expr",
69050  /* 234 */ "cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
69051  /* 235 */ "uniqueflag ::= UNIQUE",
69052  /* 236 */ "uniqueflag ::=",
69053  /* 237 */ "idxlist_opt ::=",
69054  /* 238 */ "idxlist_opt ::= LP idxlist RP",
69055  /* 239 */ "idxlist ::= idxlist COMMA idxitem collate sortorder",
69056  /* 240 */ "idxlist ::= idxitem collate sortorder",
69057  /* 241 */ "idxitem ::= nm",
69058  /* 242 */ "collate ::=",
69059  /* 243 */ "collate ::= COLLATE ids",
69060  /* 244 */ "cmd ::= DROP INDEX ifexists fullname",
69061  /* 245 */ "cmd ::= VACUUM",
69062  /* 246 */ "cmd ::= VACUUM nm",
69063  /* 247 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
69064  /* 248 */ "cmd ::= PRAGMA nm dbnm EQ ON",
69065  /* 249 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
69066  /* 250 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
69067  /* 251 */ "cmd ::= PRAGMA nm dbnm",
69068  /* 252 */ "nmnum ::= plus_num",
69069  /* 253 */ "nmnum ::= nm",
69070  /* 254 */ "plus_num ::= plus_opt number",
69071  /* 255 */ "minus_num ::= MINUS number",
69072  /* 256 */ "number ::= INTEGER|FLOAT",
69073  /* 257 */ "plus_opt ::= PLUS",
69074  /* 258 */ "plus_opt ::=",
69075  /* 259 */ "cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END",
69076  /* 260 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
69077  /* 261 */ "trigger_time ::= BEFORE",
69078  /* 262 */ "trigger_time ::= AFTER",
69079  /* 263 */ "trigger_time ::= INSTEAD OF",
69080  /* 264 */ "trigger_time ::=",
69081  /* 265 */ "trigger_event ::= DELETE|INSERT",
69082  /* 266 */ "trigger_event ::= UPDATE",
69083  /* 267 */ "trigger_event ::= UPDATE OF inscollist",
69084  /* 268 */ "foreach_clause ::=",
69085  /* 269 */ "foreach_clause ::= FOR EACH ROW",
69086  /* 270 */ "when_clause ::=",
69087  /* 271 */ "when_clause ::= WHEN expr",
69088  /* 272 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
69089  /* 273 */ "trigger_cmd_list ::=",
69090  /* 274 */ "trigger_cmd ::= UPDATE orconf nm SET setlist where_opt",
69091  /* 275 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP",
69092  /* 276 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt select",
69093  /* 277 */ "trigger_cmd ::= DELETE FROM nm where_opt",
69094  /* 278 */ "trigger_cmd ::= select",
69095  /* 279 */ "expr ::= RAISE LP IGNORE RP",
69096  /* 280 */ "expr ::= RAISE LP raisetype COMMA nm RP",
69097  /* 281 */ "raisetype ::= ROLLBACK",
69098  /* 282 */ "raisetype ::= ABORT",
69099  /* 283 */ "raisetype ::= FAIL",
69100  /* 284 */ "cmd ::= DROP TRIGGER ifexists fullname",
69101  /* 285 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
69102  /* 286 */ "cmd ::= DETACH database_kw_opt expr",
69103  /* 287 */ "key_opt ::=",
69104  /* 288 */ "key_opt ::= KEY expr",
69105  /* 289 */ "database_kw_opt ::= DATABASE",
69106  /* 290 */ "database_kw_opt ::=",
69107  /* 291 */ "cmd ::= REINDEX",
69108  /* 292 */ "cmd ::= REINDEX nm dbnm",
69109  /* 293 */ "cmd ::= ANALYZE",
69110  /* 294 */ "cmd ::= ANALYZE nm dbnm",
69111  /* 295 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
69112  /* 296 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
69113  /* 297 */ "add_column_fullname ::= fullname",
69114  /* 298 */ "kwcolumn_opt ::=",
69115  /* 299 */ "kwcolumn_opt ::= COLUMNKW",
69116  /* 300 */ "cmd ::= create_vtab",
69117  /* 301 */ "cmd ::= create_vtab LP vtabarglist RP",
69118  /* 302 */ "create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm",
69119  /* 303 */ "vtabarglist ::= vtabarg",
69120  /* 304 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
69121  /* 305 */ "vtabarg ::=",
69122  /* 306 */ "vtabarg ::= vtabarg vtabargtoken",
69123  /* 307 */ "vtabargtoken ::= ANY",
69124  /* 308 */ "vtabargtoken ::= lp anylist RP",
69125  /* 309 */ "lp ::= LP",
69126  /* 310 */ "anylist ::=",
69127  /* 311 */ "anylist ::= anylist ANY",
69128 };
69129 #endif /* NDEBUG */
69130
69131
69132 #if YYSTACKDEPTH<=0
69133 /*
69134 ** Try to increase the size of the parser stack.
69135 */
69136 static void yyGrowStack(yyParser *p){
69137   int newSize;
69138   yyStackEntry *pNew;
69139
69140   newSize = p->yystksz*2 + 100;
69141   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
69142   if( pNew ){
69143     p->yystack = pNew;
69144     p->yystksz = newSize;
69145 #ifndef NDEBUG
69146     if( yyTraceFILE ){
69147       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
69148               yyTracePrompt, p->yystksz);
69149     }
69150 #endif
69151   }
69152 }
69153 #endif
69154
69155 /* 
69156 ** This function allocates a new parser.
69157 ** The only argument is a pointer to a function which works like
69158 ** malloc.
69159 **
69160 ** Inputs:
69161 ** A pointer to the function used to allocate memory.
69162 **
69163 ** Outputs:
69164 ** A pointer to a parser.  This pointer is used in subsequent calls
69165 ** to sqlite3Parser and sqlite3ParserFree.
69166 */
69167 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
69168   yyParser *pParser;
69169   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
69170   if( pParser ){
69171     pParser->yyidx = -1;
69172 #if YYSTACKDEPTH<=0
69173     yyGrowStack(pParser);
69174 #endif
69175   }
69176   return pParser;
69177 }
69178
69179 /* The following function deletes the value associated with a
69180 ** symbol.  The symbol can be either a terminal or nonterminal.
69181 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
69182 ** the value.
69183 */
69184 static void yy_destructor(YYCODETYPE yymajor, YYMINORTYPE *yypminor){
69185   switch( yymajor ){
69186     /* Here is inserted the actions which take place when a
69187     ** terminal or non-terminal is destroyed.  This can happen
69188     ** when the symbol is popped from the stack during a
69189     ** reduce or during error processing or when a parser is 
69190     ** being destroyed before it is finished parsing.
69191     **
69192     ** Note: during a reduce, the only symbols destroyed are those
69193     ** which appear on the RHS of the rule, but which are not used
69194     ** inside the C code.
69195     */
69196     case 155:
69197     case 189:
69198     case 206:
69199 {sqlite3SelectDelete((yypminor->yy219));}
69200       break;
69201     case 169:
69202     case 170:
69203     case 194:
69204     case 196:
69205     case 204:
69206     case 210:
69207     case 218:
69208     case 221:
69209     case 223:
69210     case 235:
69211 {sqlite3ExprDelete((yypminor->yy172));}
69212       break;
69213     case 174:
69214     case 182:
69215     case 192:
69216     case 195:
69217     case 197:
69218     case 199:
69219     case 209:
69220     case 211:
69221     case 212:
69222     case 215:
69223     case 216:
69224     case 222:
69225 {sqlite3ExprListDelete((yypminor->yy174));}
69226       break;
69227     case 188:
69228     case 193:
69229     case 201:
69230     case 202:
69231 {sqlite3SrcListDelete((yypminor->yy373));}
69232       break;
69233     case 205:
69234     case 208:
69235     case 214:
69236 {sqlite3IdListDelete((yypminor->yy432));}
69237       break;
69238     case 231:
69239     case 236:
69240 {sqlite3DeleteTriggerStep((yypminor->yy243));}
69241       break;
69242     case 233:
69243 {sqlite3IdListDelete((yypminor->yy370).b);}
69244       break;
69245     case 238:
69246 {sqlite3ExprDelete((yypminor->yy386));}
69247       break;
69248     default:  break;   /* If no destructor action specified: do nothing */
69249   }
69250 }
69251
69252 /*
69253 ** Pop the parser's stack once.
69254 **
69255 ** If there is a destructor routine associated with the token which
69256 ** is popped from the stack, then call it.
69257 **
69258 ** Return the major token number for the symbol popped.
69259 */
69260 static int yy_pop_parser_stack(yyParser *pParser){
69261   YYCODETYPE yymajor;
69262   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
69263
69264   if( pParser->yyidx<0 ) return 0;
69265 #ifndef NDEBUG
69266   if( yyTraceFILE && pParser->yyidx>=0 ){
69267     fprintf(yyTraceFILE,"%sPopping %s\n",
69268       yyTracePrompt,
69269       yyTokenName[yytos->major]);
69270   }
69271 #endif
69272   yymajor = yytos->major;
69273   yy_destructor( yymajor, &yytos->minor);
69274   pParser->yyidx--;
69275   return yymajor;
69276 }
69277
69278 /* 
69279 ** Deallocate and destroy a parser.  Destructors are all called for
69280 ** all stack elements before shutting the parser down.
69281 **
69282 ** Inputs:
69283 ** <ul>
69284 ** <li>  A pointer to the parser.  This should be a pointer
69285 **       obtained from sqlite3ParserAlloc.
69286 ** <li>  A pointer to a function used to reclaim memory obtained
69287 **       from malloc.
69288 ** </ul>
69289 */
69290 SQLITE_PRIVATE void sqlite3ParserFree(
69291   void *p,                    /* The parser to be deleted */
69292   void (*freeProc)(void*)     /* Function used to reclaim memory */
69293 ){
69294   yyParser *pParser = (yyParser*)p;
69295   if( pParser==0 ) return;
69296   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
69297 #if YYSTACKDEPTH<=0
69298   free(pParser->yystack);
69299 #endif
69300   (*freeProc)((void*)pParser);
69301 }
69302
69303 /*
69304 ** Find the appropriate action for a parser given the terminal
69305 ** look-ahead token iLookAhead.
69306 **
69307 ** If the look-ahead token is YYNOCODE, then check to see if the action is
69308 ** independent of the look-ahead.  If it is, return the action, otherwise
69309 ** return YY_NO_ACTION.
69310 */
69311 static int yy_find_shift_action(
69312   yyParser *pParser,        /* The parser */
69313   YYCODETYPE iLookAhead     /* The look-ahead token */
69314 ){
69315   int i;
69316   int stateno = pParser->yystack[pParser->yyidx].stateno;
69317  
69318   if( stateno>YY_SHIFT_MAX || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
69319     return yy_default[stateno];
69320   }
69321   if( iLookAhead==YYNOCODE ){
69322     return YY_NO_ACTION;
69323   }
69324   i += iLookAhead;
69325   if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
69326     if( iLookAhead>0 ){
69327 #ifdef YYFALLBACK
69328       int iFallback;            /* Fallback token */
69329       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
69330              && (iFallback = yyFallback[iLookAhead])!=0 ){
69331 #ifndef NDEBUG
69332         if( yyTraceFILE ){
69333           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
69334              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
69335         }
69336 #endif
69337         return yy_find_shift_action(pParser, iFallback);
69338       }
69339 #endif
69340 #ifdef YYWILDCARD
69341       {
69342         int j = i - iLookAhead + YYWILDCARD;
69343         if( j>=0 && j<YY_SZ_ACTTAB && yy_lookahead[j]==YYWILDCARD ){
69344 #ifndef NDEBUG
69345           if( yyTraceFILE ){
69346             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
69347                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
69348           }
69349 #endif /* NDEBUG */
69350           return yy_action[j];
69351         }
69352       }
69353 #endif /* YYWILDCARD */
69354     }
69355     return yy_default[stateno];
69356   }else{
69357     return yy_action[i];
69358   }
69359 }
69360
69361 /*
69362 ** Find the appropriate action for a parser given the non-terminal
69363 ** look-ahead token iLookAhead.
69364 **
69365 ** If the look-ahead token is YYNOCODE, then check to see if the action is
69366 ** independent of the look-ahead.  If it is, return the action, otherwise
69367 ** return YY_NO_ACTION.
69368 */
69369 static int yy_find_reduce_action(
69370   int stateno,              /* Current state number */
69371   YYCODETYPE iLookAhead     /* The look-ahead token */
69372 ){
69373   int i;
69374   /* int stateno = pParser->yystack[pParser->yyidx].stateno; */
69375  
69376   if( stateno>YY_REDUCE_MAX ||
69377       (i = yy_reduce_ofst[stateno])==YY_REDUCE_USE_DFLT ){
69378     return yy_default[stateno];
69379   }
69380   if( iLookAhead==YYNOCODE ){
69381     return YY_NO_ACTION;
69382   }
69383   i += iLookAhead;
69384   if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
69385     return yy_default[stateno];
69386   }else{
69387     return yy_action[i];
69388   }
69389 }
69390
69391 /*
69392 ** The following routine is called if the stack overflows.
69393 */
69394 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
69395    sqlite3ParserARG_FETCH;
69396    yypParser->yyidx--;
69397 #ifndef NDEBUG
69398    if( yyTraceFILE ){
69399      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
69400    }
69401 #endif
69402    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
69403    /* Here code is inserted which will execute if the parser
69404    ** stack every overflows */
69405
69406   sqlite3ErrorMsg(pParse, "parser stack overflow");
69407   pParse->parseError = 1;
69408    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
69409 }
69410
69411 /*
69412 ** Perform a shift action.
69413 */
69414 static void yy_shift(
69415   yyParser *yypParser,          /* The parser to be shifted */
69416   int yyNewState,               /* The new state to shift in */
69417   int yyMajor,                  /* The major token to shift in */
69418   YYMINORTYPE *yypMinor         /* Pointer ot the minor token to shift in */
69419 ){
69420   yyStackEntry *yytos;
69421   yypParser->yyidx++;
69422 #if YYSTACKDEPTH>0 
69423   if( yypParser->yyidx>=YYSTACKDEPTH ){
69424     yyStackOverflow(yypParser, yypMinor);
69425     return;
69426   }
69427 #else
69428   if( yypParser->yyidx>=yypParser->yystksz ){
69429     yyGrowStack(yypParser);
69430     if( yypParser->yyidx>=yypParser->yystksz ){
69431       yyStackOverflow(yypParser, yypMinor);
69432       return;
69433     }
69434   }
69435 #endif
69436   yytos = &yypParser->yystack[yypParser->yyidx];
69437   yytos->stateno = yyNewState;
69438   yytos->major = yyMajor;
69439   yytos->minor = *yypMinor;
69440 #ifndef NDEBUG
69441   if( yyTraceFILE && yypParser->yyidx>0 ){
69442     int i;
69443     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
69444     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
69445     for(i=1; i<=yypParser->yyidx; i++)
69446       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
69447     fprintf(yyTraceFILE,"\n");
69448   }
69449 #endif
69450 }
69451
69452 /* The following table contains information about every rule that
69453 ** is used during the reduce.
69454 */
69455 static const struct {
69456   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
69457   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
69458 } yyRuleInfo[] = {
69459   { 139, 1 },
69460   { 140, 2 },
69461   { 140, 1 },
69462   { 142, 1 },
69463   { 141, 1 },
69464   { 141, 3 },
69465   { 144, 0 },
69466   { 144, 1 },
69467   { 144, 3 },
69468   { 143, 3 },
69469   { 146, 0 },
69470   { 146, 1 },
69471   { 146, 2 },
69472   { 145, 0 },
69473   { 145, 1 },
69474   { 145, 1 },
69475   { 145, 1 },
69476   { 143, 2 },
69477   { 143, 2 },
69478   { 143, 2 },
69479   { 143, 2 },
69480   { 148, 6 },
69481   { 151, 0 },
69482   { 151, 3 },
69483   { 150, 1 },
69484   { 150, 0 },
69485   { 149, 4 },
69486   { 149, 2 },
69487   { 153, 3 },
69488   { 153, 1 },
69489   { 156, 3 },
69490   { 157, 1 },
69491   { 160, 1 },
69492   { 161, 1 },
69493   { 147, 1 },
69494   { 147, 1 },
69495   { 147, 1 },
69496   { 158, 0 },
69497   { 158, 1 },
69498   { 162, 1 },
69499   { 162, 4 },
69500   { 162, 6 },
69501   { 163, 1 },
69502   { 163, 2 },
69503   { 164, 1 },
69504   { 164, 1 },
69505   { 159, 2 },
69506   { 159, 0 },
69507   { 167, 3 },
69508   { 167, 1 },
69509   { 168, 2 },
69510   { 168, 4 },
69511   { 168, 3 },
69512   { 168, 3 },
69513   { 168, 2 },
69514   { 168, 2 },
69515   { 168, 3 },
69516   { 168, 5 },
69517   { 168, 2 },
69518   { 168, 4 },
69519   { 168, 4 },
69520   { 168, 1 },
69521   { 168, 2 },
69522   { 173, 0 },
69523   { 173, 1 },
69524   { 175, 0 },
69525   { 175, 2 },
69526   { 177, 2 },
69527   { 177, 3 },
69528   { 177, 3 },
69529   { 177, 3 },
69530   { 178, 2 },
69531   { 178, 2 },
69532   { 178, 1 },
69533   { 178, 1 },
69534   { 176, 3 },
69535   { 176, 2 },
69536   { 179, 0 },
69537   { 179, 2 },
69538   { 179, 2 },
69539   { 154, 0 },
69540   { 154, 2 },
69541   { 180, 3 },
69542   { 180, 2 },
69543   { 180, 1 },
69544   { 181, 2 },
69545   { 181, 7 },
69546   { 181, 5 },
69547   { 181, 5 },
69548   { 181, 10 },
69549   { 183, 0 },
69550   { 183, 1 },
69551   { 171, 0 },
69552   { 171, 3 },
69553   { 184, 0 },
69554   { 184, 2 },
69555   { 185, 1 },
69556   { 185, 1 },
69557   { 185, 1 },
69558   { 143, 4 },
69559   { 187, 2 },
69560   { 187, 0 },
69561   { 143, 8 },
69562   { 143, 4 },
69563   { 143, 1 },
69564   { 155, 1 },
69565   { 155, 3 },
69566   { 190, 1 },
69567   { 190, 2 },
69568   { 190, 1 },
69569   { 189, 9 },
69570   { 191, 1 },
69571   { 191, 1 },
69572   { 191, 0 },
69573   { 199, 2 },
69574   { 199, 0 },
69575   { 192, 3 },
69576   { 192, 2 },
69577   { 192, 4 },
69578   { 200, 2 },
69579   { 200, 1 },
69580   { 200, 0 },
69581   { 193, 0 },
69582   { 193, 2 },
69583   { 202, 2 },
69584   { 202, 0 },
69585   { 201, 6 },
69586   { 201, 7 },
69587   { 206, 1 },
69588   { 206, 1 },
69589   { 152, 0 },
69590   { 152, 2 },
69591   { 188, 2 },
69592   { 203, 1 },
69593   { 203, 2 },
69594   { 203, 3 },
69595   { 203, 4 },
69596   { 204, 2 },
69597   { 204, 0 },
69598   { 205, 4 },
69599   { 205, 0 },
69600   { 197, 0 },
69601   { 197, 3 },
69602   { 209, 4 },
69603   { 209, 2 },
69604   { 210, 1 },
69605   { 172, 1 },
69606   { 172, 1 },
69607   { 172, 0 },
69608   { 195, 0 },
69609   { 195, 3 },
69610   { 196, 0 },
69611   { 196, 2 },
69612   { 198, 0 },
69613   { 198, 2 },
69614   { 198, 4 },
69615   { 198, 4 },
69616   { 143, 4 },
69617   { 194, 0 },
69618   { 194, 2 },
69619   { 143, 6 },
69620   { 212, 5 },
69621   { 212, 3 },
69622   { 143, 8 },
69623   { 143, 5 },
69624   { 143, 6 },
69625   { 213, 2 },
69626   { 213, 1 },
69627   { 215, 3 },
69628   { 215, 1 },
69629   { 214, 0 },
69630   { 214, 3 },
69631   { 208, 3 },
69632   { 208, 1 },
69633   { 170, 1 },
69634   { 170, 3 },
69635   { 169, 1 },
69636   { 170, 1 },
69637   { 170, 1 },
69638   { 170, 3 },
69639   { 170, 5 },
69640   { 169, 1 },
69641   { 169, 1 },
69642   { 170, 1 },
69643   { 170, 1 },
69644   { 170, 3 },
69645   { 170, 6 },
69646   { 170, 5 },
69647   { 170, 4 },
69648   { 169, 1 },
69649   { 170, 3 },
69650   { 170, 3 },
69651   { 170, 3 },
69652   { 170, 3 },
69653   { 170, 3 },
69654   { 170, 3 },
69655   { 170, 3 },
69656   { 170, 3 },
69657   { 217, 1 },
69658   { 217, 2 },
69659   { 217, 1 },
69660   { 217, 2 },
69661   { 218, 2 },
69662   { 218, 0 },
69663   { 170, 4 },
69664   { 170, 2 },
69665   { 170, 3 },
69666   { 170, 3 },
69667   { 170, 4 },
69668   { 170, 2 },
69669   { 170, 2 },
69670   { 170, 2 },
69671   { 170, 2 },
69672   { 219, 1 },
69673   { 219, 2 },
69674   { 170, 5 },
69675   { 220, 1 },
69676   { 220, 2 },
69677   { 170, 5 },
69678   { 170, 3 },
69679   { 170, 5 },
69680   { 170, 4 },
69681   { 170, 4 },
69682   { 170, 5 },
69683   { 222, 5 },
69684   { 222, 4 },
69685   { 223, 2 },
69686   { 223, 0 },
69687   { 221, 1 },
69688   { 221, 0 },
69689   { 216, 1 },
69690   { 216, 0 },
69691   { 211, 3 },
69692   { 211, 1 },
69693   { 143, 11 },
69694   { 224, 1 },
69695   { 224, 0 },
69696   { 174, 0 },
69697   { 174, 3 },
69698   { 182, 5 },
69699   { 182, 3 },
69700   { 225, 1 },
69701   { 226, 0 },
69702   { 226, 2 },
69703   { 143, 4 },
69704   { 143, 1 },
69705   { 143, 2 },
69706   { 143, 5 },
69707   { 143, 5 },
69708   { 143, 5 },
69709   { 143, 6 },
69710   { 143, 3 },
69711   { 227, 1 },
69712   { 227, 1 },
69713   { 165, 2 },
69714   { 166, 2 },
69715   { 229, 1 },
69716   { 228, 1 },
69717   { 228, 0 },
69718   { 143, 5 },
69719   { 230, 11 },
69720   { 232, 1 },
69721   { 232, 1 },
69722   { 232, 2 },
69723   { 232, 0 },
69724   { 233, 1 },
69725   { 233, 1 },
69726   { 233, 3 },
69727   { 234, 0 },
69728   { 234, 3 },
69729   { 235, 0 },
69730   { 235, 2 },
69731   { 231, 3 },
69732   { 231, 0 },
69733   { 236, 6 },
69734   { 236, 8 },
69735   { 236, 5 },
69736   { 236, 4 },
69737   { 236, 1 },
69738   { 170, 4 },
69739   { 170, 6 },
69740   { 186, 1 },
69741   { 186, 1 },
69742   { 186, 1 },
69743   { 143, 4 },
69744   { 143, 6 },
69745   { 143, 3 },
69746   { 238, 0 },
69747   { 238, 2 },
69748   { 237, 1 },
69749   { 237, 0 },
69750   { 143, 1 },
69751   { 143, 3 },
69752   { 143, 1 },
69753   { 143, 3 },
69754   { 143, 6 },
69755   { 143, 6 },
69756   { 239, 1 },
69757   { 240, 0 },
69758   { 240, 1 },
69759   { 143, 1 },
69760   { 143, 4 },
69761   { 241, 7 },
69762   { 242, 1 },
69763   { 242, 3 },
69764   { 243, 0 },
69765   { 243, 2 },
69766   { 244, 1 },
69767   { 244, 3 },
69768   { 245, 1 },
69769   { 246, 0 },
69770   { 246, 2 },
69771 };
69772
69773 static void yy_accept(yyParser*);  /* Forward Declaration */
69774
69775 /*
69776 ** Perform a reduce action and the shift that must immediately
69777 ** follow the reduce.
69778 */
69779 static void yy_reduce(
69780   yyParser *yypParser,         /* The parser */
69781   int yyruleno                 /* Number of the rule by which to reduce */
69782 ){
69783   int yygoto;                     /* The next state */
69784   int yyact;                      /* The next action */
69785   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
69786   yyStackEntry *yymsp;            /* The top of the parser's stack */
69787   int yysize;                     /* Amount to pop the stack */
69788   sqlite3ParserARG_FETCH;
69789   yymsp = &yypParser->yystack[yypParser->yyidx];
69790 #ifndef NDEBUG
69791   if( yyTraceFILE && yyruleno>=0 
69792         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
69793     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
69794       yyRuleName[yyruleno]);
69795   }
69796 #endif /* NDEBUG */
69797
69798   /* Silence complaints from purify about yygotominor being uninitialized
69799   ** in some cases when it is copied into the stack after the following
69800   ** switch.  yygotominor is uninitialized when a rule reduces that does
69801   ** not set the value of its left-hand side nonterminal.  Leaving the
69802   ** value of the nonterminal uninitialized is utterly harmless as long
69803   ** as the value is never used.  So really the only thing this code
69804   ** accomplishes is to quieten purify.  
69805   **
69806   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
69807   ** without this code, their parser segfaults.  I'm not sure what there
69808   ** parser is doing to make this happen.  This is the second bug report
69809   ** from wireshark this week.  Clearly they are stressing Lemon in ways
69810   ** that it has not been previously stressed...  (SQLite ticket #2172)
69811   */
69812   memset(&yygotominor, 0, sizeof(yygotominor));
69813
69814
69815   switch( yyruleno ){
69816   /* Beginning here are the reduction cases.  A typical example
69817   ** follows:
69818   **   case 0:
69819   **  #line <lineno> <grammarfile>
69820   **     { ... }           // User supplied code
69821   **  #line <lineno> <thisfile>
69822   **     break;
69823   */
69824       case 0:
69825       case 1:
69826       case 2:
69827       case 4:
69828       case 5:
69829       case 10:
69830       case 11:
69831       case 12:
69832       case 20:
69833       case 28:
69834       case 29:
69835       case 37:
69836       case 44:
69837       case 45:
69838       case 46:
69839       case 47:
69840       case 48:
69841       case 49:
69842       case 55:
69843       case 82:
69844       case 83:
69845       case 84:
69846       case 85:
69847       case 257:
69848       case 258:
69849       case 268:
69850       case 269:
69851       case 289:
69852       case 290:
69853       case 298:
69854       case 299:
69855       case 303:
69856       case 304:
69857       case 306:
69858       case 310:
69859 {
69860 }
69861         break;
69862       case 3:
69863 { sqlite3FinishCoding(pParse); }
69864         break;
69865       case 6:
69866 { sqlite3BeginParse(pParse, 0); }
69867         break;
69868       case 7:
69869 { sqlite3BeginParse(pParse, 1); }
69870         break;
69871       case 8:
69872 { sqlite3BeginParse(pParse, 2); }
69873         break;
69874       case 9:
69875 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy46);}
69876         break;
69877       case 13:
69878 {yygotominor.yy46 = TK_DEFERRED;}
69879         break;
69880       case 14:
69881       case 15:
69882       case 16:
69883       case 107:
69884       case 109:
69885 {yygotominor.yy46 = yymsp[0].major;}
69886         break;
69887       case 17:
69888       case 18:
69889 {sqlite3CommitTransaction(pParse);}
69890         break;
69891       case 19:
69892 {sqlite3RollbackTransaction(pParse);}
69893         break;
69894       case 21:
69895 {
69896    sqlite3StartTable(pParse,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410,yymsp[-4].minor.yy46,0,0,yymsp[-2].minor.yy46);
69897 }
69898         break;
69899       case 22:
69900       case 25:
69901       case 63:
69902       case 77:
69903       case 79:
69904       case 90:
69905       case 101:
69906       case 112:
69907       case 113:
69908       case 213:
69909       case 216:
69910 {yygotominor.yy46 = 0;}
69911         break;
69912       case 23:
69913       case 24:
69914       case 64:
69915       case 78:
69916       case 100:
69917       case 111:
69918       case 214:
69919       case 217:
69920 {yygotominor.yy46 = 1;}
69921         break;
69922       case 26:
69923 {
69924   sqlite3EndTable(pParse,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy0,0);
69925 }
69926         break;
69927       case 27:
69928 {
69929   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy219);
69930   sqlite3SelectDelete(yymsp[0].minor.yy219);
69931 }
69932         break;
69933       case 30:
69934 {
69935   yygotominor.yy410.z = yymsp[-2].minor.yy410.z;
69936   yygotominor.yy410.n = (pParse->sLastToken.z-yymsp[-2].minor.yy410.z) + pParse->sLastToken.n;
69937 }
69938         break;
69939       case 31:
69940 {
69941   sqlite3AddColumn(pParse,&yymsp[0].minor.yy410);
69942   yygotominor.yy410 = yymsp[0].minor.yy410;
69943 }
69944         break;
69945       case 32:
69946       case 33:
69947       case 34:
69948       case 35:
69949       case 36:
69950       case 256:
69951 {yygotominor.yy410 = yymsp[0].minor.yy0;}
69952         break;
69953       case 38:
69954 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy410);}
69955         break;
69956       case 39:
69957       case 42:
69958       case 119:
69959       case 120:
69960       case 131:
69961       case 241:
69962       case 243:
69963       case 252:
69964       case 253:
69965       case 254:
69966       case 255:
69967 {yygotominor.yy410 = yymsp[0].minor.yy410;}
69968         break;
69969       case 40:
69970 {
69971   yygotominor.yy410.z = yymsp[-3].minor.yy410.z;
69972   yygotominor.yy410.n = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy410.z;
69973 }
69974         break;
69975       case 41:
69976 {
69977   yygotominor.yy410.z = yymsp[-5].minor.yy410.z;
69978   yygotominor.yy410.n = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy410.z;
69979 }
69980         break;
69981       case 43:
69982 {yygotominor.yy410.z=yymsp[-1].minor.yy410.z; yygotominor.yy410.n=yymsp[0].minor.yy410.n+(yymsp[0].minor.yy410.z-yymsp[-1].minor.yy410.z);}
69983         break;
69984       case 50:
69985       case 52:
69986 {sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy172);}
69987         break;
69988       case 51:
69989 {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy172);}
69990         break;
69991       case 53:
69992 {
69993   Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy172, 0, 0);
69994   sqlite3AddDefaultValue(pParse,p);
69995 }
69996         break;
69997       case 54:
69998 {
69999   Expr *p = sqlite3PExpr(pParse, TK_STRING, 0, 0, &yymsp[0].minor.yy410);
70000   sqlite3AddDefaultValue(pParse,p);
70001 }
70002         break;
70003       case 56:
70004 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy46);}
70005         break;
70006       case 57:
70007 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy46,yymsp[0].minor.yy46,yymsp[-2].minor.yy46);}
70008         break;
70009       case 58:
70010 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy46,0,0,0,0);}
70011         break;
70012       case 59:
70013 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy172);}
70014         break;
70015       case 60:
70016 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy410,yymsp[-1].minor.yy174,yymsp[0].minor.yy46);}
70017         break;
70018       case 61:
70019 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy46);}
70020         break;
70021       case 62:
70022 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy410);}
70023         break;
70024       case 65:
70025 { yygotominor.yy46 = OE_Restrict * 0x010101; }
70026         break;
70027       case 66:
70028 { yygotominor.yy46 = (yymsp[-1].minor.yy46 & yymsp[0].minor.yy405.mask) | yymsp[0].minor.yy405.value; }
70029         break;
70030       case 67:
70031 { yygotominor.yy405.value = 0;     yygotominor.yy405.mask = 0x000000; }
70032         break;
70033       case 68:
70034 { yygotominor.yy405.value = yymsp[0].minor.yy46;     yygotominor.yy405.mask = 0x0000ff; }
70035         break;
70036       case 69:
70037 { yygotominor.yy405.value = yymsp[0].minor.yy46<<8;  yygotominor.yy405.mask = 0x00ff00; }
70038         break;
70039       case 70:
70040 { yygotominor.yy405.value = yymsp[0].minor.yy46<<16; yygotominor.yy405.mask = 0xff0000; }
70041         break;
70042       case 71:
70043 { yygotominor.yy46 = OE_SetNull; }
70044         break;
70045       case 72:
70046 { yygotominor.yy46 = OE_SetDflt; }
70047         break;
70048       case 73:
70049 { yygotominor.yy46 = OE_Cascade; }
70050         break;
70051       case 74:
70052 { yygotominor.yy46 = OE_Restrict; }
70053         break;
70054       case 75:
70055       case 76:
70056       case 91:
70057       case 93:
70058       case 95:
70059       case 96:
70060       case 166:
70061 {yygotominor.yy46 = yymsp[0].minor.yy46;}
70062         break;
70063       case 80:
70064 {yygotominor.yy410.n = 0; yygotominor.yy410.z = 0;}
70065         break;
70066       case 81:
70067 {yygotominor.yy410 = yymsp[-1].minor.yy0;}
70068         break;
70069       case 86:
70070 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy174,yymsp[0].minor.yy46,yymsp[-2].minor.yy46,0);}
70071         break;
70072       case 87:
70073 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy174,yymsp[0].minor.yy46,0,0,0,0);}
70074         break;
70075       case 88:
70076 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy172);}
70077         break;
70078       case 89:
70079 {
70080     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy174, &yymsp[-3].minor.yy410, yymsp[-2].minor.yy174, yymsp[-1].minor.yy46);
70081     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy46);
70082 }
70083         break;
70084       case 92:
70085       case 94:
70086 {yygotominor.yy46 = OE_Default;}
70087         break;
70088       case 97:
70089 {yygotominor.yy46 = OE_Ignore;}
70090         break;
70091       case 98:
70092       case 167:
70093 {yygotominor.yy46 = OE_Replace;}
70094         break;
70095       case 99:
70096 {
70097   sqlite3DropTable(pParse, yymsp[0].minor.yy373, 0, yymsp[-1].minor.yy46);
70098 }
70099         break;
70100       case 102:
70101 {
70102   sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy410, &yymsp[-2].minor.yy410, yymsp[0].minor.yy219, yymsp[-6].minor.yy46, yymsp[-4].minor.yy46);
70103 }
70104         break;
70105       case 103:
70106 {
70107   sqlite3DropTable(pParse, yymsp[0].minor.yy373, 1, yymsp[-1].minor.yy46);
70108 }
70109         break;
70110       case 104:
70111 {
70112   sqlite3Select(pParse, yymsp[0].minor.yy219, SRT_Callback, 0, 0, 0, 0, 0);
70113   sqlite3SelectDelete(yymsp[0].minor.yy219);
70114 }
70115         break;
70116       case 105:
70117       case 128:
70118 {yygotominor.yy219 = yymsp[0].minor.yy219;}
70119         break;
70120       case 106:
70121 {
70122   if( yymsp[0].minor.yy219 ){
70123     yymsp[0].minor.yy219->op = yymsp[-1].minor.yy46;
70124     yymsp[0].minor.yy219->pPrior = yymsp[-2].minor.yy219;
70125   }else{
70126     sqlite3SelectDelete(yymsp[-2].minor.yy219);
70127   }
70128   yygotominor.yy219 = yymsp[0].minor.yy219;
70129 }
70130         break;
70131       case 108:
70132 {yygotominor.yy46 = TK_ALL;}
70133         break;
70134       case 110:
70135 {
70136   yygotominor.yy219 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy174,yymsp[-5].minor.yy373,yymsp[-4].minor.yy172,yymsp[-3].minor.yy174,yymsp[-2].minor.yy172,yymsp[-1].minor.yy174,yymsp[-7].minor.yy46,yymsp[0].minor.yy234.pLimit,yymsp[0].minor.yy234.pOffset);
70137 }
70138         break;
70139       case 114:
70140       case 238:
70141 {yygotominor.yy174 = yymsp[-1].minor.yy174;}
70142         break;
70143       case 115:
70144       case 141:
70145       case 149:
70146       case 231:
70147       case 237:
70148 {yygotominor.yy174 = 0;}
70149         break;
70150       case 116:
70151 {
70152    yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy174,yymsp[-1].minor.yy172,yymsp[0].minor.yy410.n?&yymsp[0].minor.yy410:0);
70153 }
70154         break;
70155       case 117:
70156 {
70157   Expr *p = sqlite3PExpr(pParse, TK_ALL, 0, 0, 0);
70158   yygotominor.yy174 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy174, p, 0);
70159 }
70160         break;
70161       case 118:
70162 {
70163   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, 0);
70164   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy410);
70165   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
70166   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy174, pDot, 0);
70167 }
70168         break;
70169       case 121:
70170 {yygotominor.yy410.n = 0;}
70171         break;
70172       case 122:
70173 {yygotominor.yy373 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy373));}
70174         break;
70175       case 123:
70176 {
70177   yygotominor.yy373 = yymsp[0].minor.yy373;
70178   sqlite3SrcListShiftJoinType(yygotominor.yy373);
70179 }
70180         break;
70181       case 124:
70182 {
70183    yygotominor.yy373 = yymsp[-1].minor.yy373;
70184    if( yygotominor.yy373 && yygotominor.yy373->nSrc>0 ) yygotominor.yy373->a[yygotominor.yy373->nSrc-1].jointype = yymsp[0].minor.yy46;
70185 }
70186         break;
70187       case 125:
70188 {yygotominor.yy373 = 0;}
70189         break;
70190       case 126:
70191 {
70192   yygotominor.yy373 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-5].minor.yy373,&yymsp[-4].minor.yy410,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,0,yymsp[-1].minor.yy172,yymsp[0].minor.yy432);
70193 }
70194         break;
70195       case 127:
70196 {
70197     yygotominor.yy373 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy373,0,0,&yymsp[-2].minor.yy410,yymsp[-4].minor.yy219,yymsp[-1].minor.yy172,yymsp[0].minor.yy432);
70198   }
70199         break;
70200       case 129:
70201 {
70202      sqlite3SrcListShiftJoinType(yymsp[0].minor.yy373);
70203      yygotominor.yy219 = sqlite3SelectNew(pParse,0,yymsp[0].minor.yy373,0,0,0,0,0,0,0);
70204   }
70205         break;
70206       case 130:
70207 {yygotominor.yy410.z=0; yygotominor.yy410.n=0;}
70208         break;
70209       case 132:
70210 {yygotominor.yy373 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410);}
70211         break;
70212       case 133:
70213 { yygotominor.yy46 = JT_INNER; }
70214         break;
70215       case 134:
70216 { yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
70217         break;
70218       case 135:
70219 { yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy410,0); }
70220         break;
70221       case 136:
70222 { yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy410,&yymsp[-1].minor.yy410); }
70223         break;
70224       case 137:
70225       case 145:
70226       case 152:
70227       case 159:
70228       case 174:
70229       case 202:
70230       case 226:
70231       case 228:
70232 {yygotominor.yy172 = yymsp[0].minor.yy172;}
70233         break;
70234       case 138:
70235       case 151:
70236       case 158:
70237       case 203:
70238       case 227:
70239       case 229:
70240 {yygotominor.yy172 = 0;}
70241         break;
70242       case 139:
70243       case 171:
70244 {yygotominor.yy432 = yymsp[-1].minor.yy432;}
70245         break;
70246       case 140:
70247       case 170:
70248 {yygotominor.yy432 = 0;}
70249         break;
70250       case 142:
70251       case 150:
70252       case 230:
70253 {yygotominor.yy174 = yymsp[0].minor.yy174;}
70254         break;
70255       case 143:
70256 {
70257   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy174,yymsp[-1].minor.yy172,0);
70258   if( yygotominor.yy174 ) yygotominor.yy174->a[yygotominor.yy174->nExpr-1].sortOrder = yymsp[0].minor.yy46;
70259 }
70260         break;
70261       case 144:
70262 {
70263   yygotominor.yy174 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy172,0);
70264   if( yygotominor.yy174 && yygotominor.yy174->a ) yygotominor.yy174->a[0].sortOrder = yymsp[0].minor.yy46;
70265 }
70266         break;
70267       case 146:
70268       case 148:
70269 {yygotominor.yy46 = SQLITE_SO_ASC;}
70270         break;
70271       case 147:
70272 {yygotominor.yy46 = SQLITE_SO_DESC;}
70273         break;
70274       case 153:
70275 {yygotominor.yy234.pLimit = 0; yygotominor.yy234.pOffset = 0;}
70276         break;
70277       case 154:
70278 {yygotominor.yy234.pLimit = yymsp[0].minor.yy172; yygotominor.yy234.pOffset = 0;}
70279         break;
70280       case 155:
70281 {yygotominor.yy234.pLimit = yymsp[-2].minor.yy172; yygotominor.yy234.pOffset = yymsp[0].minor.yy172;}
70282         break;
70283       case 156:
70284 {yygotominor.yy234.pOffset = yymsp[-2].minor.yy172; yygotominor.yy234.pLimit = yymsp[0].minor.yy172;}
70285         break;
70286       case 157:
70287 {sqlite3DeleteFrom(pParse,yymsp[-1].minor.yy373,yymsp[0].minor.yy172);}
70288         break;
70289       case 160:
70290 {
70291   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy174,SQLITE_MAX_COLUMN,"set list"); 
70292   sqlite3Update(pParse,yymsp[-3].minor.yy373,yymsp[-1].minor.yy174,yymsp[0].minor.yy172,yymsp[-4].minor.yy46);
70293 }
70294         break;
70295       case 161:
70296 {yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy174,yymsp[0].minor.yy172,&yymsp[-2].minor.yy410);}
70297         break;
70298       case 162:
70299 {yygotominor.yy174 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy172,&yymsp[-2].minor.yy410);}
70300         break;
70301       case 163:
70302 {sqlite3Insert(pParse, yymsp[-5].minor.yy373, yymsp[-1].minor.yy174, 0, yymsp[-4].minor.yy432, yymsp[-7].minor.yy46);}
70303         break;
70304       case 164:
70305 {sqlite3Insert(pParse, yymsp[-2].minor.yy373, 0, yymsp[0].minor.yy219, yymsp[-1].minor.yy432, yymsp[-4].minor.yy46);}
70306         break;
70307       case 165:
70308 {sqlite3Insert(pParse, yymsp[-3].minor.yy373, 0, 0, yymsp[-2].minor.yy432, yymsp[-5].minor.yy46);}
70309         break;
70310       case 168:
70311       case 232:
70312 {yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy174,yymsp[0].minor.yy172,0);}
70313         break;
70314       case 169:
70315       case 233:
70316 {yygotominor.yy174 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy172,0);}
70317         break;
70318       case 172:
70319 {yygotominor.yy432 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy432,&yymsp[0].minor.yy410);}
70320         break;
70321       case 173:
70322 {yygotominor.yy432 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy410);}
70323         break;
70324       case 175:
70325 {yygotominor.yy172 = yymsp[-1].minor.yy172; sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); }
70326         break;
70327       case 176:
70328       case 181:
70329       case 182:
70330 {yygotominor.yy172 = sqlite3PExpr(pParse, yymsp[0].major, 0, 0, &yymsp[0].minor.yy0);}
70331         break;
70332       case 177:
70333       case 178:
70334 {yygotominor.yy172 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);}
70335         break;
70336       case 179:
70337 {
70338   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy410);
70339   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy410);
70340   yygotominor.yy172 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
70341 }
70342         break;
70343       case 180:
70344 {
70345   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy410);
70346   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy410);
70347   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy410);
70348   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
70349   yygotominor.yy172 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
70350 }
70351         break;
70352       case 183:
70353 {yygotominor.yy172 = sqlite3RegisterExpr(pParse, &yymsp[0].minor.yy0);}
70354         break;
70355       case 184:
70356 {
70357   Token *pToken = &yymsp[0].minor.yy0;
70358   Expr *pExpr = yygotominor.yy172 = sqlite3PExpr(pParse, TK_VARIABLE, 0, 0, pToken);
70359   sqlite3ExprAssignVarNumber(pParse, pExpr);
70360 }
70361         break;
70362       case 185:
70363 {
70364   yygotominor.yy172 = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy172, &yymsp[0].minor.yy410);
70365 }
70366         break;
70367       case 186:
70368 {
70369   yygotominor.yy172 = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy172, 0, &yymsp[-1].minor.yy410);
70370   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
70371 }
70372         break;
70373       case 187:
70374 {
70375   if( yymsp[-1].minor.yy174 && yymsp[-1].minor.yy174->nExpr>SQLITE_MAX_FUNCTION_ARG ){
70376     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
70377   }
70378   yygotominor.yy172 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy174, &yymsp[-4].minor.yy0);
70379   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
70380   if( yymsp[-2].minor.yy46 && yygotominor.yy172 ){
70381     yygotominor.yy172->flags |= EP_Distinct;
70382   }
70383 }
70384         break;
70385       case 188:
70386 {
70387   yygotominor.yy172 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
70388   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
70389 }
70390         break;
70391       case 189:
70392 {
70393   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
70394   ** treated as functions that return constants */
70395   yygotominor.yy172 = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
70396   if( yygotominor.yy172 ){
70397     yygotominor.yy172->op = TK_CONST_FUNC;  
70398     yygotominor.yy172->span = yymsp[0].minor.yy0;
70399   }
70400 }
70401         break;
70402       case 190:
70403       case 191:
70404       case 192:
70405       case 193:
70406       case 194:
70407       case 195:
70408       case 196:
70409       case 197:
70410 {yygotominor.yy172 = sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy172,yymsp[0].minor.yy172,0);}
70411         break;
70412       case 198:
70413       case 200:
70414 {yygotominor.yy72.eOperator = yymsp[0].minor.yy0; yygotominor.yy72.not = 0;}
70415         break;
70416       case 199:
70417       case 201:
70418 {yygotominor.yy72.eOperator = yymsp[0].minor.yy0; yygotominor.yy72.not = 1;}
70419         break;
70420       case 204:
70421 {
70422   ExprList *pList;
70423   pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy172, 0);
70424   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-3].minor.yy172, 0);
70425   if( yymsp[0].minor.yy172 ){
70426     pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy172, 0);
70427   }
70428   yygotominor.yy172 = sqlite3ExprFunction(pParse, pList, &yymsp[-2].minor.yy72.eOperator);
70429   if( yymsp[-2].minor.yy72.not ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0);
70430   sqlite3ExprSpan(yygotominor.yy172, &yymsp[-3].minor.yy172->span, &yymsp[-1].minor.yy172->span);
70431   if( yygotominor.yy172 ) yygotominor.yy172->flags |= EP_InfixFunc;
70432 }
70433         break;
70434       case 205:
70435 {
70436   yygotominor.yy172 = sqlite3PExpr(pParse, yymsp[0].major, yymsp[-1].minor.yy172, 0, 0);
70437   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy172->span,&yymsp[0].minor.yy0);
70438 }
70439         break;
70440       case 206:
70441 {
70442   yygotominor.yy172 = sqlite3PExpr(pParse, TK_ISNULL, yymsp[-2].minor.yy172, 0, 0);
70443   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy172->span,&yymsp[0].minor.yy0);
70444 }
70445         break;
70446       case 207:
70447 {
70448   yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-2].minor.yy172, 0, 0);
70449   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy172->span,&yymsp[0].minor.yy0);
70450 }
70451         break;
70452       case 208:
70453 {
70454   yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-3].minor.yy172, 0, 0);
70455   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy172->span,&yymsp[0].minor.yy0);
70456 }
70457         break;
70458       case 209:
70459       case 210:
70460 {
70461   yygotominor.yy172 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy172, 0, 0);
70462   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy172->span);
70463 }
70464         break;
70465       case 211:
70466 {
70467   yygotominor.yy172 = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy172, 0, 0);
70468   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy172->span);
70469 }
70470         break;
70471       case 212:
70472 {
70473   yygotominor.yy172 = sqlite3PExpr(pParse, TK_UPLUS, yymsp[0].minor.yy172, 0, 0);
70474   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy172->span);
70475 }
70476         break;
70477       case 215:
70478 {
70479   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy172, 0);
70480   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy172, 0);
70481   yygotominor.yy172 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy172, 0, 0);
70482   if( yygotominor.yy172 ){
70483     yygotominor.yy172->pList = pList;
70484   }else{
70485     sqlite3ExprListDelete(pList);
70486   } 
70487   if( yymsp[-3].minor.yy46 ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0);
70488   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy172->span);
70489 }
70490         break;
70491       case 218:
70492 {
70493     yygotominor.yy172 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy172, 0, 0);
70494     if( yygotominor.yy172 ){
70495       yygotominor.yy172->pList = yymsp[-1].minor.yy174;
70496       sqlite3ExprSetHeight(yygotominor.yy172);
70497     }else{
70498       sqlite3ExprListDelete(yymsp[-1].minor.yy174);
70499     }
70500     if( yymsp[-3].minor.yy46 ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0);
70501     sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy0);
70502   }
70503         break;
70504       case 219:
70505 {
70506     yygotominor.yy172 = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
70507     if( yygotominor.yy172 ){
70508       yygotominor.yy172->pSelect = yymsp[-1].minor.yy219;
70509       sqlite3ExprSetHeight(yygotominor.yy172);
70510     }else{
70511       sqlite3SelectDelete(yymsp[-1].minor.yy219);
70512     }
70513     sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
70514   }
70515         break;
70516       case 220:
70517 {
70518     yygotominor.yy172 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy172, 0, 0);
70519     if( yygotominor.yy172 ){
70520       yygotominor.yy172->pSelect = yymsp[-1].minor.yy219;
70521       sqlite3ExprSetHeight(yygotominor.yy172);
70522     }else{
70523       sqlite3SelectDelete(yymsp[-1].minor.yy219);
70524     }
70525     if( yymsp[-3].minor.yy46 ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0);
70526     sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy0);
70527   }
70528         break;
70529       case 221:
70530 {
70531     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410);
70532     yygotominor.yy172 = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy172, 0, 0);
70533     if( yygotominor.yy172 ){
70534       yygotominor.yy172->pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
70535       sqlite3ExprSetHeight(yygotominor.yy172);
70536     }else{
70537       sqlite3SrcListDelete(pSrc);
70538     }
70539     if( yymsp[-2].minor.yy46 ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0);
70540     sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy172->span,yymsp[0].minor.yy410.z?&yymsp[0].minor.yy410:&yymsp[-1].minor.yy410);
70541   }
70542         break;
70543       case 222:
70544 {
70545     Expr *p = yygotominor.yy172 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
70546     if( p ){
70547       p->pSelect = yymsp[-1].minor.yy219;
70548       sqlite3ExprSpan(p,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
70549       sqlite3ExprSetHeight(yygotominor.yy172);
70550     }else{
70551       sqlite3SelectDelete(yymsp[-1].minor.yy219);
70552     }
70553   }
70554         break;
70555       case 223:
70556 {
70557   yygotominor.yy172 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy172, yymsp[-1].minor.yy172, 0);
70558   if( yygotominor.yy172 ){
70559     yygotominor.yy172->pList = yymsp[-2].minor.yy174;
70560     sqlite3ExprSetHeight(yygotominor.yy172);
70561   }else{
70562     sqlite3ExprListDelete(yymsp[-2].minor.yy174);
70563   }
70564   sqlite3ExprSpan(yygotominor.yy172, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
70565 }
70566         break;
70567       case 224:
70568 {
70569   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy174, yymsp[-2].minor.yy172, 0);
70570   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yygotominor.yy174, yymsp[0].minor.yy172, 0);
70571 }
70572         break;
70573       case 225:
70574 {
70575   yygotominor.yy174 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy172, 0);
70576   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yygotominor.yy174, yymsp[0].minor.yy172, 0);
70577 }
70578         break;
70579       case 234:
70580 {
70581   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy410, &yymsp[-5].minor.yy410, 
70582                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy410,0), yymsp[-1].minor.yy174, yymsp[-9].minor.yy46,
70583                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy46);
70584 }
70585         break;
70586       case 235:
70587       case 282:
70588 {yygotominor.yy46 = OE_Abort;}
70589         break;
70590       case 236:
70591 {yygotominor.yy46 = OE_None;}
70592         break;
70593       case 239:
70594 {
70595   Expr *p = 0;
70596   if( yymsp[-1].minor.yy410.n>0 ){
70597     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
70598     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy410);
70599   }
70600   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy174, p, &yymsp[-2].minor.yy410);
70601   sqlite3ExprListCheckLength(pParse, yygotominor.yy174, SQLITE_MAX_COLUMN, "index");
70602   if( yygotominor.yy174 ) yygotominor.yy174->a[yygotominor.yy174->nExpr-1].sortOrder = yymsp[0].minor.yy46;
70603 }
70604         break;
70605       case 240:
70606 {
70607   Expr *p = 0;
70608   if( yymsp[-1].minor.yy410.n>0 ){
70609     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
70610     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy410);
70611   }
70612   yygotominor.yy174 = sqlite3ExprListAppend(pParse,0, p, &yymsp[-2].minor.yy410);
70613   sqlite3ExprListCheckLength(pParse, yygotominor.yy174, SQLITE_MAX_COLUMN, "index");
70614   if( yygotominor.yy174 ) yygotominor.yy174->a[yygotominor.yy174->nExpr-1].sortOrder = yymsp[0].minor.yy46;
70615 }
70616         break;
70617       case 242:
70618 {yygotominor.yy410.z = 0; yygotominor.yy410.n = 0;}
70619         break;
70620       case 244:
70621 {sqlite3DropIndex(pParse, yymsp[0].minor.yy373, yymsp[-1].minor.yy46);}
70622         break;
70623       case 245:
70624       case 246:
70625 {sqlite3Vacuum(pParse);}
70626         break;
70627       case 247:
70628 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,&yymsp[0].minor.yy410,0);}
70629         break;
70630       case 248:
70631 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,&yymsp[0].minor.yy0,0);}
70632         break;
70633       case 249:
70634 {
70635   sqlite3Pragma(pParse,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,&yymsp[0].minor.yy410,1);
70636 }
70637         break;
70638       case 250:
70639 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy410,&yymsp[-3].minor.yy410,&yymsp[-1].minor.yy410,0);}
70640         break;
70641       case 251:
70642 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410,0,0);}
70643         break;
70644       case 259:
70645 {
70646   Token all;
70647   all.z = yymsp[-3].minor.yy410.z;
70648   all.n = (yymsp[0].minor.yy0.z - yymsp[-3].minor.yy410.z) + yymsp[0].minor.yy0.n;
70649   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy243, &all);
70650 }
70651         break;
70652       case 260:
70653 {
70654   sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy410, &yymsp[-6].minor.yy410, yymsp[-5].minor.yy46, yymsp[-4].minor.yy370.a, yymsp[-4].minor.yy370.b, yymsp[-2].minor.yy373, yymsp[0].minor.yy172, yymsp[-10].minor.yy46, yymsp[-8].minor.yy46);
70655   yygotominor.yy410 = (yymsp[-6].minor.yy410.n==0?yymsp[-7].minor.yy410:yymsp[-6].minor.yy410);
70656 }
70657         break;
70658       case 261:
70659       case 264:
70660 { yygotominor.yy46 = TK_BEFORE; }
70661         break;
70662       case 262:
70663 { yygotominor.yy46 = TK_AFTER;  }
70664         break;
70665       case 263:
70666 { yygotominor.yy46 = TK_INSTEAD;}
70667         break;
70668       case 265:
70669       case 266:
70670 {yygotominor.yy370.a = yymsp[0].major; yygotominor.yy370.b = 0;}
70671         break;
70672       case 267:
70673 {yygotominor.yy370.a = TK_UPDATE; yygotominor.yy370.b = yymsp[0].minor.yy432;}
70674         break;
70675       case 270:
70676 { yygotominor.yy172 = 0; }
70677         break;
70678       case 271:
70679 { yygotominor.yy172 = yymsp[0].minor.yy172; }
70680         break;
70681       case 272:
70682 {
70683   if( yymsp[-2].minor.yy243 ){
70684     yymsp[-2].minor.yy243->pLast->pNext = yymsp[-1].minor.yy243;
70685   }else{
70686     yymsp[-2].minor.yy243 = yymsp[-1].minor.yy243;
70687   }
70688   yymsp[-2].minor.yy243->pLast = yymsp[-1].minor.yy243;
70689   yygotominor.yy243 = yymsp[-2].minor.yy243;
70690 }
70691         break;
70692       case 273:
70693 { yygotominor.yy243 = 0; }
70694         break;
70695       case 274:
70696 { yygotominor.yy243 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-3].minor.yy410, yymsp[-1].minor.yy174, yymsp[0].minor.yy172, yymsp[-4].minor.yy46); }
70697         break;
70698       case 275:
70699 {yygotominor.yy243 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy410, yymsp[-4].minor.yy432, yymsp[-1].minor.yy174, 0, yymsp[-7].minor.yy46);}
70700         break;
70701       case 276:
70702 {yygotominor.yy243 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy410, yymsp[-1].minor.yy432, 0, yymsp[0].minor.yy219, yymsp[-4].minor.yy46);}
70703         break;
70704       case 277:
70705 {yygotominor.yy243 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-1].minor.yy410, yymsp[0].minor.yy172);}
70706         break;
70707       case 278:
70708 {yygotominor.yy243 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy219); }
70709         break;
70710       case 279:
70711 {
70712   yygotominor.yy172 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
70713   if( yygotominor.yy172 ){
70714     yygotominor.yy172->iColumn = OE_Ignore;
70715     sqlite3ExprSpan(yygotominor.yy172, &yymsp[-3].minor.yy0, &yymsp[0].minor.yy0);
70716   }
70717 }
70718         break;
70719       case 280:
70720 {
70721   yygotominor.yy172 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy410); 
70722   if( yygotominor.yy172 ) {
70723     yygotominor.yy172->iColumn = yymsp[-3].minor.yy46;
70724     sqlite3ExprSpan(yygotominor.yy172, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
70725   }
70726 }
70727         break;
70728       case 281:
70729 {yygotominor.yy46 = OE_Rollback;}
70730         break;
70731       case 283:
70732 {yygotominor.yy46 = OE_Fail;}
70733         break;
70734       case 284:
70735 {
70736   sqlite3DropTrigger(pParse,yymsp[0].minor.yy373,yymsp[-1].minor.yy46);
70737 }
70738         break;
70739       case 285:
70740 {
70741   sqlite3Attach(pParse, yymsp[-3].minor.yy172, yymsp[-1].minor.yy172, yymsp[0].minor.yy386);
70742 }
70743         break;
70744       case 286:
70745 {
70746   sqlite3Detach(pParse, yymsp[0].minor.yy172);
70747 }
70748         break;
70749       case 287:
70750 { yygotominor.yy386 = 0; }
70751         break;
70752       case 288:
70753 { yygotominor.yy386 = yymsp[0].minor.yy172; }
70754         break;
70755       case 291:
70756 {sqlite3Reindex(pParse, 0, 0);}
70757         break;
70758       case 292:
70759 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy410, &yymsp[0].minor.yy410);}
70760         break;
70761       case 293:
70762 {sqlite3Analyze(pParse, 0, 0);}
70763         break;
70764       case 294:
70765 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy410, &yymsp[0].minor.yy410);}
70766         break;
70767       case 295:
70768 {
70769   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy373,&yymsp[0].minor.yy410);
70770 }
70771         break;
70772       case 296:
70773 {
70774   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy410);
70775 }
70776         break;
70777       case 297:
70778 {
70779   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy373);
70780 }
70781         break;
70782       case 300:
70783 {sqlite3VtabFinishParse(pParse,0);}
70784         break;
70785       case 301:
70786 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
70787         break;
70788       case 302:
70789 {
70790     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy410, &yymsp[-2].minor.yy410, &yymsp[0].minor.yy410);
70791 }
70792         break;
70793       case 305:
70794 {sqlite3VtabArgInit(pParse);}
70795         break;
70796       case 307:
70797       case 308:
70798       case 309:
70799       case 311:
70800 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
70801         break;
70802   };
70803   yygoto = yyRuleInfo[yyruleno].lhs;
70804   yysize = yyRuleInfo[yyruleno].nrhs;
70805   yypParser->yyidx -= yysize;
70806   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,yygoto);
70807   if( yyact < YYNSTATE ){
70808 #ifdef NDEBUG
70809     /* If we are not debugging and the reduce action popped at least
70810     ** one element off the stack, then we can push the new element back
70811     ** onto the stack here, and skip the stack overflow test in yy_shift().
70812     ** That gives a significant speed improvement. */
70813     if( yysize ){
70814       yypParser->yyidx++;
70815       yymsp -= yysize-1;
70816       yymsp->stateno = yyact;
70817       yymsp->major = yygoto;
70818       yymsp->minor = yygotominor;
70819     }else
70820 #endif
70821     {
70822       yy_shift(yypParser,yyact,yygoto,&yygotominor);
70823     }
70824   }else if( yyact == YYNSTATE + YYNRULE + 1 ){
70825     yy_accept(yypParser);
70826   }
70827 }
70828
70829 /*
70830 ** The following code executes when the parse fails
70831 */
70832 static void yy_parse_failed(
70833   yyParser *yypParser           /* The parser */
70834 ){
70835   sqlite3ParserARG_FETCH;
70836 #ifndef NDEBUG
70837   if( yyTraceFILE ){
70838     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
70839   }
70840 #endif
70841   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
70842   /* Here code is inserted which will be executed whenever the
70843   ** parser fails */
70844   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
70845 }
70846
70847 /*
70848 ** The following code executes when a syntax error first occurs.
70849 */
70850 static void yy_syntax_error(
70851   yyParser *yypParser,           /* The parser */
70852   int yymajor,                   /* The major type of the error token */
70853   YYMINORTYPE yyminor            /* The minor type of the error token */
70854 ){
70855   sqlite3ParserARG_FETCH;
70856 #define TOKEN (yyminor.yy0)
70857
70858   if( !pParse->parseError ){
70859     if( TOKEN.z[0] ){
70860       sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
70861     }else{
70862       sqlite3ErrorMsg(pParse, "incomplete SQL statement");
70863     }
70864     pParse->parseError = 1;
70865   }
70866   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
70867 }
70868
70869 /*
70870 ** The following is executed when the parser accepts
70871 */
70872 static void yy_accept(
70873   yyParser *yypParser           /* The parser */
70874 ){
70875   sqlite3ParserARG_FETCH;
70876 #ifndef NDEBUG
70877   if( yyTraceFILE ){
70878     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
70879   }
70880 #endif
70881   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
70882   /* Here code is inserted which will be executed whenever the
70883   ** parser accepts */
70884   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
70885 }
70886
70887 /* The main parser program.
70888 ** The first argument is a pointer to a structure obtained from
70889 ** "sqlite3ParserAlloc" which describes the current state of the parser.
70890 ** The second argument is the major token number.  The third is
70891 ** the minor token.  The fourth optional argument is whatever the
70892 ** user wants (and specified in the grammar) and is available for
70893 ** use by the action routines.
70894 **
70895 ** Inputs:
70896 ** <ul>
70897 ** <li> A pointer to the parser (an opaque structure.)
70898 ** <li> The major token number.
70899 ** <li> The minor token number.
70900 ** <li> An option argument of a grammar-specified type.
70901 ** </ul>
70902 **
70903 ** Outputs:
70904 ** None.
70905 */
70906 SQLITE_PRIVATE void sqlite3Parser(
70907   void *yyp,                   /* The parser */
70908   int yymajor,                 /* The major token code number */
70909   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
70910   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
70911 ){
70912   YYMINORTYPE yyminorunion;
70913   int yyact;            /* The parser action. */
70914   int yyendofinput;     /* True if we are at the end of input */
70915   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
70916   yyParser *yypParser;  /* The parser */
70917
70918   /* (re)initialize the parser, if necessary */
70919   yypParser = (yyParser*)yyp;
70920   if( yypParser->yyidx<0 ){
70921 #if YYSTACKDEPTH<=0
70922     if( yypParser->yystksz <=0 ){
70923       memset(&yyminorunion, 0, sizeof(yyminorunion));
70924       yyStackOverflow(yypParser, &yyminorunion);
70925       return;
70926     }
70927 #endif
70928     yypParser->yyidx = 0;
70929     yypParser->yyerrcnt = -1;
70930     yypParser->yystack[0].stateno = 0;
70931     yypParser->yystack[0].major = 0;
70932   }
70933   yyminorunion.yy0 = yyminor;
70934   yyendofinput = (yymajor==0);
70935   sqlite3ParserARG_STORE;
70936
70937 #ifndef NDEBUG
70938   if( yyTraceFILE ){
70939     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
70940   }
70941 #endif
70942
70943   do{
70944     yyact = yy_find_shift_action(yypParser,yymajor);
70945     if( yyact<YYNSTATE ){
70946       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
70947       yypParser->yyerrcnt--;
70948       if( yyendofinput && yypParser->yyidx>=0 ){
70949         yymajor = 0;
70950       }else{
70951         yymajor = YYNOCODE;
70952       }
70953     }else if( yyact < YYNSTATE + YYNRULE ){
70954       yy_reduce(yypParser,yyact-YYNSTATE);
70955     }else if( yyact == YY_ERROR_ACTION ){
70956       int yymx;
70957 #ifndef NDEBUG
70958       if( yyTraceFILE ){
70959         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
70960       }
70961 #endif
70962 #ifdef YYERRORSYMBOL
70963       /* A syntax error has occurred.
70964       ** The response to an error depends upon whether or not the
70965       ** grammar defines an error token "ERROR".  
70966       **
70967       ** This is what we do if the grammar does define ERROR:
70968       **
70969       **  * Call the %syntax_error function.
70970       **
70971       **  * Begin popping the stack until we enter a state where
70972       **    it is legal to shift the error symbol, then shift
70973       **    the error symbol.
70974       **
70975       **  * Set the error count to three.
70976       **
70977       **  * Begin accepting and shifting new tokens.  No new error
70978       **    processing will occur until three tokens have been
70979       **    shifted successfully.
70980       **
70981       */
70982       if( yypParser->yyerrcnt<0 ){
70983         yy_syntax_error(yypParser,yymajor,yyminorunion);
70984       }
70985       yymx = yypParser->yystack[yypParser->yyidx].major;
70986       if( yymx==YYERRORSYMBOL || yyerrorhit ){
70987 #ifndef NDEBUG
70988         if( yyTraceFILE ){
70989           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
70990              yyTracePrompt,yyTokenName[yymajor]);
70991         }
70992 #endif
70993         yy_destructor(yymajor,&yyminorunion);
70994         yymajor = YYNOCODE;
70995       }else{
70996          while(
70997           yypParser->yyidx >= 0 &&
70998           yymx != YYERRORSYMBOL &&
70999           (yyact = yy_find_reduce_action(
71000                         yypParser->yystack[yypParser->yyidx].stateno,
71001                         YYERRORSYMBOL)) >= YYNSTATE
71002         ){
71003           yy_pop_parser_stack(yypParser);
71004         }
71005         if( yypParser->yyidx < 0 || yymajor==0 ){
71006           yy_destructor(yymajor,&yyminorunion);
71007           yy_parse_failed(yypParser);
71008           yymajor = YYNOCODE;
71009         }else if( yymx!=YYERRORSYMBOL ){
71010           YYMINORTYPE u2;
71011           u2.YYERRSYMDT = 0;
71012           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
71013         }
71014       }
71015       yypParser->yyerrcnt = 3;
71016       yyerrorhit = 1;
71017 #else  /* YYERRORSYMBOL is not defined */
71018       /* This is what we do if the grammar does not define ERROR:
71019       **
71020       **  * Report an error message, and throw away the input token.
71021       **
71022       **  * If the input token is $, then fail the parse.
71023       **
71024       ** As before, subsequent error messages are suppressed until
71025       ** three input tokens have been successfully shifted.
71026       */
71027       if( yypParser->yyerrcnt<=0 ){
71028         yy_syntax_error(yypParser,yymajor,yyminorunion);
71029       }
71030       yypParser->yyerrcnt = 3;
71031       yy_destructor(yymajor,&yyminorunion);
71032       if( yyendofinput ){
71033         yy_parse_failed(yypParser);
71034       }
71035       yymajor = YYNOCODE;
71036 #endif
71037     }else{
71038       yy_accept(yypParser);
71039       yymajor = YYNOCODE;
71040     }
71041   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
71042   return;
71043 }
71044
71045 /************** End of parse.c ***********************************************/
71046 /************** Begin file tokenize.c ****************************************/
71047 /*
71048 ** 2001 September 15
71049 **
71050 ** The author disclaims copyright to this source code.  In place of
71051 ** a legal notice, here is a blessing:
71052 **
71053 **    May you do good and not evil.
71054 **    May you find forgiveness for yourself and forgive others.
71055 **    May you share freely, never taking more than you give.
71056 **
71057 *************************************************************************
71058 ** An tokenizer for SQL
71059 **
71060 ** This file contains C code that splits an SQL input string up into
71061 ** individual tokens and sends those tokens one-by-one over to the
71062 ** parser for analysis.
71063 **
71064 ** $Id: tokenize.c,v 1.136 2007/08/27 23:26:59 drh Exp $
71065 */
71066
71067 /*
71068 ** The charMap() macro maps alphabetic characters into their
71069 ** lower-case ASCII equivalent.  On ASCII machines, this is just
71070 ** an upper-to-lower case map.  On EBCDIC machines we also need
71071 ** to adjust the encoding.  Only alphabetic characters and underscores
71072 ** need to be translated.
71073 */
71074 #ifdef SQLITE_ASCII
71075 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
71076 #endif
71077 #ifdef SQLITE_EBCDIC
71078 # define charMap(X) ebcdicToAscii[(unsigned char)X]
71079 const unsigned char ebcdicToAscii[] = {
71080 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
71081    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
71082    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
71083    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
71084    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
71085    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
71086    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
71087    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
71088    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
71089    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
71090    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
71091    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
71092    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
71093    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
71094    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
71095    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
71096    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
71097 };
71098 #endif
71099
71100 /*
71101 ** The sqlite3KeywordCode function looks up an identifier to determine if
71102 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
71103 ** returned.  If the input is not a keyword, TK_ID is returned.
71104 **
71105 ** The implementation of this routine was generated by a program,
71106 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
71107 ** The output of the mkkeywordhash.c program is written into a file
71108 ** named keywordhash.h and then included into this source file by
71109 ** the #include below.
71110 */
71111 /************** Include keywordhash.h in the middle of tokenize.c ************/
71112 /************** Begin file keywordhash.h *************************************/
71113 /***** This file contains automatically generated code ******
71114 **
71115 ** The code in this file has been automatically generated by
71116 **
71117 **     $Header: /sqlite/sqlite/tool/mkkeywordhash.c,v 1.31 2007/07/30 18:26:20 rse Exp $
71118 **
71119 ** The code in this file implements a function that determines whether
71120 ** or not a given identifier is really an SQL keyword.  The same thing
71121 ** might be implemented more directly using a hand-written hash table.
71122 ** But by using this automatically generated code, the size of the code
71123 ** is substantially reduced.  This is important for embedded applications
71124 ** on platforms with limited memory.
71125 */
71126 /* Hash score: 165 */
71127 static int keywordCode(const char *z, int n){
71128   /* zText[] encodes 775 bytes of keywords in 526 bytes */
71129   static const char zText[526] =
71130     "BEFOREIGNOREGEXPLAINSTEADDESCAPEACHECKEYCONSTRAINTERSECTABLEFT"
71131     "HENDATABASELECTRANSACTIONATURALTERAISELSEXCEPTRIGGEREFERENCES"
71132     "UNIQUERYATTACHAVINGROUPDATEMPORARYBEGINNEREINDEXCLUSIVEXISTSBETWEEN"
71133     "OTNULLIKECASCADEFERRABLECASECOLLATECREATECURRENT_DATEDELETEDETACH"
71134     "IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN"
71135     "WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICT"
71136     "CROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOB"
71137     "YIFINTOFFSETISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUM"
71138     "VIEWINITIALLY";
71139   static const unsigned char aHash[127] = {
71140       63,  92, 109,  61,   0,  38,   0,   0,  69,   0,  64,   0,   0,
71141      102,   4,  65,   7,   0, 108,  72, 103,  99,   0,  22,   0,   0,
71142      113,   0, 111, 106,   0,  18,  80,   0,   1,   0,   0,  56,  57,
71143        0,  55,  11,   0,  33,  77,  89,   0, 110,  88,   0,   0,  45,
71144        0,  90,  54,   0,  20,   0, 114,  34,  19,   0,  10,  97,  28,
71145       83,   0,   0, 116,  93,  47, 115,  41,  12,  44,   0,  78,   0,
71146       87,  29,   0,  86,   0,   0,   0,  82,  79,  84,  75,  96,   6,
71147       14,  95,   0,  68,   0,  21,  76,  98,  27,   0, 112,  67, 104,
71148       49,  40,  71,   0,   0,  81, 100,   0, 107,   0,  15,   0,   0,
71149       24,   0,  73,  42,  50,   0,  16,  48,   0,  37,
71150   };
71151   static const unsigned char aNext[116] = {
71152        0,   0,   0,   0,   0,   0,   0,   0,   0,   9,   0,   0,   0,
71153        0,   0,   0,   0,   5,   0,   0,   0,   0,   0,   0,   0,   0,
71154        0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  32,   0,   0,
71155       17,   0,   0,   0,  36,  39,   0,   0,  25,   0,   0,  31,   0,
71156        0,   0,  43,  52,   0,   0,   0,  53,   0,   0,   0,   0,   0,
71157        0,   0,   0,   0,  51,   0,   0,   0,   0,  26,   0,   8,  46,
71158        2,   0,   0,   0,   0,   0,   0,   0,   3,  58,  66,   0,  13,
71159        0,  91,  85,   0,  94,   0,  74,   0,   0,  62,   0,  35, 101,
71160        0,   0, 105,  23,  30,  60,  70,   0,   0,  59,   0,   0,
71161   };
71162   static const unsigned char aLen[116] = {
71163        6,   7,   3,   6,   6,   7,   7,   3,   4,   6,   4,   5,   3,
71164       10,   9,   5,   4,   4,   3,   8,   2,   6,  11,   2,   7,   5,
71165        5,   4,   6,   7,  10,   6,   5,   6,   6,   5,   6,   4,   9,
71166        2,   5,   5,   7,   5,   9,   6,   7,   7,   3,   4,   4,   7,
71167        3,  10,   4,   7,   6,  12,   6,   6,   9,   4,   6,   5,   4,
71168        7,   6,   5,   6,   7,   5,   4,   5,   6,   5,   7,   3,   7,
71169       13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   8,   8,
71170        2,   4,   4,   4,   4,   4,   2,   2,   4,   6,   2,   3,   6,
71171        5,   8,   5,   5,   8,   3,   5,   5,   6,   4,   9,   3,
71172   };
71173   static const unsigned short int aOffset[116] = {
71174        0,   2,   2,   6,  10,  13,  18,  23,  25,  26,  31,  33,  37,
71175       40,  47,  55,  58,  61,  63,  65,  70,  71,  76,  85,  86,  91,
71176       95,  99, 102, 107, 113, 123, 126, 131, 136, 141, 144, 148, 148,
71177      152, 157, 160, 164, 166, 169, 177, 183, 189, 189, 192, 195, 199,
71178      200, 204, 214, 218, 225, 231, 243, 249, 255, 264, 266, 272, 277,
71179      279, 286, 291, 296, 302, 308, 313, 317, 320, 326, 330, 337, 339,
71180      346, 348, 350, 359, 363, 369, 375, 383, 388, 388, 404, 411, 418,
71181      419, 426, 430, 434, 438, 442, 445, 447, 449, 452, 452, 455, 458,
71182      464, 468, 476, 480, 485, 493, 496, 501, 506, 512, 516, 521,
71183   };
71184   static const unsigned char aCode[116] = {
71185     TK_BEFORE,     TK_FOREIGN,    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    
71186     TK_EXPLAIN,    TK_INSTEAD,    TK_ADD,        TK_DESC,       TK_ESCAPE,     
71187     TK_EACH,       TK_CHECK,      TK_KEY,        TK_CONSTRAINT, TK_INTERSECT,  
71188     TK_TABLE,      TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DATABASE,   
71189     TK_AS,         TK_SELECT,     TK_TRANSACTION,TK_ON,         TK_JOIN_KW,    
71190     TK_ALTER,      TK_RAISE,      TK_ELSE,       TK_EXCEPT,     TK_TRIGGER,    
71191     TK_REFERENCES, TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     
71192     TK_GROUP,      TK_UPDATE,     TK_TEMP,       TK_TEMP,       TK_OR,         
71193     TK_BEGIN,      TK_JOIN_KW,    TK_REINDEX,    TK_INDEX,      TK_EXCLUSIVE,  
71194     TK_EXISTS,     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NULL,       
71195     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DEFERRABLE, TK_CASE,       
71196     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DELETE,     TK_DETACH,     
71197     TK_IMMEDIATE,  TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       
71198     TK_ANALYZE,    TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    
71199     TK_LIMIT,      TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      
71200     TK_REPLACE,    TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         
71201     TK_IN,         TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   
71202     TK_JOIN_KW,    TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   
71203     TK_DISTINCT,   TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       
71204     TK_JOIN_KW,    TK_LIKE_KW,    TK_BY,         TK_IF,         TK_INTO,       
71205     TK_OFFSET,     TK_OF,         TK_SET,        TK_ISNULL,     TK_ORDER,      
71206     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        
71207     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  
71208     TK_ALL,        
71209   };
71210   int h, i;
71211   if( n<2 ) return TK_ID;
71212   h = ((charMap(z[0])*4) ^
71213       (charMap(z[n-1])*3) ^
71214       n) % 127;
71215   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
71216     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
71217       return aCode[i];
71218     }
71219   }
71220   return TK_ID;
71221 }
71222 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
71223   return keywordCode((char*)z, n);
71224 }
71225
71226 /************** End of keywordhash.h *****************************************/
71227 /************** Continuing where we left off in tokenize.c *******************/
71228
71229
71230 /*
71231 ** If X is a character that can be used in an identifier then
71232 ** IdChar(X) will be true.  Otherwise it is false.
71233 **
71234 ** For ASCII, any character with the high-order bit set is
71235 ** allowed in an identifier.  For 7-bit characters, 
71236 ** sqlite3IsIdChar[X] must be 1.
71237 **
71238 ** For EBCDIC, the rules are more complex but have the same
71239 ** end result.
71240 **
71241 ** Ticket #1066.  the SQL standard does not allow '$' in the
71242 ** middle of identfiers.  But many SQL implementations do. 
71243 ** SQLite will allow '$' in identifiers for compatibility.
71244 ** But the feature is undocumented.
71245 */
71246 #ifdef SQLITE_ASCII
71247 SQLITE_PRIVATE const char sqlite3IsAsciiIdChar[] = {
71248 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
71249     0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
71250     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
71251     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
71252     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
71253     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
71254     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
71255 };
71256 #define IdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20]))
71257 #endif
71258 #ifdef SQLITE_EBCDIC
71259 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
71260 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
71261     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
71262     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
71263     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
71264     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
71265     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
71266     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
71267     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
71268     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
71269     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
71270     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
71271     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
71272     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
71273 };
71274 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
71275 #endif
71276
71277
71278 /*
71279 ** Return the length of the token that begins at z[0]. 
71280 ** Store the token type in *tokenType before returning.
71281 */
71282 static int getToken(const unsigned char *z, int *tokenType){
71283   int i, c;
71284   switch( *z ){
71285     case ' ': case '\t': case '\n': case '\f': case '\r': {
71286       for(i=1; isspace(z[i]); i++){}
71287       *tokenType = TK_SPACE;
71288       return i;
71289     }
71290     case '-': {
71291       if( z[1]=='-' ){
71292         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
71293         *tokenType = TK_COMMENT;
71294         return i;
71295       }
71296       *tokenType = TK_MINUS;
71297       return 1;
71298     }
71299     case '(': {
71300       *tokenType = TK_LP;
71301       return 1;
71302     }
71303     case ')': {
71304       *tokenType = TK_RP;
71305       return 1;
71306     }
71307     case ';': {
71308       *tokenType = TK_SEMI;
71309       return 1;
71310     }
71311     case '+': {
71312       *tokenType = TK_PLUS;
71313       return 1;
71314     }
71315     case '*': {
71316       *tokenType = TK_STAR;
71317       return 1;
71318     }
71319     case '/': {
71320       if( z[1]!='*' || z[2]==0 ){
71321         *tokenType = TK_SLASH;
71322         return 1;
71323       }
71324       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
71325       if( c ) i++;
71326       *tokenType = TK_COMMENT;
71327       return i;
71328     }
71329     case '%': {
71330       *tokenType = TK_REM;
71331       return 1;
71332     }
71333     case '=': {
71334       *tokenType = TK_EQ;
71335       return 1 + (z[1]=='=');
71336     }
71337     case '<': {
71338       if( (c=z[1])=='=' ){
71339         *tokenType = TK_LE;
71340         return 2;
71341       }else if( c=='>' ){
71342         *tokenType = TK_NE;
71343         return 2;
71344       }else if( c=='<' ){
71345         *tokenType = TK_LSHIFT;
71346         return 2;
71347       }else{
71348         *tokenType = TK_LT;
71349         return 1;
71350       }
71351     }
71352     case '>': {
71353       if( (c=z[1])=='=' ){
71354         *tokenType = TK_GE;
71355         return 2;
71356       }else if( c=='>' ){
71357         *tokenType = TK_RSHIFT;
71358         return 2;
71359       }else{
71360         *tokenType = TK_GT;
71361         return 1;
71362       }
71363     }
71364     case '!': {
71365       if( z[1]!='=' ){
71366         *tokenType = TK_ILLEGAL;
71367         return 2;
71368       }else{
71369         *tokenType = TK_NE;
71370         return 2;
71371       }
71372     }
71373     case '|': {
71374       if( z[1]!='|' ){
71375         *tokenType = TK_BITOR;
71376         return 1;
71377       }else{
71378         *tokenType = TK_CONCAT;
71379         return 2;
71380       }
71381     }
71382     case ',': {
71383       *tokenType = TK_COMMA;
71384       return 1;
71385     }
71386     case '&': {
71387       *tokenType = TK_BITAND;
71388       return 1;
71389     }
71390     case '~': {
71391       *tokenType = TK_BITNOT;
71392       return 1;
71393     }
71394     case '`':
71395     case '\'':
71396     case '"': {
71397       int delim = z[0];
71398       for(i=1; (c=z[i])!=0; i++){
71399         if( c==delim ){
71400           if( z[i+1]==delim ){
71401             i++;
71402           }else{
71403             break;
71404           }
71405         }
71406       }
71407       if( c ){
71408         *tokenType = TK_STRING;
71409         return i+1;
71410       }else{
71411         *tokenType = TK_ILLEGAL;
71412         return i;
71413       }
71414     }
71415     case '.': {
71416 #ifndef SQLITE_OMIT_FLOATING_POINT
71417       if( !isdigit(z[1]) )
71418 #endif
71419       {
71420         *tokenType = TK_DOT;
71421         return 1;
71422       }
71423       /* If the next character is a digit, this is a floating point
71424       ** number that begins with ".".  Fall thru into the next case */
71425     }
71426     case '0': case '1': case '2': case '3': case '4':
71427     case '5': case '6': case '7': case '8': case '9': {
71428       *tokenType = TK_INTEGER;
71429       for(i=0; isdigit(z[i]); i++){}
71430 #ifndef SQLITE_OMIT_FLOATING_POINT
71431       if( z[i]=='.' ){
71432         i++;
71433         while( isdigit(z[i]) ){ i++; }
71434         *tokenType = TK_FLOAT;
71435       }
71436       if( (z[i]=='e' || z[i]=='E') &&
71437            ( isdigit(z[i+1]) 
71438             || ((z[i+1]=='+' || z[i+1]=='-') && isdigit(z[i+2]))
71439            )
71440       ){
71441         i += 2;
71442         while( isdigit(z[i]) ){ i++; }
71443         *tokenType = TK_FLOAT;
71444       }
71445 #endif
71446       while( IdChar(z[i]) ){
71447         *tokenType = TK_ILLEGAL;
71448         i++;
71449       }
71450       return i;
71451     }
71452     case '[': {
71453       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
71454       *tokenType = TK_ID;
71455       return i;
71456     }
71457     case '?': {
71458       *tokenType = TK_VARIABLE;
71459       for(i=1; isdigit(z[i]); i++){}
71460       return i;
71461     }
71462     case '#': {
71463       for(i=1; isdigit(z[i]); i++){}
71464       if( i>1 ){
71465         /* Parameters of the form #NNN (where NNN is a number) are used
71466         ** internally by sqlite3NestedParse.  */
71467         *tokenType = TK_REGISTER;
71468         return i;
71469       }
71470       /* Fall through into the next case if the '#' is not followed by
71471       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
71472     }
71473 #ifndef SQLITE_OMIT_TCL_VARIABLE
71474     case '$':
71475 #endif
71476     case '@':  /* For compatibility with MS SQL Server */
71477     case ':': {
71478       int n = 0;
71479       *tokenType = TK_VARIABLE;
71480       for(i=1; (c=z[i])!=0; i++){
71481         if( IdChar(c) ){
71482           n++;
71483 #ifndef SQLITE_OMIT_TCL_VARIABLE
71484         }else if( c=='(' && n>0 ){
71485           do{
71486             i++;
71487           }while( (c=z[i])!=0 && !isspace(c) && c!=')' );
71488           if( c==')' ){
71489             i++;
71490           }else{
71491             *tokenType = TK_ILLEGAL;
71492           }
71493           break;
71494         }else if( c==':' && z[i+1]==':' ){
71495           i++;
71496 #endif
71497         }else{
71498           break;
71499         }
71500       }
71501       if( n==0 ) *tokenType = TK_ILLEGAL;
71502       return i;
71503     }
71504 #ifndef SQLITE_OMIT_BLOB_LITERAL
71505     case 'x': case 'X': {
71506       if( (c=z[1])=='\'' || c=='"' ){
71507         int delim = c;
71508         *tokenType = TK_BLOB;
71509         for(i=2; (c=z[i])!=0; i++){
71510           if( c==delim ){
71511             if( i%2 ) *tokenType = TK_ILLEGAL;
71512             break;
71513           }
71514           if( !isxdigit(c) ){
71515             *tokenType = TK_ILLEGAL;
71516             return i;
71517           }
71518         }
71519         if( c ) i++;
71520         return i;
71521       }
71522       /* Otherwise fall through to the next case */
71523     }
71524 #endif
71525     default: {
71526       if( !IdChar(*z) ){
71527         break;
71528       }
71529       for(i=1; IdChar(z[i]); i++){}
71530       *tokenType = keywordCode((char*)z, i);
71531       return i;
71532     }
71533   }
71534   *tokenType = TK_ILLEGAL;
71535   return 1;
71536 }
71537 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
71538   return getToken(z, tokenType);
71539 }
71540
71541 /*
71542 ** Run the parser on the given SQL string.  The parser structure is
71543 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
71544 ** and pzErrMsg!=NULL then an error message might be written into 
71545 ** memory obtained from sqlite3_malloc() and *pzErrMsg made to point to that
71546 ** error message.  Or maybe not.
71547 */
71548 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
71549   int nErr = 0;
71550   int i;
71551   void *pEngine;
71552   int tokenType;
71553   int lastTokenParsed = -1;
71554   sqlite3 *db = pParse->db;
71555
71556   if( db->activeVdbeCnt==0 ){
71557     db->u1.isInterrupted = 0;
71558   }
71559   pParse->rc = SQLITE_OK;
71560   i = 0;
71561   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3_malloc);
71562   if( pEngine==0 ){
71563     db->mallocFailed = 1;
71564     return SQLITE_NOMEM;
71565   }
71566   assert( pParse->sLastToken.dyn==0 );
71567   assert( pParse->pNewTable==0 );
71568   assert( pParse->pNewTrigger==0 );
71569   assert( pParse->nVar==0 );
71570   assert( pParse->nVarExpr==0 );
71571   assert( pParse->nVarExprAlloc==0 );
71572   assert( pParse->apVarExpr==0 );
71573   pParse->zTail = pParse->zSql = zSql;
71574   while( !db->mallocFailed && zSql[i]!=0 ){
71575     assert( i>=0 );
71576     pParse->sLastToken.z = (u8*)&zSql[i];
71577     assert( pParse->sLastToken.dyn==0 );
71578     pParse->sLastToken.n = getToken((unsigned char*)&zSql[i],&tokenType);
71579     i += pParse->sLastToken.n;
71580     if( i>SQLITE_MAX_SQL_LENGTH ){
71581       pParse->rc = SQLITE_TOOBIG;
71582       break;
71583     }
71584     switch( tokenType ){
71585       case TK_SPACE:
71586       case TK_COMMENT: {
71587         if( db->u1.isInterrupted ){
71588           pParse->rc = SQLITE_INTERRUPT;
71589           sqlite3SetString(pzErrMsg, "interrupt", (char*)0);
71590           goto abort_parse;
71591         }
71592         break;
71593       }
71594       case TK_ILLEGAL: {
71595         if( pzErrMsg ){
71596           sqlite3_free(*pzErrMsg);
71597           *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
71598                           &pParse->sLastToken);
71599         }
71600         nErr++;
71601         goto abort_parse;
71602       }
71603       case TK_SEMI: {
71604         pParse->zTail = &zSql[i];
71605         /* Fall thru into the default case */
71606       }
71607       default: {
71608         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
71609         lastTokenParsed = tokenType;
71610         if( pParse->rc!=SQLITE_OK ){
71611           goto abort_parse;
71612         }
71613         break;
71614       }
71615     }
71616   }
71617 abort_parse:
71618   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
71619     if( lastTokenParsed!=TK_SEMI ){
71620       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
71621       pParse->zTail = &zSql[i];
71622     }
71623     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
71624   }
71625   sqlite3ParserFree(pEngine, sqlite3_free);
71626   if( db->mallocFailed ){
71627     pParse->rc = SQLITE_NOMEM;
71628   }
71629   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
71630     sqlite3SetString(&pParse->zErrMsg, sqlite3ErrStr(pParse->rc), (char*)0);
71631   }
71632   if( pParse->zErrMsg ){
71633     if( pzErrMsg && *pzErrMsg==0 ){
71634       *pzErrMsg = pParse->zErrMsg;
71635     }else{
71636       sqlite3_free(pParse->zErrMsg);
71637     }
71638     pParse->zErrMsg = 0;
71639     if( !nErr ) nErr++;
71640   }
71641   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
71642     sqlite3VdbeDelete(pParse->pVdbe);
71643     pParse->pVdbe = 0;
71644   }
71645 #ifndef SQLITE_OMIT_SHARED_CACHE
71646   if( pParse->nested==0 ){
71647     sqlite3_free(pParse->aTableLock);
71648     pParse->aTableLock = 0;
71649     pParse->nTableLock = 0;
71650   }
71651 #endif
71652
71653   if( !IN_DECLARE_VTAB ){
71654     /* If the pParse->declareVtab flag is set, do not delete any table 
71655     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
71656     ** will take responsibility for freeing the Table structure.
71657     */
71658     sqlite3DeleteTable(pParse->pNewTable);
71659   }
71660
71661   sqlite3DeleteTrigger(pParse->pNewTrigger);
71662   sqlite3_free(pParse->apVarExpr);
71663   if( nErr>0 && (pParse->rc==SQLITE_OK || pParse->rc==SQLITE_DONE) ){
71664     pParse->rc = SQLITE_ERROR;
71665   }
71666   return nErr;
71667 }
71668
71669 /************** End of tokenize.c ********************************************/
71670 /************** Begin file complete.c ****************************************/
71671 /*
71672 ** 2001 September 15
71673 **
71674 ** The author disclaims copyright to this source code.  In place of
71675 ** a legal notice, here is a blessing:
71676 **
71677 **    May you do good and not evil.
71678 **    May you find forgiveness for yourself and forgive others.
71679 **    May you share freely, never taking more than you give.
71680 **
71681 *************************************************************************
71682 ** An tokenizer for SQL
71683 **
71684 ** This file contains C code that implements the sqlite3_complete() API.
71685 ** This code used to be part of the tokenizer.c source file.  But by
71686 ** separating it out, the code will be automatically omitted from
71687 ** static links that do not use it.
71688 **
71689 ** $Id: complete.c,v 1.6 2007/08/27 23:26:59 drh Exp $
71690 */
71691 #ifndef SQLITE_OMIT_COMPLETE
71692
71693 /*
71694 ** This is defined in tokenize.c.  We just have to import the definition.
71695 */
71696 #ifndef SQLITE_AMALGAMATION
71697 #ifdef SQLITE_ASCII
71698 SQLITE_PRIVATE const char sqlite3IsAsciiIdChar[];
71699 #define IdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20]))
71700 #endif
71701 #ifdef SQLITE_EBCDIC
71702 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
71703 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
71704 #endif
71705 #endif /* SQLITE_AMALGAMATION */
71706
71707
71708 /*
71709 ** Token types used by the sqlite3_complete() routine.  See the header
71710 ** comments on that procedure for additional information.
71711 */
71712 #define tkSEMI    0
71713 #define tkWS      1
71714 #define tkOTHER   2
71715 #define tkEXPLAIN 3
71716 #define tkCREATE  4
71717 #define tkTEMP    5
71718 #define tkTRIGGER 6
71719 #define tkEND     7
71720
71721 /*
71722 ** Return TRUE if the given SQL string ends in a semicolon.
71723 **
71724 ** Special handling is require for CREATE TRIGGER statements.
71725 ** Whenever the CREATE TRIGGER keywords are seen, the statement
71726 ** must end with ";END;".
71727 **
71728 ** This implementation uses a state machine with 7 states:
71729 **
71730 **   (0) START     At the beginning or end of an SQL statement.  This routine
71731 **                 returns 1 if it ends in the START state and 0 if it ends
71732 **                 in any other state.
71733 **
71734 **   (1) NORMAL    We are in the middle of statement which ends with a single
71735 **                 semicolon.
71736 **
71737 **   (2) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
71738 **                 a statement.
71739 **
71740 **   (3) CREATE    The keyword CREATE has been seen at the beginning of a
71741 **                 statement, possibly preceeded by EXPLAIN and/or followed by
71742 **                 TEMP or TEMPORARY
71743 **
71744 **   (4) TRIGGER   We are in the middle of a trigger definition that must be
71745 **                 ended by a semicolon, the keyword END, and another semicolon.
71746 **
71747 **   (5) SEMI      We've seen the first semicolon in the ";END;" that occurs at
71748 **                 the end of a trigger definition.
71749 **
71750 **   (6) END       We've seen the ";END" of the ";END;" that occurs at the end
71751 **                 of a trigger difinition.
71752 **
71753 ** Transitions between states above are determined by tokens extracted
71754 ** from the input.  The following tokens are significant:
71755 **
71756 **   (0) tkSEMI      A semicolon.
71757 **   (1) tkWS        Whitespace
71758 **   (2) tkOTHER     Any other SQL token.
71759 **   (3) tkEXPLAIN   The "explain" keyword.
71760 **   (4) tkCREATE    The "create" keyword.
71761 **   (5) tkTEMP      The "temp" or "temporary" keyword.
71762 **   (6) tkTRIGGER   The "trigger" keyword.
71763 **   (7) tkEND       The "end" keyword.
71764 **
71765 ** Whitespace never causes a state transition and is always ignored.
71766 **
71767 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
71768 ** to recognize the end of a trigger can be omitted.  All we have to do
71769 ** is look for a semicolon that is not part of an string or comment.
71770 */
71771 SQLITE_API int sqlite3_complete(const char *zSql){
71772   u8 state = 0;   /* Current state, using numbers defined in header comment */
71773   u8 token;       /* Value of the next token */
71774
71775 #ifndef SQLITE_OMIT_TRIGGER
71776   /* A complex statement machine used to detect the end of a CREATE TRIGGER
71777   ** statement.  This is the normal case.
71778   */
71779   static const u8 trans[7][8] = {
71780                      /* Token:                                                */
71781      /* State:       **  SEMI  WS  OTHER EXPLAIN  CREATE  TEMP  TRIGGER  END  */
71782      /* 0   START: */ {    0,  0,     1,      2,      3,    1,       1,   1,  },
71783      /* 1  NORMAL: */ {    0,  1,     1,      1,      1,    1,       1,   1,  },
71784      /* 2 EXPLAIN: */ {    0,  2,     1,      1,      3,    1,       1,   1,  },
71785      /* 3  CREATE: */ {    0,  3,     1,      1,      1,    3,       4,   1,  },
71786      /* 4 TRIGGER: */ {    5,  4,     4,      4,      4,    4,       4,   4,  },
71787      /* 5    SEMI: */ {    5,  5,     4,      4,      4,    4,       4,   6,  },
71788      /* 6     END: */ {    0,  6,     4,      4,      4,    4,       4,   4,  },
71789   };
71790 #else
71791   /* If triggers are not suppored by this compile then the statement machine
71792   ** used to detect the end of a statement is much simplier
71793   */
71794   static const u8 trans[2][3] = {
71795                      /* Token:           */
71796      /* State:       **  SEMI  WS  OTHER */
71797      /* 0   START: */ {    0,  0,     1, },
71798      /* 1  NORMAL: */ {    0,  1,     1, },
71799   };
71800 #endif /* SQLITE_OMIT_TRIGGER */
71801
71802   while( *zSql ){
71803     switch( *zSql ){
71804       case ';': {  /* A semicolon */
71805         token = tkSEMI;
71806         break;
71807       }
71808       case ' ':
71809       case '\r':
71810       case '\t':
71811       case '\n':
71812       case '\f': {  /* White space is ignored */
71813         token = tkWS;
71814         break;
71815       }
71816       case '/': {   /* C-style comments */
71817         if( zSql[1]!='*' ){
71818           token = tkOTHER;
71819           break;
71820         }
71821         zSql += 2;
71822         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
71823         if( zSql[0]==0 ) return 0;
71824         zSql++;
71825         token = tkWS;
71826         break;
71827       }
71828       case '-': {   /* SQL-style comments from "--" to end of line */
71829         if( zSql[1]!='-' ){
71830           token = tkOTHER;
71831           break;
71832         }
71833         while( *zSql && *zSql!='\n' ){ zSql++; }
71834         if( *zSql==0 ) return state==0;
71835         token = tkWS;
71836         break;
71837       }
71838       case '[': {   /* Microsoft-style identifiers in [...] */
71839         zSql++;
71840         while( *zSql && *zSql!=']' ){ zSql++; }
71841         if( *zSql==0 ) return 0;
71842         token = tkOTHER;
71843         break;
71844       }
71845       case '`':     /* Grave-accent quoted symbols used by MySQL */
71846       case '"':     /* single- and double-quoted strings */
71847       case '\'': {
71848         int c = *zSql;
71849         zSql++;
71850         while( *zSql && *zSql!=c ){ zSql++; }
71851         if( *zSql==0 ) return 0;
71852         token = tkOTHER;
71853         break;
71854       }
71855       default: {
71856         int c;
71857         if( IdChar((u8)*zSql) ){
71858           /* Keywords and unquoted identifiers */
71859           int nId;
71860           for(nId=1; IdChar(zSql[nId]); nId++){}
71861 #ifdef SQLITE_OMIT_TRIGGER
71862           token = tkOTHER;
71863 #else
71864           switch( *zSql ){
71865             case 'c': case 'C': {
71866               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
71867                 token = tkCREATE;
71868               }else{
71869                 token = tkOTHER;
71870               }
71871               break;
71872             }
71873             case 't': case 'T': {
71874               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
71875                 token = tkTRIGGER;
71876               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
71877                 token = tkTEMP;
71878               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
71879                 token = tkTEMP;
71880               }else{
71881                 token = tkOTHER;
71882               }
71883               break;
71884             }
71885             case 'e':  case 'E': {
71886               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
71887                 token = tkEND;
71888               }else
71889 #ifndef SQLITE_OMIT_EXPLAIN
71890               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
71891                 token = tkEXPLAIN;
71892               }else
71893 #endif
71894               {
71895                 token = tkOTHER;
71896               }
71897               break;
71898             }
71899             default: {
71900               token = tkOTHER;
71901               break;
71902             }
71903           }
71904 #endif /* SQLITE_OMIT_TRIGGER */
71905           zSql += nId-1;
71906         }else{
71907           /* Operators and special symbols */
71908           token = tkOTHER;
71909         }
71910         break;
71911       }
71912     }
71913     state = trans[state][token];
71914     zSql++;
71915   }
71916   return state==0;
71917 }
71918
71919 #ifndef SQLITE_OMIT_UTF16
71920 /*
71921 ** This routine is the same as the sqlite3_complete() routine described
71922 ** above, except that the parameter is required to be UTF-16 encoded, not
71923 ** UTF-8.
71924 */
71925 SQLITE_API int sqlite3_complete16(const void *zSql){
71926   sqlite3_value *pVal;
71927   char const *zSql8;
71928   int rc = SQLITE_NOMEM;
71929
71930   pVal = sqlite3ValueNew(0);
71931   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
71932   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
71933   if( zSql8 ){
71934     rc = sqlite3_complete(zSql8);
71935   }
71936   sqlite3ValueFree(pVal);
71937   return sqlite3ApiExit(0, rc);
71938 }
71939 #endif /* SQLITE_OMIT_UTF16 */
71940 #endif /* SQLITE_OMIT_COMPLETE */
71941
71942 /************** End of complete.c ********************************************/
71943 /************** Begin file main.c ********************************************/
71944 /*
71945 ** 2001 September 15
71946 **
71947 ** The author disclaims copyright to this source code.  In place of
71948 ** a legal notice, here is a blessing:
71949 **
71950 **    May you do good and not evil.
71951 **    May you find forgiveness for yourself and forgive others.
71952 **    May you share freely, never taking more than you give.
71953 **
71954 *************************************************************************
71955 ** Main file for the SQLite library.  The routines in this file
71956 ** implement the programmer interface to the library.  Routines in
71957 ** other files are for internal use by SQLite and should not be
71958 ** accessed by users of the library.
71959 **
71960 ** $Id: main.c,v 1.409 2007/12/07 18:55:28 drh Exp $
71961 */
71962
71963 /*
71964 ** The version of the library
71965 */
71966 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
71967 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
71968 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
71969 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
71970
71971 /*
71972 ** If the following function pointer is not NULL and if
71973 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
71974 ** I/O active are written using this function.  These messages
71975 ** are intended for debugging activity only.
71976 */
71977 SQLITE_API void (*sqlite3_io_trace)(const char*, ...) = 0;
71978
71979 /*
71980 ** If the following global variable points to a string which is the
71981 ** name of a directory, then that directory will be used to store
71982 ** temporary files.
71983 **
71984 ** See also the "PRAGMA temp_store_directory" SQL command.
71985 */
71986 SQLITE_API char *sqlite3_temp_directory = 0;
71987
71988
71989 /*
71990 ** This is the default collating function named "BINARY" which is always
71991 ** available.
71992 */
71993 static int binCollFunc(
71994   void *NotUsed,
71995   int nKey1, const void *pKey1,
71996   int nKey2, const void *pKey2
71997 ){
71998   int rc, n;
71999   n = nKey1<nKey2 ? nKey1 : nKey2;
72000   rc = memcmp(pKey1, pKey2, n);
72001   if( rc==0 ){
72002     rc = nKey1 - nKey2;
72003   }
72004   return rc;
72005 }
72006
72007 /*
72008 ** Another built-in collating sequence: NOCASE. 
72009 **
72010 ** This collating sequence is intended to be used for "case independant
72011 ** comparison". SQLite's knowledge of upper and lower case equivalents
72012 ** extends only to the 26 characters used in the English language.
72013 **
72014 ** At the moment there is only a UTF-8 implementation.
72015 */
72016 static int nocaseCollatingFunc(
72017   void *NotUsed,
72018   int nKey1, const void *pKey1,
72019   int nKey2, const void *pKey2
72020 ){
72021   int r = sqlite3StrNICmp(
72022       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
72023   if( 0==r ){
72024     r = nKey1-nKey2;
72025   }
72026   return r;
72027 }
72028
72029 /*
72030 ** Return the ROWID of the most recent insert
72031 */
72032 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
72033   return db->lastRowid;
72034 }
72035
72036 /*
72037 ** Return the number of changes in the most recent call to sqlite3_exec().
72038 */
72039 SQLITE_API int sqlite3_changes(sqlite3 *db){
72040   return db->nChange;
72041 }
72042
72043 /*
72044 ** Return the number of changes since the database handle was opened.
72045 */
72046 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
72047   return db->nTotalChange;
72048 }
72049
72050 /*
72051 ** Close an existing SQLite database
72052 */
72053 SQLITE_API int sqlite3_close(sqlite3 *db){
72054   HashElem *i;
72055   int j;
72056
72057   if( !db ){
72058     return SQLITE_OK;
72059   }
72060   if( sqlite3SafetyCheck(db) ){
72061     return SQLITE_MISUSE;
72062   }
72063   sqlite3_mutex_enter(db->mutex);
72064
72065 #ifdef SQLITE_SSE
72066   {
72067     extern void sqlite3SseCleanup(sqlite3*);
72068     sqlite3SseCleanup(db);
72069   }
72070 #endif 
72071
72072   sqlite3ResetInternalSchema(db, 0);
72073
72074   /* If a transaction is open, the ResetInternalSchema() call above
72075   ** will not have called the xDisconnect() method on any virtual
72076   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
72077   ** call will do so. We need to do this before the check for active
72078   ** SQL statements below, as the v-table implementation may be storing
72079   ** some prepared statements internally.
72080   */
72081   sqlite3VtabRollback(db);
72082
72083   /* If there are any outstanding VMs, return SQLITE_BUSY. */
72084   if( db->pVdbe ){
72085     sqlite3Error(db, SQLITE_BUSY, 
72086         "Unable to close due to unfinalised statements");
72087     sqlite3_mutex_leave(db->mutex);
72088     return SQLITE_BUSY;
72089   }
72090   assert( !sqlite3SafetyCheck(db) );
72091
72092   /* FIX ME: db->magic may be set to SQLITE_MAGIC_CLOSED if the database
72093   ** cannot be opened for some reason. So this routine needs to run in
72094   ** that case. But maybe there should be an extra magic value for the
72095   ** "failed to open" state.
72096   **
72097   ** TODO: Coverage tests do not test the case where this condition is
72098   ** true. It's hard to see how to cause it without messing with threads.
72099   */
72100   if( db->magic!=SQLITE_MAGIC_CLOSED && sqlite3SafetyOn(db) ){
72101     /* printf("DID NOT CLOSE\n"); fflush(stdout); */
72102     sqlite3_mutex_leave(db->mutex);
72103     return SQLITE_ERROR;
72104   }
72105
72106   for(j=0; j<db->nDb; j++){
72107     struct Db *pDb = &db->aDb[j];
72108     if( pDb->pBt ){
72109       sqlite3BtreeClose(pDb->pBt);
72110       pDb->pBt = 0;
72111       if( j!=1 ){
72112         pDb->pSchema = 0;
72113       }
72114     }
72115   }
72116   sqlite3ResetInternalSchema(db, 0);
72117   assert( db->nDb<=2 );
72118   assert( db->aDb==db->aDbStatic );
72119   for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
72120     FuncDef *pFunc, *pNext;
72121     for(pFunc = (FuncDef*)sqliteHashData(i); pFunc; pFunc=pNext){
72122       pNext = pFunc->pNext;
72123       sqlite3_free(pFunc);
72124     }
72125   }
72126
72127   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
72128     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
72129     /* Invoke any destructors registered for collation sequence user data. */
72130     for(j=0; j<3; j++){
72131       if( pColl[j].xDel ){
72132         pColl[j].xDel(pColl[j].pUser);
72133       }
72134     }
72135     sqlite3_free(pColl);
72136   }
72137   sqlite3HashClear(&db->aCollSeq);
72138 #ifndef SQLITE_OMIT_VIRTUALTABLE
72139   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
72140     Module *pMod = (Module *)sqliteHashData(i);
72141     if( pMod->xDestroy ){
72142       pMod->xDestroy(pMod->pAux);
72143     }
72144     sqlite3_free(pMod);
72145   }
72146   sqlite3HashClear(&db->aModule);
72147 #endif
72148
72149   sqlite3HashClear(&db->aFunc);
72150   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
72151   if( db->pErr ){
72152     sqlite3ValueFree(db->pErr);
72153   }
72154   sqlite3CloseExtensions(db);
72155
72156   db->magic = SQLITE_MAGIC_ERROR;
72157
72158   /* The temp-database schema is allocated differently from the other schema
72159   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
72160   ** So it needs to be freed here. Todo: Why not roll the temp schema into
72161   ** the same sqliteMalloc() as the one that allocates the database 
72162   ** structure?
72163   */
72164   sqlite3_free(db->aDb[1].pSchema);
72165   sqlite3_mutex_leave(db->mutex);
72166   sqlite3_mutex_free(db->mutex);
72167   sqlite3_free(db);
72168   return SQLITE_OK;
72169 }
72170
72171 /*
72172 ** Rollback all database files.
72173 */
72174 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
72175   int i;
72176   int inTrans = 0;
72177   assert( sqlite3_mutex_held(db->mutex) );
72178   sqlite3MallocEnterBenignBlock(1);                 /* Enter benign region */
72179   for(i=0; i<db->nDb; i++){
72180     if( db->aDb[i].pBt ){
72181       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
72182         inTrans = 1;
72183       }
72184       sqlite3BtreeRollback(db->aDb[i].pBt);
72185       db->aDb[i].inTrans = 0;
72186     }
72187   }
72188   sqlite3VtabRollback(db);
72189   sqlite3MallocLeaveBenignBlock();                 /* Leave benign region */
72190
72191   if( db->flags&SQLITE_InternChanges ){
72192     sqlite3ExpirePreparedStatements(db);
72193     sqlite3ResetInternalSchema(db, 0);
72194   }
72195
72196   /* If one has been configured, invoke the rollback-hook callback */
72197   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
72198     db->xRollbackCallback(db->pRollbackArg);
72199   }
72200 }
72201
72202 /*
72203 ** Return a static string that describes the kind of error specified in the
72204 ** argument.
72205 */
72206 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
72207   const char *z;
72208   switch( rc & 0xff ){
72209     case SQLITE_ROW:
72210     case SQLITE_DONE:
72211     case SQLITE_OK:         z = "not an error";                          break;
72212     case SQLITE_ERROR:      z = "SQL logic error or missing database";   break;
72213     case SQLITE_PERM:       z = "access permission denied";              break;
72214     case SQLITE_ABORT:      z = "callback requested query abort";        break;
72215     case SQLITE_BUSY:       z = "database is locked";                    break;
72216     case SQLITE_LOCKED:     z = "database table is locked";              break;
72217     case SQLITE_NOMEM:      z = "out of memory";                         break;
72218     case SQLITE_READONLY:   z = "attempt to write a readonly database";  break;
72219     case SQLITE_INTERRUPT:  z = "interrupted";                           break;
72220     case SQLITE_IOERR:      z = "disk I/O error";                        break;
72221     case SQLITE_CORRUPT:    z = "database disk image is malformed";      break;
72222     case SQLITE_FULL:       z = "database or disk is full";              break;
72223     case SQLITE_CANTOPEN:   z = "unable to open database file";          break;
72224     case SQLITE_EMPTY:      z = "table contains no data";                break;
72225     case SQLITE_SCHEMA:     z = "database schema has changed";           break;
72226     case SQLITE_TOOBIG:     z = "String or BLOB exceeded size limit";    break;
72227     case SQLITE_CONSTRAINT: z = "constraint failed";                     break;
72228     case SQLITE_MISMATCH:   z = "datatype mismatch";                     break;
72229     case SQLITE_MISUSE:     z = "library routine called out of sequence";break;
72230     case SQLITE_NOLFS:      z = "kernel lacks large file support";       break;
72231     case SQLITE_AUTH:       z = "authorization denied";                  break;
72232     case SQLITE_FORMAT:     z = "auxiliary database format error";       break;
72233     case SQLITE_RANGE:      z = "bind or column index out of range";     break;
72234     case SQLITE_NOTADB:     z = "file is encrypted or is not a database";break;
72235     default:                z = "unknown error";                         break;
72236   }
72237   return z;
72238 }
72239
72240 /*
72241 ** This routine implements a busy callback that sleeps and tries
72242 ** again until a timeout value is reached.  The timeout value is
72243 ** an integer number of milliseconds passed in as the first
72244 ** argument.
72245 */
72246 static int sqliteDefaultBusyCallback(
72247  void *ptr,               /* Database connection */
72248  int count                /* Number of times table has been busy */
72249 ){
72250 #if OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
72251   static const u8 delays[] =
72252      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
72253   static const u8 totals[] =
72254      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
72255 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
72256   sqlite3 *db = (sqlite3 *)ptr;
72257   int timeout = db->busyTimeout;
72258   int delay, prior;
72259
72260   assert( count>=0 );
72261   if( count < NDELAY ){
72262     delay = delays[count];
72263     prior = totals[count];
72264   }else{
72265     delay = delays[NDELAY-1];
72266     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
72267   }
72268   if( prior + delay > timeout ){
72269     delay = timeout - prior;
72270     if( delay<=0 ) return 0;
72271   }
72272   sqlite3OsSleep(db->pVfs, delay*1000);
72273   return 1;
72274 #else
72275   sqlite3 *db = (sqlite3 *)ptr;
72276   int timeout = ((sqlite3 *)ptr)->busyTimeout;
72277   if( (count+1)*1000 > timeout ){
72278     return 0;
72279   }
72280   sqlite3OsSleep(db->pVfs, 1000000);
72281   return 1;
72282 #endif
72283 }
72284
72285 /*
72286 ** Invoke the given busy handler.
72287 **
72288 ** This routine is called when an operation failed with a lock.
72289 ** If this routine returns non-zero, the lock is retried.  If it
72290 ** returns 0, the operation aborts with an SQLITE_BUSY error.
72291 */
72292 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
72293   int rc;
72294   if( p==0 || p->xFunc==0 || p->nBusy<0 ) return 0;
72295   rc = p->xFunc(p->pArg, p->nBusy);
72296   if( rc==0 ){
72297     p->nBusy = -1;
72298   }else{
72299     p->nBusy++;
72300   }
72301   return rc; 
72302 }
72303
72304 /*
72305 ** This routine sets the busy callback for an Sqlite database to the
72306 ** given callback function with the given argument.
72307 */
72308 SQLITE_API int sqlite3_busy_handler(
72309   sqlite3 *db,
72310   int (*xBusy)(void*,int),
72311   void *pArg
72312 ){
72313   if( sqlite3SafetyCheck(db) ){
72314     return SQLITE_MISUSE;
72315   }
72316   sqlite3_mutex_enter(db->mutex);
72317   db->busyHandler.xFunc = xBusy;
72318   db->busyHandler.pArg = pArg;
72319   db->busyHandler.nBusy = 0;
72320   sqlite3_mutex_leave(db->mutex);
72321   return SQLITE_OK;
72322 }
72323
72324 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
72325 /*
72326 ** This routine sets the progress callback for an Sqlite database to the
72327 ** given callback function with the given argument. The progress callback will
72328 ** be invoked every nOps opcodes.
72329 */
72330 SQLITE_API void sqlite3_progress_handler(
72331   sqlite3 *db, 
72332   int nOps,
72333   int (*xProgress)(void*), 
72334   void *pArg
72335 ){
72336   if( !sqlite3SafetyCheck(db) ){
72337     sqlite3_mutex_enter(db->mutex);
72338     if( nOps>0 ){
72339       db->xProgress = xProgress;
72340       db->nProgressOps = nOps;
72341       db->pProgressArg = pArg;
72342     }else{
72343       db->xProgress = 0;
72344       db->nProgressOps = 0;
72345       db->pProgressArg = 0;
72346     }
72347     sqlite3_mutex_leave(db->mutex);
72348   }
72349 }
72350 #endif
72351
72352
72353 /*
72354 ** This routine installs a default busy handler that waits for the
72355 ** specified number of milliseconds before returning 0.
72356 */
72357 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
72358   if( sqlite3SafetyCheck(db) ){
72359     return SQLITE_MISUSE;
72360   }
72361   if( ms>0 ){
72362     db->busyTimeout = ms;
72363     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
72364   }else{
72365     sqlite3_busy_handler(db, 0, 0);
72366   }
72367   return SQLITE_OK;
72368 }
72369
72370 /*
72371 ** Cause any pending operation to stop at its earliest opportunity.
72372 */
72373 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
72374   if( db && (db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_BUSY) ){
72375     db->u1.isInterrupted = 1;
72376   }
72377 }
72378
72379
72380 /*
72381 ** This function is exactly the same as sqlite3_create_function(), except
72382 ** that it is designed to be called by internal code. The difference is
72383 ** that if a malloc() fails in sqlite3_create_function(), an error code
72384 ** is returned and the mallocFailed flag cleared. 
72385 */
72386 SQLITE_PRIVATE int sqlite3CreateFunc(
72387   sqlite3 *db,
72388   const char *zFunctionName,
72389   int nArg,
72390   int enc,
72391   void *pUserData,
72392   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
72393   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
72394   void (*xFinal)(sqlite3_context*)
72395 ){
72396   FuncDef *p;
72397   int nName;
72398
72399   assert( sqlite3_mutex_held(db->mutex) );
72400   if( sqlite3SafetyCheck(db) ){
72401     return SQLITE_MISUSE;
72402   }
72403   if( zFunctionName==0 ||
72404       (xFunc && (xFinal || xStep)) || 
72405       (!xFunc && (xFinal && !xStep)) ||
72406       (!xFunc && (!xFinal && xStep)) ||
72407       (nArg<-1 || nArg>127) ||
72408       (255<(nName = strlen(zFunctionName))) ){
72409     sqlite3Error(db, SQLITE_ERROR, "bad parameters");
72410     return SQLITE_ERROR;
72411   }
72412   
72413 #ifndef SQLITE_OMIT_UTF16
72414   /* If SQLITE_UTF16 is specified as the encoding type, transform this
72415   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
72416   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
72417   **
72418   ** If SQLITE_ANY is specified, add three versions of the function
72419   ** to the hash table.
72420   */
72421   if( enc==SQLITE_UTF16 ){
72422     enc = SQLITE_UTF16NATIVE;
72423   }else if( enc==SQLITE_ANY ){
72424     int rc;
72425     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
72426          pUserData, xFunc, xStep, xFinal);
72427     if( rc==SQLITE_OK ){
72428       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
72429           pUserData, xFunc, xStep, xFinal);
72430     }
72431     if( rc!=SQLITE_OK ){
72432       return rc;
72433     }
72434     enc = SQLITE_UTF16BE;
72435   }
72436 #else
72437   enc = SQLITE_UTF8;
72438 #endif
72439   
72440   /* Check if an existing function is being overridden or deleted. If so,
72441   ** and there are active VMs, then return SQLITE_BUSY. If a function
72442   ** is being overridden/deleted but there are no active VMs, allow the
72443   ** operation to continue but invalidate all precompiled statements.
72444   */
72445   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 0);
72446   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
72447     if( db->activeVdbeCnt ){
72448       sqlite3Error(db, SQLITE_BUSY, 
72449         "Unable to delete/modify user-function due to active statements");
72450       assert( !db->mallocFailed );
72451       return SQLITE_BUSY;
72452     }else{
72453       sqlite3ExpirePreparedStatements(db);
72454     }
72455   }
72456
72457   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 1);
72458   assert(p || db->mallocFailed);
72459   if( !p ){
72460     return SQLITE_NOMEM;
72461   }
72462   p->flags = 0;
72463   p->xFunc = xFunc;
72464   p->xStep = xStep;
72465   p->xFinalize = xFinal;
72466   p->pUserData = pUserData;
72467   p->nArg = nArg;
72468   return SQLITE_OK;
72469 }
72470
72471 /*
72472 ** Create new user functions.
72473 */
72474 SQLITE_API int sqlite3_create_function(
72475   sqlite3 *db,
72476   const char *zFunctionName,
72477   int nArg,
72478   int enc,
72479   void *p,
72480   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
72481   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
72482   void (*xFinal)(sqlite3_context*)
72483 ){
72484   int rc;
72485   sqlite3_mutex_enter(db->mutex);
72486   assert( !db->mallocFailed );
72487   rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
72488   rc = sqlite3ApiExit(db, rc);
72489   sqlite3_mutex_leave(db->mutex);
72490   return rc;
72491 }
72492
72493 #ifndef SQLITE_OMIT_UTF16
72494 SQLITE_API int sqlite3_create_function16(
72495   sqlite3 *db,
72496   const void *zFunctionName,
72497   int nArg,
72498   int eTextRep,
72499   void *p,
72500   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
72501   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
72502   void (*xFinal)(sqlite3_context*)
72503 ){
72504   int rc;
72505   char *zFunc8;
72506   sqlite3_mutex_enter(db->mutex);
72507   assert( !db->mallocFailed );
72508   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
72509   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
72510   sqlite3_free(zFunc8);
72511   rc = sqlite3ApiExit(db, rc);
72512   sqlite3_mutex_leave(db->mutex);
72513   return rc;
72514 }
72515 #endif
72516
72517
72518 /*
72519 ** Declare that a function has been overloaded by a virtual table.
72520 **
72521 ** If the function already exists as a regular global function, then
72522 ** this routine is a no-op.  If the function does not exist, then create
72523 ** a new one that always throws a run-time error.  
72524 **
72525 ** When virtual tables intend to provide an overloaded function, they
72526 ** should call this routine to make sure the global function exists.
72527 ** A global function must exist in order for name resolution to work
72528 ** properly.
72529 */
72530 SQLITE_API int sqlite3_overload_function(
72531   sqlite3 *db,
72532   const char *zName,
72533   int nArg
72534 ){
72535   int nName = strlen(zName);
72536   int rc;
72537   sqlite3_mutex_enter(db->mutex);
72538   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
72539     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
72540                       0, sqlite3InvalidFunction, 0, 0);
72541   }
72542   rc = sqlite3ApiExit(db, SQLITE_OK);
72543   sqlite3_mutex_leave(db->mutex);
72544   return rc;
72545 }
72546
72547 #ifndef SQLITE_OMIT_TRACE
72548 /*
72549 ** Register a trace function.  The pArg from the previously registered trace
72550 ** is returned.  
72551 **
72552 ** A NULL trace function means that no tracing is executes.  A non-NULL
72553 ** trace is a pointer to a function that is invoked at the start of each
72554 ** SQL statement.
72555 */
72556 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
72557   void *pOld;
72558   sqlite3_mutex_enter(db->mutex);
72559   pOld = db->pTraceArg;
72560   db->xTrace = xTrace;
72561   db->pTraceArg = pArg;
72562   sqlite3_mutex_leave(db->mutex);
72563   return pOld;
72564 }
72565 /*
72566 ** Register a profile function.  The pArg from the previously registered 
72567 ** profile function is returned.  
72568 **
72569 ** A NULL profile function means that no profiling is executes.  A non-NULL
72570 ** profile is a pointer to a function that is invoked at the conclusion of
72571 ** each SQL statement that is run.
72572 */
72573 SQLITE_API void *sqlite3_profile(
72574   sqlite3 *db,
72575   void (*xProfile)(void*,const char*,sqlite_uint64),
72576   void *pArg
72577 ){
72578   void *pOld;
72579   sqlite3_mutex_enter(db->mutex);
72580   pOld = db->pProfileArg;
72581   db->xProfile = xProfile;
72582   db->pProfileArg = pArg;
72583   sqlite3_mutex_leave(db->mutex);
72584   return pOld;
72585 }
72586 #endif /* SQLITE_OMIT_TRACE */
72587
72588 /*** EXPERIMENTAL ***
72589 **
72590 ** Register a function to be invoked when a transaction comments.
72591 ** If the invoked function returns non-zero, then the commit becomes a
72592 ** rollback.
72593 */
72594 SQLITE_API void *sqlite3_commit_hook(
72595   sqlite3 *db,              /* Attach the hook to this database */
72596   int (*xCallback)(void*),  /* Function to invoke on each commit */
72597   void *pArg                /* Argument to the function */
72598 ){
72599   void *pOld;
72600   sqlite3_mutex_enter(db->mutex);
72601   pOld = db->pCommitArg;
72602   db->xCommitCallback = xCallback;
72603   db->pCommitArg = pArg;
72604   sqlite3_mutex_leave(db->mutex);
72605   return pOld;
72606 }
72607
72608 /*
72609 ** Register a callback to be invoked each time a row is updated,
72610 ** inserted or deleted using this database connection.
72611 */
72612 SQLITE_API void *sqlite3_update_hook(
72613   sqlite3 *db,              /* Attach the hook to this database */
72614   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
72615   void *pArg                /* Argument to the function */
72616 ){
72617   void *pRet;
72618   sqlite3_mutex_enter(db->mutex);
72619   pRet = db->pUpdateArg;
72620   db->xUpdateCallback = xCallback;
72621   db->pUpdateArg = pArg;
72622   sqlite3_mutex_leave(db->mutex);
72623   return pRet;
72624 }
72625
72626 /*
72627 ** Register a callback to be invoked each time a transaction is rolled
72628 ** back by this database connection.
72629 */
72630 SQLITE_API void *sqlite3_rollback_hook(
72631   sqlite3 *db,              /* Attach the hook to this database */
72632   void (*xCallback)(void*), /* Callback function */
72633   void *pArg                /* Argument to the function */
72634 ){
72635   void *pRet;
72636   sqlite3_mutex_enter(db->mutex);
72637   pRet = db->pRollbackArg;
72638   db->xRollbackCallback = xCallback;
72639   db->pRollbackArg = pArg;
72640   sqlite3_mutex_leave(db->mutex);
72641   return pRet;
72642 }
72643
72644 /*
72645 ** This routine is called to create a connection to a database BTree
72646 ** driver.  If zFilename is the name of a file, then that file is
72647 ** opened and used.  If zFilename is the magic name ":memory:" then
72648 ** the database is stored in memory (and is thus forgotten as soon as
72649 ** the connection is closed.)  If zFilename is NULL then the database
72650 ** is a "virtual" database for transient use only and is deleted as
72651 ** soon as the connection is closed.
72652 **
72653 ** A virtual database can be either a disk file (that is automatically
72654 ** deleted when the file is closed) or it an be held entirely in memory,
72655 ** depending on the values of the TEMP_STORE compile-time macro and the
72656 ** db->temp_store variable, according to the following chart:
72657 **
72658 **       TEMP_STORE     db->temp_store     Location of temporary database
72659 **       ----------     --------------     ------------------------------
72660 **           0               any             file
72661 **           1                1              file
72662 **           1                2              memory
72663 **           1                0              file
72664 **           2                1              file
72665 **           2                2              memory
72666 **           2                0              memory
72667 **           3               any             memory
72668 */
72669 SQLITE_PRIVATE int sqlite3BtreeFactory(
72670   const sqlite3 *db,        /* Main database when opening aux otherwise 0 */
72671   const char *zFilename,    /* Name of the file containing the BTree database */
72672   int omitJournal,          /* if TRUE then do not journal this file */
72673   int nCache,               /* How many pages in the page cache */
72674   int vfsFlags,             /* Flags passed through to vfsOpen */
72675   Btree **ppBtree           /* Pointer to new Btree object written here */
72676 ){
72677   int btFlags = 0;
72678   int rc;
72679   
72680   assert( sqlite3_mutex_held(db->mutex) );
72681   assert( ppBtree != 0);
72682   if( omitJournal ){
72683     btFlags |= BTREE_OMIT_JOURNAL;
72684   }
72685   if( db->flags & SQLITE_NoReadlock ){
72686     btFlags |= BTREE_NO_READLOCK;
72687   }
72688   if( zFilename==0 ){
72689 #if TEMP_STORE==0
72690     /* Do nothing */
72691 #endif
72692 #ifndef SQLITE_OMIT_MEMORYDB
72693 #if TEMP_STORE==1
72694     if( db->temp_store==2 ) zFilename = ":memory:";
72695 #endif
72696 #if TEMP_STORE==2
72697     if( db->temp_store!=1 ) zFilename = ":memory:";
72698 #endif
72699 #if TEMP_STORE==3
72700     zFilename = ":memory:";
72701 #endif
72702 #endif /* SQLITE_OMIT_MEMORYDB */
72703   }
72704
72705   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
72706     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
72707   }
72708   rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
72709   if( rc==SQLITE_OK ){
72710     sqlite3BtreeSetCacheSize(*ppBtree, nCache);
72711   }
72712   return rc;
72713 }
72714
72715 /*
72716 ** Return UTF-8 encoded English language explanation of the most recent
72717 ** error.
72718 */
72719 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
72720   const char *z;
72721   if( !db ){
72722     return sqlite3ErrStr(SQLITE_NOMEM);
72723   }
72724   if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
72725     return sqlite3ErrStr(SQLITE_MISUSE);
72726   }
72727   sqlite3_mutex_enter(db->mutex);
72728   assert( !db->mallocFailed );
72729   z = (char*)sqlite3_value_text(db->pErr);
72730   if( z==0 ){
72731     z = sqlite3ErrStr(db->errCode);
72732   }
72733   sqlite3_mutex_leave(db->mutex);
72734   return z;
72735 }
72736
72737 #ifndef SQLITE_OMIT_UTF16
72738 /*
72739 ** Return UTF-16 encoded English language explanation of the most recent
72740 ** error.
72741 */
72742 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
72743   /* Because all the characters in the string are in the unicode
72744   ** range 0x00-0xFF, if we pad the big-endian string with a 
72745   ** zero byte, we can obtain the little-endian string with
72746   ** &big_endian[1].
72747   */
72748   static const char outOfMemBe[] = {
72749     0, 'o', 0, 'u', 0, 't', 0, ' ', 
72750     0, 'o', 0, 'f', 0, ' ', 
72751     0, 'm', 0, 'e', 0, 'm', 0, 'o', 0, 'r', 0, 'y', 0, 0, 0
72752   };
72753   static const char misuseBe [] = {
72754     0, 'l', 0, 'i', 0, 'b', 0, 'r', 0, 'a', 0, 'r', 0, 'y', 0, ' ', 
72755     0, 'r', 0, 'o', 0, 'u', 0, 't', 0, 'i', 0, 'n', 0, 'e', 0, ' ', 
72756     0, 'c', 0, 'a', 0, 'l', 0, 'l', 0, 'e', 0, 'd', 0, ' ', 
72757     0, 'o', 0, 'u', 0, 't', 0, ' ', 
72758     0, 'o', 0, 'f', 0, ' ', 
72759     0, 's', 0, 'e', 0, 'q', 0, 'u', 0, 'e', 0, 'n', 0, 'c', 0, 'e', 0, 0, 0
72760   };
72761
72762   const void *z;
72763   if( !db ){
72764     return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
72765   }
72766   if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
72767     return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
72768   }
72769   sqlite3_mutex_enter(db->mutex);
72770   assert( !db->mallocFailed );
72771   z = sqlite3_value_text16(db->pErr);
72772   if( z==0 ){
72773     sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
72774          SQLITE_UTF8, SQLITE_STATIC);
72775     z = sqlite3_value_text16(db->pErr);
72776   }
72777   sqlite3ApiExit(0, 0);
72778   sqlite3_mutex_leave(db->mutex);
72779   return z;
72780 }
72781 #endif /* SQLITE_OMIT_UTF16 */
72782
72783 /*
72784 ** Return the most recent error code generated by an SQLite routine. If NULL is
72785 ** passed to this function, we assume a malloc() failed during sqlite3_open().
72786 */
72787 SQLITE_API int sqlite3_errcode(sqlite3 *db){
72788   if( !db || db->mallocFailed ){
72789     return SQLITE_NOMEM;
72790   }
72791   if( sqlite3SafetyCheck(db) ){
72792     return SQLITE_MISUSE;
72793   }
72794   return db->errCode & db->errMask;
72795 }
72796
72797 /*
72798 ** Create a new collating function for database "db".  The name is zName
72799 ** and the encoding is enc.
72800 */
72801 static int createCollation(
72802   sqlite3* db, 
72803   const char *zName, 
72804   int enc, 
72805   void* pCtx,
72806   int(*xCompare)(void*,int,const void*,int,const void*),
72807   void(*xDel)(void*)
72808 ){
72809   CollSeq *pColl;
72810   int enc2;
72811   
72812   if( sqlite3SafetyCheck(db) ){
72813     return SQLITE_MISUSE;
72814   }
72815   assert( sqlite3_mutex_held(db->mutex) );
72816
72817   /* If SQLITE_UTF16 is specified as the encoding type, transform this
72818   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
72819   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
72820   */
72821   enc2 = enc & ~SQLITE_UTF16_ALIGNED;
72822   if( enc2==SQLITE_UTF16 ){
72823     enc2 = SQLITE_UTF16NATIVE;
72824   }
72825
72826   if( (enc2&~3)!=0 ){
72827     sqlite3Error(db, SQLITE_ERROR, "unknown encoding");
72828     return SQLITE_ERROR;
72829   }
72830
72831   /* Check if this call is removing or replacing an existing collation 
72832   ** sequence. If so, and there are active VMs, return busy. If there
72833   ** are no active VMs, invalidate any pre-compiled statements.
72834   */
72835   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, strlen(zName), 0);
72836   if( pColl && pColl->xCmp ){
72837     if( db->activeVdbeCnt ){
72838       sqlite3Error(db, SQLITE_BUSY, 
72839         "Unable to delete/modify collation sequence due to active statements");
72840       return SQLITE_BUSY;
72841     }
72842     sqlite3ExpirePreparedStatements(db);
72843
72844     /* If collation sequence pColl was created directly by a call to
72845     ** sqlite3_create_collation, and not generated by synthCollSeq(),
72846     ** then any copies made by synthCollSeq() need to be invalidated.
72847     ** Also, collation destructor - CollSeq.xDel() - function may need
72848     ** to be called.
72849     */ 
72850     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
72851       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, strlen(zName));
72852       int j;
72853       for(j=0; j<3; j++){
72854         CollSeq *p = &aColl[j];
72855         if( p->enc==pColl->enc ){
72856           if( p->xDel ){
72857             p->xDel(p->pUser);
72858           }
72859           p->xCmp = 0;
72860         }
72861       }
72862     }
72863   }
72864
72865   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, strlen(zName), 1);
72866   if( pColl ){
72867     pColl->xCmp = xCompare;
72868     pColl->pUser = pCtx;
72869     pColl->xDel = xDel;
72870     pColl->enc = enc2 | (enc & SQLITE_UTF16_ALIGNED);
72871   }
72872   sqlite3Error(db, SQLITE_OK, 0);
72873   return SQLITE_OK;
72874 }
72875
72876
72877 /*
72878 ** This routine does the work of opening a database on behalf of
72879 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
72880 ** is UTF-8 encoded.
72881 */
72882 static int openDatabase(
72883   const char *zFilename, /* Database filename UTF-8 encoded */
72884   sqlite3 **ppDb,        /* OUT: Returned database handle */
72885   unsigned flags,        /* Operational flags */
72886   const char *zVfs       /* Name of the VFS to use */
72887 ){
72888   sqlite3 *db;
72889   int rc;
72890   CollSeq *pColl;
72891
72892   /* Allocate the sqlite data structure */
72893   db = sqlite3MallocZero( sizeof(sqlite3) );
72894   if( db==0 ) goto opendb_out;
72895   db->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
72896   if( db->mutex==0 ){
72897     sqlite3_free(db);
72898     db = 0;
72899     goto opendb_out;
72900   }
72901   sqlite3_mutex_enter(db->mutex);
72902   db->errMask = 0xff;
72903   db->priorNewRowid = 0;
72904   db->nDb = 2;
72905   db->magic = SQLITE_MAGIC_BUSY;
72906   db->aDb = db->aDbStatic;
72907   db->autoCommit = 1;
72908   db->nextAutovac = -1;
72909   db->flags |= SQLITE_ShortColNames
72910 #if SQLITE_DEFAULT_FILE_FORMAT<4
72911                  | SQLITE_LegacyFileFmt
72912 #endif
72913 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
72914                  | SQLITE_LoadExtension
72915 #endif
72916       ;
72917   sqlite3HashInit(&db->aFunc, SQLITE_HASH_STRING, 0);
72918   sqlite3HashInit(&db->aCollSeq, SQLITE_HASH_STRING, 0);
72919 #ifndef SQLITE_OMIT_VIRTUALTABLE
72920   sqlite3HashInit(&db->aModule, SQLITE_HASH_STRING, 0);
72921 #endif
72922
72923   db->pVfs = sqlite3_vfs_find(zVfs);
72924   if( !db->pVfs ){
72925     rc = SQLITE_ERROR;
72926     db->magic = SQLITE_MAGIC_CLOSED;
72927     sqlite3Error(db, rc, "no such vfs: %s", (zVfs?zVfs:"(null)"));
72928     goto opendb_out;
72929   }
72930
72931   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
72932   ** and UTF-16, so add a version for each to avoid any unnecessary
72933   ** conversions. The only error that can occur here is a malloc() failure.
72934   */
72935   if( createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0) ||
72936       createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0) ||
72937       createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0) ||
72938       (db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0))==0 
72939   ){
72940     assert( db->mallocFailed );
72941     db->magic = SQLITE_MAGIC_CLOSED;
72942     goto opendb_out;
72943   }
72944
72945   /* Also add a UTF-8 case-insensitive collation sequence. */
72946   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
72947
72948   /* Set flags on the built-in collating sequences */
72949   db->pDfltColl->type = SQLITE_COLL_BINARY;
72950   pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "NOCASE", 6, 0);
72951   if( pColl ){
72952     pColl->type = SQLITE_COLL_NOCASE;
72953   }
72954
72955   /* Open the backend database driver */
72956   db->openFlags = flags;
72957   rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE, 
72958                            flags | SQLITE_OPEN_MAIN_DB,
72959                            &db->aDb[0].pBt);
72960   if( rc!=SQLITE_OK ){
72961     sqlite3Error(db, rc, 0);
72962     db->magic = SQLITE_MAGIC_CLOSED;
72963     goto opendb_out;
72964   }
72965   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
72966   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
72967
72968
72969   /* The default safety_level for the main database is 'full'; for the temp
72970   ** database it is 'NONE'. This matches the pager layer defaults.  
72971   */
72972   db->aDb[0].zName = "main";
72973   db->aDb[0].safety_level = 3;
72974 #ifndef SQLITE_OMIT_TEMPDB
72975   db->aDb[1].zName = "temp";
72976   db->aDb[1].safety_level = 1;
72977 #endif
72978
72979   db->magic = SQLITE_MAGIC_OPEN;
72980   if( db->mallocFailed ){
72981     goto opendb_out;
72982   }
72983
72984   /* Register all built-in functions, but do not attempt to read the
72985   ** database schema yet. This is delayed until the first time the database
72986   ** is accessed.
72987   */
72988   sqlite3Error(db, SQLITE_OK, 0);
72989   sqlite3RegisterBuiltinFunctions(db);
72990
72991   /* Load automatic extensions - extensions that have been registered
72992   ** using the sqlite3_automatic_extension() API.
72993   */
72994   (void)sqlite3AutoLoadExtensions(db);
72995   if( sqlite3_errcode(db)!=SQLITE_OK ){
72996     goto opendb_out;
72997   }
72998
72999 #ifdef SQLITE_ENABLE_FTS1
73000   if( !db->mallocFailed ){
73001     extern int sqlite3Fts1Init(sqlite3*);
73002     rc = sqlite3Fts1Init(db);
73003   }
73004 #endif
73005
73006 #ifdef SQLITE_ENABLE_FTS2
73007   if( !db->mallocFailed && rc==SQLITE_OK ){
73008     extern int sqlite3Fts2Init(sqlite3*);
73009     rc = sqlite3Fts2Init(db);
73010   }
73011 #endif
73012
73013 #ifdef SQLITE_ENABLE_FTS3
73014   if( !db->mallocFailed && rc==SQLITE_OK ){
73015     extern int sqlite3Fts3Init(sqlite3*);
73016     rc = sqlite3Fts3Init(db);
73017   }
73018 #endif
73019
73020 #ifdef SQLITE_ENABLE_ICU
73021   if( !db->mallocFailed && rc==SQLITE_OK ){
73022     extern int sqlite3IcuInit(sqlite3*);
73023     rc = sqlite3IcuInit(db);
73024   }
73025 #endif
73026   sqlite3Error(db, rc, 0);
73027
73028   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
73029   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
73030   ** mode.  Doing nothing at all also makes NORMAL the default.
73031   */
73032 #ifdef SQLITE_DEFAULT_LOCKING_MODE
73033   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
73034   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
73035                           SQLITE_DEFAULT_LOCKING_MODE);
73036 #endif
73037
73038 opendb_out:
73039   if( db && db->mutex ){
73040     sqlite3_mutex_leave(db->mutex);
73041   }
73042   if( SQLITE_NOMEM==(rc = sqlite3_errcode(db)) ){
73043     sqlite3_close(db);
73044     db = 0;
73045   }
73046   *ppDb = db;
73047   return sqlite3ApiExit(0, rc);
73048 }
73049
73050 /*
73051 ** Open a new database handle.
73052 */
73053 SQLITE_API int sqlite3_open(
73054   const char *zFilename, 
73055   sqlite3 **ppDb 
73056 ){
73057   return openDatabase(zFilename, ppDb,
73058                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
73059 }
73060 SQLITE_API int sqlite3_open_v2(
73061   const char *filename,   /* Database filename (UTF-8) */
73062   sqlite3 **ppDb,         /* OUT: SQLite db handle */
73063   int flags,              /* Flags */
73064   const char *zVfs        /* Name of VFS module to use */
73065 ){
73066   return openDatabase(filename, ppDb, flags, zVfs);
73067 }
73068
73069 #ifndef SQLITE_OMIT_UTF16
73070 /*
73071 ** Open a new database handle.
73072 */
73073 SQLITE_API int sqlite3_open16(
73074   const void *zFilename, 
73075   sqlite3 **ppDb
73076 ){
73077   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
73078   sqlite3_value *pVal;
73079   int rc = SQLITE_NOMEM;
73080
73081   assert( zFilename );
73082   assert( ppDb );
73083   *ppDb = 0;
73084   pVal = sqlite3ValueNew(0);
73085   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
73086   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
73087   if( zFilename8 ){
73088     rc = openDatabase(zFilename8, ppDb,
73089                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
73090     if( rc==SQLITE_OK && *ppDb ){
73091       rc = sqlite3_exec(*ppDb, "PRAGMA encoding = 'UTF-16'", 0, 0, 0);
73092       if( rc!=SQLITE_OK ){
73093         sqlite3_close(*ppDb);
73094         *ppDb = 0;
73095       }
73096     }
73097   }
73098   sqlite3ValueFree(pVal);
73099
73100   return sqlite3ApiExit(0, rc);
73101 }
73102 #endif /* SQLITE_OMIT_UTF16 */
73103
73104 /*
73105 ** Register a new collation sequence with the database handle db.
73106 */
73107 SQLITE_API int sqlite3_create_collation(
73108   sqlite3* db, 
73109   const char *zName, 
73110   int enc, 
73111   void* pCtx,
73112   int(*xCompare)(void*,int,const void*,int,const void*)
73113 ){
73114   int rc;
73115   sqlite3_mutex_enter(db->mutex);
73116   assert( !db->mallocFailed );
73117   rc = createCollation(db, zName, enc, pCtx, xCompare, 0);
73118   rc = sqlite3ApiExit(db, rc);
73119   sqlite3_mutex_leave(db->mutex);
73120   return rc;
73121 }
73122
73123 /*
73124 ** Register a new collation sequence with the database handle db.
73125 */
73126 SQLITE_API int sqlite3_create_collation_v2(
73127   sqlite3* db, 
73128   const char *zName, 
73129   int enc, 
73130   void* pCtx,
73131   int(*xCompare)(void*,int,const void*,int,const void*),
73132   void(*xDel)(void*)
73133 ){
73134   int rc;
73135   sqlite3_mutex_enter(db->mutex);
73136   assert( !db->mallocFailed );
73137   rc = createCollation(db, zName, enc, pCtx, xCompare, xDel);
73138   rc = sqlite3ApiExit(db, rc);
73139   sqlite3_mutex_leave(db->mutex);
73140   return rc;
73141 }
73142
73143 #ifndef SQLITE_OMIT_UTF16
73144 /*
73145 ** Register a new collation sequence with the database handle db.
73146 */
73147 SQLITE_API int sqlite3_create_collation16(
73148   sqlite3* db, 
73149   const char *zName, 
73150   int enc, 
73151   void* pCtx,
73152   int(*xCompare)(void*,int,const void*,int,const void*)
73153 ){
73154   int rc = SQLITE_OK;
73155   char *zName8; 
73156   sqlite3_mutex_enter(db->mutex);
73157   assert( !db->mallocFailed );
73158   zName8 = sqlite3Utf16to8(db, zName, -1);
73159   if( zName8 ){
73160     rc = createCollation(db, zName8, enc, pCtx, xCompare, 0);
73161     sqlite3_free(zName8);
73162   }
73163   rc = sqlite3ApiExit(db, rc);
73164   sqlite3_mutex_leave(db->mutex);
73165   return rc;
73166 }
73167 #endif /* SQLITE_OMIT_UTF16 */
73168
73169 /*
73170 ** Register a collation sequence factory callback with the database handle
73171 ** db. Replace any previously installed collation sequence factory.
73172 */
73173 SQLITE_API int sqlite3_collation_needed(
73174   sqlite3 *db, 
73175   void *pCollNeededArg, 
73176   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
73177 ){
73178   if( sqlite3SafetyCheck(db) ){
73179     return SQLITE_MISUSE;
73180   }
73181   sqlite3_mutex_enter(db->mutex);
73182   db->xCollNeeded = xCollNeeded;
73183   db->xCollNeeded16 = 0;
73184   db->pCollNeededArg = pCollNeededArg;
73185   sqlite3_mutex_leave(db->mutex);
73186   return SQLITE_OK;
73187 }
73188
73189 #ifndef SQLITE_OMIT_UTF16
73190 /*
73191 ** Register a collation sequence factory callback with the database handle
73192 ** db. Replace any previously installed collation sequence factory.
73193 */
73194 SQLITE_API int sqlite3_collation_needed16(
73195   sqlite3 *db, 
73196   void *pCollNeededArg, 
73197   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
73198 ){
73199   if( sqlite3SafetyCheck(db) ){
73200     return SQLITE_MISUSE;
73201   }
73202   sqlite3_mutex_enter(db->mutex);
73203   db->xCollNeeded = 0;
73204   db->xCollNeeded16 = xCollNeeded16;
73205   db->pCollNeededArg = pCollNeededArg;
73206   sqlite3_mutex_leave(db->mutex);
73207   return SQLITE_OK;
73208 }
73209 #endif /* SQLITE_OMIT_UTF16 */
73210
73211 #ifndef SQLITE_OMIT_GLOBALRECOVER
73212 /*
73213 ** This function is now an anachronism. It used to be used to recover from a
73214 ** malloc() failure, but SQLite now does this automatically.
73215 */
73216 SQLITE_API int sqlite3_global_recover(void){
73217   return SQLITE_OK;
73218 }
73219 #endif
73220
73221 /*
73222 ** Test to see whether or not the database connection is in autocommit
73223 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
73224 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
73225 ** by the next COMMIT or ROLLBACK.
73226 **
73227 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
73228 */
73229 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
73230   return db->autoCommit;
73231 }
73232
73233 #ifdef SQLITE_DEBUG
73234 /*
73235 ** The following routine is subtituted for constant SQLITE_CORRUPT in
73236 ** debugging builds.  This provides a way to set a breakpoint for when
73237 ** corruption is first detected.
73238 */
73239 SQLITE_PRIVATE int sqlite3Corrupt(void){
73240   return SQLITE_CORRUPT;
73241 }
73242 #endif
73243
73244 /*
73245 ** This is a convenience routine that makes sure that all thread-specific
73246 ** data for this thread has been deallocated.
73247 **
73248 ** SQLite no longer uses thread-specific data so this routine is now a
73249 ** no-op.  It is retained for historical compatibility.
73250 */
73251 SQLITE_API void sqlite3_thread_cleanup(void){
73252 }
73253
73254 /*
73255 ** Return meta information about a specific column of a database table.
73256 ** See comment in sqlite3.h (sqlite.h.in) for details.
73257 */
73258 #ifdef SQLITE_ENABLE_COLUMN_METADATA
73259 SQLITE_API int sqlite3_table_column_metadata(
73260   sqlite3 *db,                /* Connection handle */
73261   const char *zDbName,        /* Database name or NULL */
73262   const char *zTableName,     /* Table name */
73263   const char *zColumnName,    /* Column name */
73264   char const **pzDataType,    /* OUTPUT: Declared data type */
73265   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
73266   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
73267   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
73268   int *pAutoinc               /* OUTPUT: True if colums is auto-increment */
73269 ){
73270   int rc;
73271   char *zErrMsg = 0;
73272   Table *pTab = 0;
73273   Column *pCol = 0;
73274   int iCol;
73275
73276   char const *zDataType = 0;
73277   char const *zCollSeq = 0;
73278   int notnull = 0;
73279   int primarykey = 0;
73280   int autoinc = 0;
73281
73282   /* Ensure the database schema has been loaded */
73283   if( sqlite3SafetyOn(db) ){
73284     return SQLITE_MISUSE;
73285   }
73286   sqlite3_mutex_enter(db->mutex);
73287   rc = sqlite3Init(db, &zErrMsg);
73288   if( SQLITE_OK!=rc ){
73289     goto error_out;
73290   }
73291
73292   /* Locate the table in question */
73293   pTab = sqlite3FindTable(db, zTableName, zDbName);
73294   if( !pTab || pTab->pSelect ){
73295     pTab = 0;
73296     goto error_out;
73297   }
73298
73299   /* Find the column for which info is requested */
73300   if( sqlite3IsRowid(zColumnName) ){
73301     iCol = pTab->iPKey;
73302     if( iCol>=0 ){
73303       pCol = &pTab->aCol[iCol];
73304     }
73305   }else{
73306     for(iCol=0; iCol<pTab->nCol; iCol++){
73307       pCol = &pTab->aCol[iCol];
73308       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
73309         break;
73310       }
73311     }
73312     if( iCol==pTab->nCol ){
73313       pTab = 0;
73314       goto error_out;
73315     }
73316   }
73317
73318   /* The following block stores the meta information that will be returned
73319   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
73320   ** and autoinc. At this point there are two possibilities:
73321   ** 
73322   **     1. The specified column name was rowid", "oid" or "_rowid_" 
73323   **        and there is no explicitly declared IPK column. 
73324   **
73325   **     2. The table is not a view and the column name identified an 
73326   **        explicitly declared column. Copy meta information from *pCol.
73327   */ 
73328   if( pCol ){
73329     zDataType = pCol->zType;
73330     zCollSeq = pCol->zColl;
73331     notnull = (pCol->notNull?1:0);
73332     primarykey  = (pCol->isPrimKey?1:0);
73333     autoinc = ((pTab->iPKey==iCol && pTab->autoInc)?1:0);
73334   }else{
73335     zDataType = "INTEGER";
73336     primarykey = 1;
73337   }
73338   if( !zCollSeq ){
73339     zCollSeq = "BINARY";
73340   }
73341
73342 error_out:
73343   if( sqlite3SafetyOff(db) ){
73344     rc = SQLITE_MISUSE;
73345   }
73346
73347   /* Whether the function call succeeded or failed, set the output parameters
73348   ** to whatever their local counterparts contain. If an error did occur,
73349   ** this has the effect of zeroing all output parameters.
73350   */
73351   if( pzDataType ) *pzDataType = zDataType;
73352   if( pzCollSeq ) *pzCollSeq = zCollSeq;
73353   if( pNotNull ) *pNotNull = notnull;
73354   if( pPrimaryKey ) *pPrimaryKey = primarykey;
73355   if( pAutoinc ) *pAutoinc = autoinc;
73356
73357   if( SQLITE_OK==rc && !pTab ){
73358     sqlite3SetString(&zErrMsg, "no such table column: ", zTableName, ".", 
73359         zColumnName, 0);
73360     rc = SQLITE_ERROR;
73361   }
73362   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
73363   sqlite3_free(zErrMsg);
73364   rc = sqlite3ApiExit(db, rc);
73365   sqlite3_mutex_leave(db->mutex);
73366   return rc;
73367 }
73368 #endif
73369
73370 /*
73371 ** Sleep for a little while.  Return the amount of time slept.
73372 */
73373 SQLITE_API int sqlite3_sleep(int ms){
73374   sqlite3_vfs *pVfs;
73375   int rc;
73376   pVfs = sqlite3_vfs_find(0);
73377
73378   /* This function works in milliseconds, but the underlying OsSleep() 
73379   ** API uses microseconds. Hence the 1000's.
73380   */
73381   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
73382   return rc;
73383 }
73384
73385 /*
73386 ** Enable or disable the extended result codes.
73387 */
73388 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
73389   sqlite3_mutex_enter(db->mutex);
73390   db->errMask = onoff ? 0xffffffff : 0xff;
73391   sqlite3_mutex_leave(db->mutex);
73392   return SQLITE_OK;
73393 }
73394
73395 /*
73396 ** Invoke the xFileControl method on a particular database.
73397 */
73398 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
73399   int rc = SQLITE_ERROR;
73400   int iDb;
73401   sqlite3_mutex_enter(db->mutex);
73402   if( zDbName==0 ){
73403     iDb = 0;
73404   }else{
73405     for(iDb=0; iDb<db->nDb; iDb++){
73406       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
73407     }
73408   }
73409   if( iDb<db->nDb ){
73410     Btree *pBtree = db->aDb[iDb].pBt;
73411     if( pBtree ){
73412       Pager *pPager;
73413       sqlite3BtreeEnter(pBtree);
73414       pPager = sqlite3BtreePager(pBtree);
73415       if( pPager ){
73416         sqlite3_file *fd = sqlite3PagerFile(pPager);
73417         if( fd ){
73418           rc = sqlite3OsFileControl(fd, op, pArg);
73419         }
73420       }
73421       sqlite3BtreeLeave(pBtree);
73422     }
73423   }
73424   sqlite3_mutex_leave(db->mutex);
73425   return rc;   
73426 }
73427
73428 /************** End of main.c ************************************************/
73429 /******************************************************************************
73430 ** This file is an amalgamation of separate C source files from the SQLite
73431 ** Full Text Search extension 2 (fts3).  By combining all the individual C 
73432 ** code  files into this single large file, the entire code can be compiled 
73433 ** as a one translation unit.  This allows many compilers to do optimizations
73434 ** that would not be possible if the files were compiled separately.  It also
73435 ** makes the code easier to import into other projects.
73436 **
73437 ** This amalgamation was generated on 2007-12-14 17:40:57 UTC.
73438 */
73439 /************** Begin file fts3.c ********************************************/
73440 /*
73441 ** 2006 Oct 10
73442 **
73443 ** The author disclaims copyright to this source code.  In place of
73444 ** a legal notice, here is a blessing:
73445 **
73446 **    May you do good and not evil.
73447 **    May you find forgiveness for yourself and forgive others.
73448 **    May you share freely, never taking more than you give.
73449 **
73450 ******************************************************************************
73451 **
73452 ** This is an SQLite module implementing full-text search.
73453 */
73454
73455 /*
73456 ** The code in this file is only compiled if:
73457 **
73458 **     * The FTS3 module is being built as an extension
73459 **       (in which case SQLITE_CORE is not defined), or
73460 **
73461 **     * The FTS3 module is being built into the core of
73462 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
73463 */
73464
73465 /* TODO(shess) Consider exporting this comment to an HTML file or the
73466 ** wiki.
73467 */
73468 /* The full-text index is stored in a series of b+tree (-like)
73469 ** structures called segments which map terms to doclists.  The
73470 ** structures are like b+trees in layout, but are constructed from the
73471 ** bottom up in optimal fashion and are not updatable.  Since trees
73472 ** are built from the bottom up, things will be described from the
73473 ** bottom up.
73474 **
73475 **
73476 **** Varints ****
73477 ** The basic unit of encoding is a variable-length integer called a
73478 ** varint.  We encode variable-length integers in little-endian order
73479 ** using seven bits * per byte as follows:
73480 **
73481 ** KEY:
73482 **         A = 0xxxxxxx    7 bits of data and one flag bit
73483 **         B = 1xxxxxxx    7 bits of data and one flag bit
73484 **
73485 **  7 bits - A
73486 ** 14 bits - BA
73487 ** 21 bits - BBA
73488 ** and so on.
73489 **
73490 ** This is identical to how sqlite encodes varints (see util.c).
73491 **
73492 **
73493 **** Document lists ****
73494 ** A doclist (document list) holds a docid-sorted list of hits for a
73495 ** given term.  Doclists hold docids, and can optionally associate
73496 ** token positions and offsets with docids.
73497 **
73498 ** A DL_POSITIONS_OFFSETS doclist is stored like this:
73499 **
73500 ** array {
73501 **   varint docid;
73502 **   array {                (position list for column 0)
73503 **     varint position;     (delta from previous position plus POS_BASE)
73504 **     varint startOffset;  (delta from previous startOffset)
73505 **     varint endOffset;    (delta from startOffset)
73506 **   }
73507 **   array {
73508 **     varint POS_COLUMN;   (marks start of position list for new column)
73509 **     varint column;       (index of new column)
73510 **     array {
73511 **       varint position;   (delta from previous position plus POS_BASE)
73512 **       varint startOffset;(delta from previous startOffset)
73513 **       varint endOffset;  (delta from startOffset)
73514 **     }
73515 **   }
73516 **   varint POS_END;        (marks end of positions for this document.
73517 ** }
73518 **
73519 ** Here, array { X } means zero or more occurrences of X, adjacent in
73520 ** memory.  A "position" is an index of a token in the token stream
73521 ** generated by the tokenizer, while an "offset" is a byte offset,
73522 ** both based at 0.  Note that POS_END and POS_COLUMN occur in the
73523 ** same logical place as the position element, and act as sentinals
73524 ** ending a position list array.
73525 **
73526 ** A DL_POSITIONS doclist omits the startOffset and endOffset
73527 ** information.  A DL_DOCIDS doclist omits both the position and
73528 ** offset information, becoming an array of varint-encoded docids.
73529 **
73530 ** On-disk data is stored as type DL_DEFAULT, so we don't serialize
73531 ** the type.  Due to how deletion is implemented in the segmentation
73532 ** system, on-disk doclists MUST store at least positions.
73533 **
73534 **
73535 **** Segment leaf nodes ****
73536 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
73537 ** nodes are written using LeafWriter, and read using LeafReader (to
73538 ** iterate through a single leaf node's data) and LeavesReader (to
73539 ** iterate through a segment's entire leaf layer).  Leaf nodes have
73540 ** the format:
73541 **
73542 ** varint iHeight;             (height from leaf level, always 0)
73543 ** varint nTerm;               (length of first term)
73544 ** char pTerm[nTerm];          (content of first term)
73545 ** varint nDoclist;            (length of term's associated doclist)
73546 ** char pDoclist[nDoclist];    (content of doclist)
73547 ** array {
73548 **                             (further terms are delta-encoded)
73549 **   varint nPrefix;           (length of prefix shared with previous term)
73550 **   varint nSuffix;           (length of unshared suffix)
73551 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
73552 **   varint nDoclist;          (length of term's associated doclist)
73553 **   char pDoclist[nDoclist];  (content of doclist)
73554 ** }
73555 **
73556 ** Here, array { X } means zero or more occurrences of X, adjacent in
73557 ** memory.
73558 **
73559 ** Leaf nodes are broken into blocks which are stored contiguously in
73560 ** the %_segments table in sorted order.  This means that when the end
73561 ** of a node is reached, the next term is in the node with the next
73562 ** greater node id.
73563 **
73564 ** New data is spilled to a new leaf node when the current node
73565 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
73566 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
73567 ** node (a leaf node with a single term and doclist).  The goal of
73568 ** these settings is to pack together groups of small doclists while
73569 ** making it efficient to directly access large doclists.  The
73570 ** assumption is that large doclists represent terms which are more
73571 ** likely to be query targets.
73572 **
73573 ** TODO(shess) It may be useful for blocking decisions to be more
73574 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
73575 ** node rather than splitting into 2k and .5k nodes.  My intuition is
73576 ** that this might extend through 2x or 4x the pagesize.
73577 **
73578 **
73579 **** Segment interior nodes ****
73580 ** Segment interior nodes store blockids for subtree nodes and terms
73581 ** to describe what data is stored by the each subtree.  Interior
73582 ** nodes are written using InteriorWriter, and read using
73583 ** InteriorReader.  InteriorWriters are created as needed when
73584 ** SegmentWriter creates new leaf nodes, or when an interior node
73585 ** itself grows too big and must be split.  The format of interior
73586 ** nodes:
73587 **
73588 ** varint iHeight;           (height from leaf level, always >0)
73589 ** varint iBlockid;          (block id of node's leftmost subtree)
73590 ** optional {
73591 **   varint nTerm;           (length of first term)
73592 **   char pTerm[nTerm];      (content of first term)
73593 **   array {
73594 **                                (further terms are delta-encoded)
73595 **     varint nPrefix;            (length of shared prefix with previous term)
73596 **     varint nSuffix;            (length of unshared suffix)
73597 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
73598 **   }
73599 ** }
73600 **
73601 ** Here, optional { X } means an optional element, while array { X }
73602 ** means zero or more occurrences of X, adjacent in memory.
73603 **
73604 ** An interior node encodes n terms separating n+1 subtrees.  The
73605 ** subtree blocks are contiguous, so only the first subtree's blockid
73606 ** is encoded.  The subtree at iBlockid will contain all terms less
73607 ** than the first term encoded (or all terms if no term is encoded).
73608 ** Otherwise, for terms greater than or equal to pTerm[i] but less
73609 ** than pTerm[i+1], the subtree for that term will be rooted at
73610 ** iBlockid+i.  Interior nodes only store enough term data to
73611 ** distinguish adjacent children (if the rightmost term of the left
73612 ** child is "something", and the leftmost term of the right child is
73613 ** "wicked", only "w" is stored).
73614 **
73615 ** New data is spilled to a new interior node at the same height when
73616 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
73617 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
73618 ** interior nodes and making the tree too skinny.  The interior nodes
73619 ** at a given height are naturally tracked by interior nodes at
73620 ** height+1, and so on.
73621 **
73622 **
73623 **** Segment directory ****
73624 ** The segment directory in table %_segdir stores meta-information for
73625 ** merging and deleting segments, and also the root node of the
73626 ** segment's tree.
73627 **
73628 ** The root node is the top node of the segment's tree after encoding
73629 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
73630 ** This could be either a leaf node or an interior node.  If the top
73631 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
73632 ** and a new root interior node is generated (which should always fit
73633 ** within ROOT_MAX because it only needs space for 2 varints, the
73634 ** height and the blockid of the previous root).
73635 **
73636 ** The meta-information in the segment directory is:
73637 **   level               - segment level (see below)
73638 **   idx                 - index within level
73639 **                       - (level,idx uniquely identify a segment)
73640 **   start_block         - first leaf node
73641 **   leaves_end_block    - last leaf node
73642 **   end_block           - last block (including interior nodes)
73643 **   root                - contents of root node
73644 **
73645 ** If the root node is a leaf node, then start_block,
73646 ** leaves_end_block, and end_block are all 0.
73647 **
73648 **
73649 **** Segment merging ****
73650 ** To amortize update costs, segments are groups into levels and
73651 ** merged in matches.  Each increase in level represents exponentially
73652 ** more documents.
73653 **
73654 ** New documents (actually, document updates) are tokenized and
73655 ** written individually (using LeafWriter) to a level 0 segment, with
73656 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
73657 ** level 0 segments are merged into a single level 1 segment.  Level 1
73658 ** is populated like level 0, and eventually MERGE_COUNT level 1
73659 ** segments are merged to a single level 2 segment (representing
73660 ** MERGE_COUNT^2 updates), and so on.
73661 **
73662 ** A segment merge traverses all segments at a given level in
73663 ** parallel, performing a straightforward sorted merge.  Since segment
73664 ** leaf nodes are written in to the %_segments table in order, this
73665 ** merge traverses the underlying sqlite disk structures efficiently.
73666 ** After the merge, all segment blocks from the merged level are
73667 ** deleted.
73668 **
73669 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
73670 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
73671 ** very similar performance numbers to 16 on insertion, though they're
73672 ** a tiny bit slower (perhaps due to more overhead in merge-time
73673 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
73674 ** 16, 2 about 66% slower than 16.
73675 **
73676 ** At query time, high MERGE_COUNT increases the number of segments
73677 ** which need to be scanned and merged.  For instance, with 100k docs
73678 ** inserted:
73679 **
73680 **    MERGE_COUNT   segments
73681 **       16           25
73682 **        8           12
73683 **        4           10
73684 **        2            6
73685 **
73686 ** This appears to have only a moderate impact on queries for very
73687 ** frequent terms (which are somewhat dominated by segment merge
73688 ** costs), and infrequent and non-existent terms still seem to be fast
73689 ** even with many segments.
73690 **
73691 ** TODO(shess) That said, it would be nice to have a better query-side
73692 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
73693 ** optimizations to things like doclist merging will swing the sweet
73694 ** spot around.
73695 **
73696 **
73697 **
73698 **** Handling of deletions and updates ****
73699 ** Since we're using a segmented structure, with no docid-oriented
73700 ** index into the term index, we clearly cannot simply update the term
73701 ** index when a document is deleted or updated.  For deletions, we
73702 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
73703 ** we simply write the new doclist.  Segment merges overwrite older
73704 ** data for a particular docid with newer data, so deletes or updates
73705 ** will eventually overtake the earlier data and knock it out.  The
73706 ** query logic likewise merges doclists so that newer data knocks out
73707 ** older data.
73708 **
73709 ** TODO(shess) Provide a VACUUM type operation to clear out all
73710 ** deletions and duplications.  This would basically be a forced merge
73711 ** into a single segment.
73712 */
73713
73714 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
73715
73716 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
73717 # define SQLITE_CORE 1
73718 #endif
73719
73720 #include <assert.h>
73721 #include <stdlib.h>
73722 #include <stdio.h>
73723 #include <string.h>
73724 #include <ctype.h>
73725
73726 /************** Include fts3.h in the middle of fts3.c ***********************/
73727 /************** Begin file fts3.h ********************************************/
73728 /*
73729 ** 2006 Oct 10
73730 **
73731 ** The author disclaims copyright to this source code.  In place of
73732 ** a legal notice, here is a blessing:
73733 **
73734 **    May you do good and not evil.
73735 **    May you find forgiveness for yourself and forgive others.
73736 **    May you share freely, never taking more than you give.
73737 **
73738 ******************************************************************************
73739 **
73740 ** This header file is used by programs that want to link against the
73741 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
73742 */
73743 /************** Include sqlite3.h in the middle of fts3.h ********************/
73744 /************** Begin file sqlite3.h *****************************************/
73745 /*
73746 ** 2001 September 15
73747 **
73748 ** The author disclaims copyright to this source code.  In place of
73749 ** a legal notice, here is a blessing:
73750 **
73751 **    May you do good and not evil.
73752 **    May you find forgiveness for yourself and forgive others.
73753 **    May you share freely, never taking more than you give.
73754 **
73755 *************************************************************************
73756 ** This header file defines the interface that the SQLite library
73757 ** presents to client programs.  If a C-function, structure, datatype,
73758 ** or constant definition does not appear in this file, then it is
73759 ** not a published API of SQLite, is subject to change without
73760 ** notice, and should not be referenced by programs that use SQLite.
73761 **
73762 ** Some of the definitions that are in this file are marked as
73763 ** "experimental".  Experimental interfaces are normally new
73764 ** features recently added to SQLite.  We do not anticipate changes 
73765 ** to experimental interfaces but reserve to make minor changes if
73766 ** experience from use "in the wild" suggest such changes are prudent.
73767 **
73768 ** The official C-language API documentation for SQLite is derived
73769 ** from comments in this file.  This file is the authoritative source
73770 ** on how SQLite interfaces are suppose to operate.
73771 **
73772 ** The name of this file under configuration management is "sqlite.h.in".
73773 ** The makefile makes some minor changes to this file (such as inserting
73774 ** the version number) and changes its name to "sqlite3.h" as
73775 ** part of the build process.
73776 **
73777 ** @(#) $Id: sqlite.h.in,v 1.278 2007/12/13 21:54:11 drh Exp $
73778 */
73779 #ifndef _SQLITE3_H_
73780 #define _SQLITE3_H_
73781 #include <stdarg.h>     /* Needed for the definition of va_list */
73782
73783 /*
73784 ** Make sure we can call this stuff from C++.
73785 */
73786 #if 0
73787 extern "C" {
73788 #endif
73789
73790
73791 /*
73792 ** Add the ability to override 'extern'
73793 */
73794 #ifndef SQLITE_EXTERN
73795 # define SQLITE_EXTERN extern
73796 #endif
73797
73798 /*
73799 ** Make sure these symbols where not defined by some previous header
73800 ** file.
73801 */
73802 #ifdef SQLITE_VERSION
73803 # undef SQLITE_VERSION
73804 #endif
73805 #ifdef SQLITE_VERSION_NUMBER
73806 # undef SQLITE_VERSION_NUMBER
73807 #endif
73808
73809 /*
73810 ** CAPI3REF: Compile-Time Library Version Numbers {F10010}
73811 **
73812 ** {F10011} The #define in the sqlite3.h header file named
73813 ** SQLITE_VERSION resolves to a string literal that identifies
73814 ** the version of the SQLite library in the format "X.Y.Z", where
73815 ** X is the major version number, Y is the minor version number and Z
73816 ** is the release number.  The X.Y.Z might be followed by "alpha" or "beta".
73817 ** {END} For example "3.1.1beta".
73818 **
73819 ** The X value is always 3 in SQLite.  The X value only changes when
73820 ** backwards compatibility is broken and we intend to never break
73821 ** backwards compatibility.  The Y value only changes when
73822 ** there are major feature enhancements that are forwards compatible
73823 ** but not backwards compatible.  The Z value is incremented with
73824 ** each release but resets back to 0 when Y is incremented.
73825 **
73826 ** {F10014} The SQLITE_VERSION_NUMBER #define resolves to an integer
73827 ** with the value  (X*1000000 + Y*1000 + Z) where X, Y, and Z are as
73828 ** with SQLITE_VERSION. {END} For example, for version "3.1.1beta", 
73829 ** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using 
73830 ** version 3.1.1 or greater at compile time, programs may use the test 
73831 ** (SQLITE_VERSION_NUMBER>=3001001).
73832 **
73833 ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
73834 */
73835 #define SQLITE_VERSION         "3.5.4"
73836 #define SQLITE_VERSION_NUMBER 3005004
73837
73838 /*
73839 ** CAPI3REF: Run-Time Library Version Numbers {F10020}
73840 **
73841 ** {F10021} The sqlite3_libversion_number() interface returns an integer
73842 ** equal to [SQLITE_VERSION_NUMBER].  {END} The value returned
73843 ** by this routine should only be different from the header values
73844 ** if the application is compiled using an sqlite3.h header from a
73845 ** different version of SQLite than library.  Cautious programmers might
73846 ** include a check in their application to verify that 
73847 ** sqlite3_libversion_number() always returns the value 
73848 ** [SQLITE_VERSION_NUMBER].
73849 **
73850 ** {F10022} The sqlite3_version[] string constant contains the text of the
73851 ** [SQLITE_VERSION] string. {F10023} The sqlite3_libversion() function returns
73852 ** a pointer to the sqlite3_version[] string constant. {END} The 
73853 ** sqlite3_libversion() function
73854 ** is provided for DLL users who can only access functions and not
73855 ** constants within the DLL.
73856 */
73857 SQLITE_EXTERN const char sqlite3_version[];
73858 const char *sqlite3_libversion(void);
73859 int sqlite3_libversion_number(void);
73860
73861 /*
73862 ** CAPI3REF: Test To See If The Library Is Threadsafe {F10100}
73863 **
73864 ** {F10101} The sqlite3_threadsafe() routine returns nonzero
73865 ** if SQLite was compiled with its mutexes enabled or zero if
73866 ** SQLite was compiled with mutexes disabled. {END}  If this
73867 ** routine returns false, then it is not safe for simultaneously
73868 ** running threads to both invoke SQLite interfaces.
73869 **
73870 ** Really all this routine does is return true if SQLite was
73871 ** compiled with the -DSQLITE_THREADSAFE=1 option and false if
73872 ** compiled with -DSQLITE_THREADSAFE=0.  If SQLite uses an
73873 ** application-defined mutex subsystem, malloc subsystem, collating
73874 ** sequence, VFS, SQL function, progress callback, commit hook,
73875 ** extension, or other accessories and these add-ons are not
73876 ** threadsafe, then clearly the combination will not be threadsafe
73877 ** either.  Hence, this routine never reports that the library
73878 ** is guaranteed to be threadsafe, only when it is guaranteed not
73879 ** to be.
73880 */
73881 int sqlite3_threadsafe(void);
73882
73883 /*
73884 ** CAPI3REF: Database Connection Handle {F12000}
73885 **
73886 ** Each open SQLite database is represented by pointer to an instance of the
73887 ** opaque structure named "sqlite3".  It is useful to think of an sqlite3
73888 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
73889 ** [sqlite3_open_v2()] interfaces are its constructors
73890 ** and [sqlite3_close()] is its destructor.  There are many other interfaces
73891 ** (such as [sqlite3_prepare_v2()], [sqlite3_create_function()], and
73892 ** [sqlite3_busy_timeout()] to name but three) that are methods on this
73893 ** object.
73894 */
73895 typedef struct sqlite3 sqlite3;
73896
73897
73898 /*
73899 ** CAPI3REF: 64-Bit Integer Types {F10200}
73900 **
73901 ** Because there is no cross-platform way to specify such types
73902 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
73903 ** {F10201} The sqlite_int64 and sqlite3_int64 types specify a
73904 ** 64-bit signed integer. {F10202} The sqlite_uint64 and
73905 ** sqlite3_uint64 types specify a 64-bit unsigned integer. {END}
73906 **
73907 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type
73908 ** definitions.  The sqlite_int64 and sqlite_uint64 types are
73909 ** supported for backwards compatibility only.
73910 */
73911 #ifdef SQLITE_INT64_TYPE
73912   typedef SQLITE_INT64_TYPE sqlite_int64;
73913   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
73914 #elif defined(_MSC_VER) || defined(__BORLANDC__)
73915   typedef __int64 sqlite_int64;
73916   typedef unsigned __int64 sqlite_uint64;
73917 #else
73918   typedef long long int sqlite_int64;
73919   typedef unsigned long long int sqlite_uint64;
73920 #endif
73921 typedef sqlite_int64 sqlite3_int64;
73922 typedef sqlite_uint64 sqlite3_uint64;
73923
73924 /*
73925 ** If compiling for a processor that lacks floating point support,
73926 ** substitute integer for floating-point
73927 */
73928 #ifdef SQLITE_OMIT_FLOATING_POINT
73929 # define double sqlite3_int64
73930 #endif
73931
73932 /*
73933 ** CAPI3REF: Closing A Database Connection {F12010}
73934 **
73935 ** {F12011} The sqlite3_close() interfaces destroys an [sqlite3] object
73936 ** allocated by a prior call to [sqlite3_open()], [sqlite3_open16()], or
73937 ** [sqlite3_open_v2()]. {F12012} Sqlite3_close() releases all
73938 ** memory used by the connection and closes all open files. {END}.
73939 **
73940 ** {F12013} If the database connection contains
73941 ** [sqlite3_stmt | prepared statements] that have not been finalized
73942 ** by [sqlite3_finalize()], then sqlite3_close() returns SQLITE_BUSY
73943 ** and leaves the connection open.  {F12014} Giving sqlite3_close()
73944 ** a NULL pointer is a harmless no-op. {END}
73945 **
73946 ** {U12015} Passing this routine a database connection that has already been
73947 ** closed results in undefined behavior. {U12016} If other interfaces that
73948 ** reference the same database connection are pending (either in the
73949 ** same thread or in different threads) when this routine is called,
73950 ** then the behavior is undefined and is almost certainly undesirable.
73951 */
73952 int sqlite3_close(sqlite3 *);
73953
73954 /*
73955 ** The type for a callback function.
73956 ** This is legacy and deprecated.  It is included for historical
73957 ** compatibility and is not documented.
73958 */
73959 typedef int (*sqlite3_callback)(void*,int,char**, char**);
73960
73961 /*
73962 ** CAPI3REF: One-Step Query Execution Interface {F12100}
73963 **
73964 ** {F12101} The sqlite3_exec() interface evaluates zero or more 
73965 ** UTF-8 encoded, semicolon-separated SQL statements in the zero-terminated
73966 ** string of its second argument.  {F12102} The SQL
73967 ** statements are evaluated in the context of the database connection
73968 ** specified by in the first argument.
73969 ** {F12103} SQL statements are prepared one by one using
73970 ** [sqlite3_prepare()] or the equivalent, evaluated
73971 ** using one or more calls to [sqlite3_step()], then destroyed
73972 ** using [sqlite3_finalize()]. {F12104} The return value of
73973 ** sqlite3_exec() is SQLITE_OK if all SQL statement run
73974 ** successfully.
73975 **
73976 ** {F12105} If one or more of the SQL statements handed to
73977 ** sqlite3_exec() are queries, then
73978 ** the callback function specified by the 3rd parameter is
73979 ** invoked once for each row of the query result. {F12106}
73980 ** If the callback returns a non-zero value then the query
73981 ** is aborted, all subsequent SQL statements
73982 ** are skipped and the sqlite3_exec() function returns the [SQLITE_ABORT].
73983 **
73984 ** {F12107} The 4th parameter to sqlite3_exec() is an arbitrary pointer
73985 ** that is passed through to the callback function as its first parameter.
73986 **
73987 ** {F12108} The 2nd parameter to the callback function is the number of
73988 ** columns in the query result.  {F12109} The 3rd parameter to the callback
73989 ** is an array of pointers to strings holding the values for each column
73990 ** as extracted using [sqlite3_column_text()].  NULL values in the result
73991 ** set result in a NULL pointer.  All other value are in their UTF-8
73992 ** string representation. {F12117}
73993 ** The 4th parameter to the callback is an array of strings
73994 ** obtained using [sqlite3_column_name()] and holding
73995 ** the names of each column, also in UTF-8.
73996 **
73997 ** {F12110} The callback function may be NULL, even for queries.  A NULL
73998 ** callback is not an error.  It just means that no callback
73999 ** will be invoked. 
74000 **
74001 ** {F12112} If an error occurs while parsing or evaluating the SQL
74002 ** then an appropriate error message is written into memory obtained
74003 ** from [sqlite3_malloc()] and *errmsg is made to point to that message
74004 ** assuming errmsg is not NULL.  
74005 ** {U12113} The calling function is responsible for freeing the memory
74006 ** using [sqlite3_free()].
74007 ** {F12116} If [sqlite3_malloc()] fails while attempting to generate
74008 ** the error message, *errmsg is set to NULL.
74009 ** {F12114} If errmsg is NULL then no attempt is made to generate an
74010 ** error message. <todo>Is the return code SQLITE_NOMEM or the original
74011 ** error code?</todo> <todo>What happens if there are multiple errors?
74012 ** Do we get code for the first error, or is the choice of reported
74013 ** error arbitrary?</todo>
74014 **
74015 ** {F12115} The return value is is SQLITE_OK if there are no errors and
74016 ** some other [SQLITE_OK | return code] if there is an error.  
74017 ** The particular return value depends on the type of error.  {END}
74018 */
74019 int sqlite3_exec(
74020   sqlite3*,                                  /* An open database */
74021   const char *sql,                           /* SQL to be evaluted */
74022   int (*callback)(void*,int,char**,char**),  /* Callback function */
74023   void *,                                    /* 1st argument to callback */
74024   char **errmsg                              /* Error msg written here */
74025 );
74026
74027 /*
74028 ** CAPI3REF: Result Codes {F10210}
74029 ** KEYWORDS: SQLITE_OK
74030 **
74031 ** Many SQLite functions return an integer result code from the set shown
74032 ** above in order to indicates success or failure.
74033 **
74034 ** {F10211} The result codes shown here are the only ones returned 
74035 ** by SQLite in its default configuration. {F10212} However, the
74036 ** [sqlite3_extended_result_codes()] API can be used to set a database
74037 ** connectoin to return more detailed result codes. {END}
74038 **
74039 ** See also: [SQLITE_IOERR_READ | extended result codes]
74040 **
74041 */
74042 #define SQLITE_OK           0   /* Successful result */
74043 /* beginning-of-error-codes */
74044 #define SQLITE_ERROR        1   /* SQL error or missing database */
74045 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
74046 #define SQLITE_PERM         3   /* Access permission denied */
74047 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
74048 #define SQLITE_BUSY         5   /* The database file is locked */
74049 #define SQLITE_LOCKED       6   /* A table in the database is locked */
74050 #define SQLITE_NOMEM        7   /* A malloc() failed */
74051 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
74052 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
74053 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
74054 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
74055 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
74056 #define SQLITE_FULL        13   /* Insertion failed because database is full */
74057 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
74058 #define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
74059 #define SQLITE_EMPTY       16   /* Database is empty */
74060 #define SQLITE_SCHEMA      17   /* The database schema changed */
74061 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
74062 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
74063 #define SQLITE_MISMATCH    20   /* Data type mismatch */
74064 #define SQLITE_MISUSE      21   /* Library used incorrectly */
74065 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
74066 #define SQLITE_AUTH        23   /* Authorization denied */
74067 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
74068 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
74069 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
74070 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
74071 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
74072 /* end-of-error-codes */
74073
74074 /*
74075 ** CAPI3REF: Extended Result Codes {F10220}
74076 **
74077 ** In its default configuration, SQLite API routines return one of 26 integer
74078 ** [SQLITE_OK | result codes].  However, experience has shown that
74079 ** many of these result codes are too course-grained.  They do not provide as
74080 ** much information about problems as programmers might like.  In an effort to
74081 ** address this, newer versions of SQLite (version 3.3.8 and later) include
74082 ** support for additional result codes that provide more detailed information
74083 ** about errors. {F10221} The extended result codes are enabled or disabled
74084 ** for each database connection using the [sqlite3_extended_result_codes()]
74085 ** API. {END}
74086 ** 
74087 ** Some of the available extended result codes are listed above.
74088 ** We expect the number of extended result codes will be expand
74089 ** over time.  {U10422} Software that uses extended result codes should expect
74090 ** to see new result codes in future releases of SQLite. {END}
74091 ** 
74092 ** {F10223} The symbolic name for an extended result code always contains
74093 ** a related primary result code as a prefix. {F10224} Primary result
74094 ** codes contain a single "_" character.  {F10225} Extended result codes
74095 ** contain two or more "_" characters. {F10226} The numeric value of an
74096 ** extended result code can be converted to its
74097 ** corresponding primary result code by masking off the lower 8 bytes. {END}
74098 **
74099 ** The SQLITE_OK result code will never be extended.  It will always
74100 ** be exactly zero.
74101 */
74102 #define SQLITE_IOERR_READ          (SQLITE_IOERR | (1<<8))
74103 #define SQLITE_IOERR_SHORT_READ    (SQLITE_IOERR | (2<<8))
74104 #define SQLITE_IOERR_WRITE         (SQLITE_IOERR | (3<<8))
74105 #define SQLITE_IOERR_FSYNC         (SQLITE_IOERR | (4<<8))
74106 #define SQLITE_IOERR_DIR_FSYNC     (SQLITE_IOERR | (5<<8))
74107 #define SQLITE_IOERR_TRUNCATE      (SQLITE_IOERR | (6<<8))
74108 #define SQLITE_IOERR_FSTAT         (SQLITE_IOERR | (7<<8))
74109 #define SQLITE_IOERR_UNLOCK        (SQLITE_IOERR | (8<<8))
74110 #define SQLITE_IOERR_RDLOCK        (SQLITE_IOERR | (9<<8))
74111 #define SQLITE_IOERR_DELETE        (SQLITE_IOERR | (10<<8))
74112 #define SQLITE_IOERR_BLOCKED       (SQLITE_IOERR | (11<<8))
74113 #define SQLITE_IOERR_NOMEM         (SQLITE_IOERR | (12<<8))
74114
74115 /*
74116 ** CAPI3REF: Flags For File Open Operations {F10230}
74117 **
74118 ** {F10231} Some combination of the these bit values are used as the
74119 ** third argument to the [sqlite3_open_v2()] interface and
74120 ** as fourth argument to the xOpen method of the
74121 ** [sqlite3_vfs] object.
74122 */
74123 #define SQLITE_OPEN_READONLY         0x00000001
74124 #define SQLITE_OPEN_READWRITE        0x00000002
74125 #define SQLITE_OPEN_CREATE           0x00000004
74126 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008
74127 #define SQLITE_OPEN_EXCLUSIVE        0x00000010
74128 #define SQLITE_OPEN_MAIN_DB          0x00000100
74129 #define SQLITE_OPEN_TEMP_DB          0x00000200
74130 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400
74131 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800
74132 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000
74133 #define SQLITE_OPEN_SUBJOURNAL       0x00002000
74134 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000
74135
74136 /*
74137 ** CAPI3REF: Device Characteristics {F10240}
74138 **
74139 ** {F10241} The xDeviceCapabilities method of the [sqlite3_io_methods]
74140 ** object returns an integer which is a vector of the these
74141 ** bit values expressing I/O characteristics of the mass storage
74142 ** device that holds the file that the [sqlite3_io_methods]
74143 ** refers to. {END}
74144 **
74145 ** {F10242} The SQLITE_IOCAP_ATOMIC property means that all writes of
74146 ** any size are atomic.  {F10243} The SQLITE_IOCAP_ATOMICnnn values
74147 ** mean that writes of blocks that are nnn bytes in size and
74148 ** are aligned to an address which is an integer multiple of
74149 ** nnn are atomic.  {F10244} The SQLITE_IOCAP_SAFE_APPEND value means
74150 ** that when data is appended to a file, the data is appended
74151 ** first then the size of the file is extended, never the other
74152 ** way around.  {F10245} The SQLITE_IOCAP_SEQUENTIAL property means that
74153 ** information is written to disk in the same order as calls
74154 ** to xWrite().
74155 */
74156 #define SQLITE_IOCAP_ATOMIC          0x00000001
74157 #define SQLITE_IOCAP_ATOMIC512       0x00000002
74158 #define SQLITE_IOCAP_ATOMIC1K        0x00000004
74159 #define SQLITE_IOCAP_ATOMIC2K        0x00000008
74160 #define SQLITE_IOCAP_ATOMIC4K        0x00000010
74161 #define SQLITE_IOCAP_ATOMIC8K        0x00000020
74162 #define SQLITE_IOCAP_ATOMIC16K       0x00000040
74163 #define SQLITE_IOCAP_ATOMIC32K       0x00000080
74164 #define SQLITE_IOCAP_ATOMIC64K       0x00000100
74165 #define SQLITE_IOCAP_SAFE_APPEND     0x00000200
74166 #define SQLITE_IOCAP_SEQUENTIAL      0x00000400
74167
74168 /*
74169 ** CAPI3REF: File Locking Levels {F10250}
74170 **
74171 ** {F10251} SQLite uses one of the following integer values as the second
74172 ** argument to calls it makes to the xLock() and xUnlock() methods
74173 ** of an [sqlite3_io_methods] object. {END}
74174 */
74175 #define SQLITE_LOCK_NONE          0
74176 #define SQLITE_LOCK_SHARED        1
74177 #define SQLITE_LOCK_RESERVED      2
74178 #define SQLITE_LOCK_PENDING       3
74179 #define SQLITE_LOCK_EXCLUSIVE     4
74180
74181 /*
74182 ** CAPI3REF: Synchronization Type Flags {F10260}
74183 **
74184 ** {F10261} When SQLite invokes the xSync() method of an
74185 ** [sqlite3_io_methods] object it uses a combination of the
74186 ** these integer values as the second argument.
74187 **
74188 ** {F10262} When the SQLITE_SYNC_DATAONLY flag is used, it means that the
74189 ** sync operation only needs to flush data to mass storage.  Inode
74190 ** information need not be flushed. {F10263} The SQLITE_SYNC_NORMAL means 
74191 ** to use normal fsync() semantics. {F10264} The SQLITE_SYNC_FULL flag means 
74192 ** to use Mac OS-X style fullsync instead of fsync().
74193 */
74194 #define SQLITE_SYNC_NORMAL        0x00002
74195 #define SQLITE_SYNC_FULL          0x00003
74196 #define SQLITE_SYNC_DATAONLY      0x00010
74197
74198
74199 /*
74200 ** CAPI3REF: OS Interface Open File Handle {F11110}
74201 **
74202 ** An [sqlite3_file] object represents an open file in the OS
74203 ** interface layer.  Individual OS interface implementations will
74204 ** want to subclass this object by appending additional fields
74205 ** for their own use.  The pMethods entry is a pointer to an
74206 ** [sqlite3_io_methods] object that defines methods for performing
74207 ** I/O operations on the open file.
74208 */
74209 typedef struct sqlite3_file sqlite3_file;
74210 struct sqlite3_file {
74211   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
74212 };
74213
74214 /*
74215 ** CAPI3REF: OS Interface File Virtual Methods Object {F11120}
74216 **
74217 ** Every file opened by the [sqlite3_vfs] xOpen method contains a pointer to
74218 ** an instance of the this object.  This object defines the
74219 ** methods used to perform various operations against the open file.
74220 **
74221 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
74222 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
74223 *  The second choice is an
74224 ** OS-X style fullsync.  The SQLITE_SYNC_DATA flag may be ORed in to
74225 ** indicate that only the data of the file and not its inode needs to be
74226 ** synced.
74227 ** 
74228 ** The integer values to xLock() and xUnlock() are one of
74229 ** <ul>
74230 ** <li> [SQLITE_LOCK_NONE],
74231 ** <li> [SQLITE_LOCK_SHARED],
74232 ** <li> [SQLITE_LOCK_RESERVED],
74233 ** <li> [SQLITE_LOCK_PENDING], or
74234 ** <li> [SQLITE_LOCK_EXCLUSIVE].
74235 ** </ul>
74236 ** xLock() increases the lock. xUnlock() decreases the lock.  
74237 ** The xCheckReservedLock() method looks
74238 ** to see if any database connection, either in this
74239 ** process or in some other process, is holding an RESERVED,
74240 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
74241 ** if such a lock exists and false if not.
74242 ** 
74243 ** The xFileControl() method is a generic interface that allows custom
74244 ** VFS implementations to directly control an open file using the
74245 ** [sqlite3_file_control()] interface.  The second "op" argument
74246 ** is an integer opcode.   The third
74247 ** argument is a generic pointer which is intended to be a pointer
74248 ** to a structure that may contain arguments or space in which to
74249 ** write return values.  Potential uses for xFileControl() might be
74250 ** functions to enable blocking locks with timeouts, to change the
74251 ** locking strategy (for example to use dot-file locks), to inquire
74252 ** about the status of a lock, or to break stale locks.  The SQLite
74253 ** core reserves opcodes less than 100 for its own use. 
74254 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
74255 ** Applications that define a custom xFileControl method should use opcodes 
74256 ** greater than 100 to avoid conflicts.
74257 **
74258 ** The xSectorSize() method returns the sector size of the
74259 ** device that underlies the file.  The sector size is the
74260 ** minimum write that can be performed without disturbing
74261 ** other bytes in the file.  The xDeviceCharacteristics()
74262 ** method returns a bit vector describing behaviors of the
74263 ** underlying device:
74264 **
74265 ** <ul>
74266 ** <li> [SQLITE_IOCAP_ATOMIC]
74267 ** <li> [SQLITE_IOCAP_ATOMIC512]
74268 ** <li> [SQLITE_IOCAP_ATOMIC1K]
74269 ** <li> [SQLITE_IOCAP_ATOMIC2K]
74270 ** <li> [SQLITE_IOCAP_ATOMIC4K]
74271 ** <li> [SQLITE_IOCAP_ATOMIC8K]
74272 ** <li> [SQLITE_IOCAP_ATOMIC16K]
74273 ** <li> [SQLITE_IOCAP_ATOMIC32K]
74274 ** <li> [SQLITE_IOCAP_ATOMIC64K]
74275 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
74276 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
74277 ** </ul>
74278 **
74279 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
74280 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
74281 ** mean that writes of blocks that are nnn bytes in size and
74282 ** are aligned to an address which is an integer multiple of
74283 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
74284 ** that when data is appended to a file, the data is appended
74285 ** first then the size of the file is extended, never the other
74286 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
74287 ** information is written to disk in the same order as calls
74288 ** to xWrite().
74289 */
74290 typedef struct sqlite3_io_methods sqlite3_io_methods;
74291 struct sqlite3_io_methods {
74292   int iVersion;
74293   int (*xClose)(sqlite3_file*);
74294   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
74295   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
74296   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
74297   int (*xSync)(sqlite3_file*, int flags);
74298   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
74299   int (*xLock)(sqlite3_file*, int);
74300   int (*xUnlock)(sqlite3_file*, int);
74301   int (*xCheckReservedLock)(sqlite3_file*);
74302   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
74303   int (*xSectorSize)(sqlite3_file*);
74304   int (*xDeviceCharacteristics)(sqlite3_file*);
74305   /* Additional methods may be added in future releases */
74306 };
74307
74308 /*
74309 ** CAPI3REF: Standard File Control Opcodes {F11310}
74310 **
74311 ** These integer constants are opcodes for the xFileControl method
74312 ** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()]
74313 ** interface.
74314 **
74315 ** {F11311} The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
74316 ** opcode cases the xFileControl method to write the current state of
74317 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
74318 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
74319 ** into an integer that the pArg argument points to. {F11312} This capability
74320 ** is used during testing and only needs to be supported when SQLITE_TEST
74321 ** is defined.
74322 */
74323 #define SQLITE_FCNTL_LOCKSTATE        1
74324
74325 /*
74326 ** CAPI3REF: Mutex Handle {F17110}
74327 **
74328 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
74329 ** abstract type for a mutex object.  {F17111} The SQLite core never looks
74330 ** at the internal representation of an [sqlite3_mutex]. {END} It only
74331 ** deals with pointers to the [sqlite3_mutex] object.
74332 **
74333 ** Mutexes are created using [sqlite3_mutex_alloc()].
74334 */
74335 typedef struct sqlite3_mutex sqlite3_mutex;
74336
74337 /*
74338 ** CAPI3REF: OS Interface Object {F11140}
74339 **
74340 ** An instance of this object defines the interface between the
74341 ** SQLite core and the underlying operating system.  The "vfs"
74342 ** in the name of the object stands for "virtual file system".
74343 **
74344 ** The iVersion field is initially 1 but may be larger for future
74345 ** versions of SQLite.  Additional fields may be appended to this
74346 ** object when the iVersion value is increased.
74347 **
74348 ** The szOsFile field is the size of the subclassed [sqlite3_file]
74349 ** structure used by this VFS.  mxPathname is the maximum length of
74350 ** a pathname in this VFS.
74351 **
74352 ** Registered vfs modules are kept on a linked list formed by
74353 ** the pNext pointer.  The [sqlite3_vfs_register()]
74354 ** and [sqlite3_vfs_unregister()] interfaces manage this list
74355 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
74356 ** searches the list.
74357 **
74358 ** The pNext field is the only fields in the sqlite3_vfs 
74359 ** structure that SQLite will ever modify.  SQLite will only access
74360 ** or modify this field while holding a particular static mutex.
74361 ** The application should never modify anything within the sqlite3_vfs
74362 ** object once the object has been registered.
74363 **
74364 ** The zName field holds the name of the VFS module.  The name must
74365 ** be unique across all VFS modules.
74366 **
74367 ** {F11141} SQLite will guarantee that the zFilename string passed to
74368 ** xOpen() is a full pathname as generated by xFullPathname() and
74369 ** that the string will be valid and unchanged until xClose() is
74370 ** called.  {END} So the [sqlite3_file] can store a pointer to the
74371 ** filename if it needs to remember the filename for some reason.
74372 **
74373 ** {F11142} The flags argument to xOpen() includes all bits set in
74374 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
74375 ** or [sqlite3_open16()] is used, then flags includes at least
74376 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END}
74377 ** If xOpen() opens a file read-only then it sets *pOutFlags to
74378 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be
74379 ** set.
74380 ** 
74381 ** {F11143} SQLite will also add one of the following flags to the xOpen()
74382 ** call, depending on the object being opened:
74383 ** 
74384 ** <ul>
74385 ** <li>  [SQLITE_OPEN_MAIN_DB]
74386 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
74387 ** <li>  [SQLITE_OPEN_TEMP_DB]
74388 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
74389 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
74390 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
74391 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
74392 ** </ul> {END}
74393 **
74394 ** The file I/O implementation can use the object type flags to
74395 ** changes the way it deals with files.  For example, an application
74396 ** that does not care about crash recovery or rollback, might make
74397 ** the open of a journal file a no-op.  Writes to this journal are
74398 ** also a no-op.  Any attempt to read the journal return SQLITE_IOERR.
74399 ** Or the implementation might recognize the a database file will
74400 ** be doing page-aligned sector reads and writes in a random order
74401 ** and set up its I/O subsystem accordingly.
74402 ** 
74403 ** {F11144} SQLite might also add one of the following flags to the xOpen
74404 ** method:
74405 ** 
74406 ** <ul>
74407 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
74408 ** <li> [SQLITE_OPEN_EXCLUSIVE]
74409 ** </ul>
74410 ** 
74411 ** {F11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
74412 ** deleted when it is closed.  {F11146} The [SQLITE_OPEN_DELETEONCLOSE]
74413 ** will be set for TEMP  databases, journals and for subjournals. 
74414 ** {F11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened
74415 ** for exclusive access.  This flag is set for all files except
74416 ** for the main database file. {END}
74417 ** 
74418 ** {F11148} At least szOsFile bytes of memory is allocated by SQLite 
74419 ** to hold the  [sqlite3_file] structure passed as the third 
74420 ** argument to xOpen.  {END}  The xOpen method does not have to
74421 ** allocate the structure; it should just fill it in.
74422 ** 
74423 ** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] 
74424 ** to test for the existance of a file,
74425 ** or [SQLITE_ACCESS_READWRITE] to test to see
74426 ** if a file is readable and writable, or [SQLITE_ACCESS_READ]
74427 ** to test to see if a file is at least readable.  {END} The file can be a 
74428 ** directory.
74429 ** 
74430 ** {F11150} SQLite will always allocate at least mxPathname+1 byte for
74431 ** the output buffers for xGetTempname and xFullPathname. {F11151} The exact
74432 ** size of the output buffer is also passed as a parameter to both 
74433 ** methods. {END} If the output buffer is not large enough, SQLITE_CANTOPEN
74434 ** should be returned. As this is handled as a fatal error by SQLite,
74435 ** vfs implementations should endeavor to prevent this by setting 
74436 ** mxPathname to a sufficiently large value.
74437 ** 
74438 ** The xRandomness(), xSleep(), and xCurrentTime() interfaces
74439 ** are not strictly a part of the filesystem, but they are
74440 ** included in the VFS structure for completeness.
74441 ** The xRandomness() function attempts to return nBytes bytes
74442 ** of good-quality randomness into zOut.  The return value is
74443 ** the actual number of bytes of randomness obtained.  The
74444 ** xSleep() method cause the calling thread to sleep for at
74445 ** least the number of microseconds given.  The xCurrentTime()
74446 ** method returns a Julian Day Number for the current date and
74447 ** time.
74448 */
74449 typedef struct sqlite3_vfs sqlite3_vfs;
74450 struct sqlite3_vfs {
74451   int iVersion;            /* Structure version number */
74452   int szOsFile;            /* Size of subclassed sqlite3_file */
74453   int mxPathname;          /* Maximum file pathname length */
74454   sqlite3_vfs *pNext;      /* Next registered VFS */
74455   const char *zName;       /* Name of this virtual file system */
74456   void *pAppData;          /* Pointer to application-specific data */
74457   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
74458                int flags, int *pOutFlags);
74459   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
74460   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags);
74461   int (*xGetTempname)(sqlite3_vfs*, int nOut, char *zOut);
74462   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
74463   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
74464   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
74465   void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol);
74466   void (*xDlClose)(sqlite3_vfs*, void*);
74467   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
74468   int (*xSleep)(sqlite3_vfs*, int microseconds);
74469   int (*xCurrentTime)(sqlite3_vfs*, double*);
74470   /* New fields may be appended in figure versions.  The iVersion
74471   ** value will increment whenever this happens. */
74472 };
74473
74474 /*
74475 ** CAPI3REF: Flags for the xAccess VFS method {F11190}
74476 **
74477 ** {F11191} These integer constants can be used as the third parameter to
74478 ** the xAccess method of an [sqlite3_vfs] object. {END}  They determine
74479 ** the kind of what kind of permissions the xAccess method is
74480 ** looking for.  {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method
74481 ** simply checks to see if the file exists. {F11193} With
74482 ** SQLITE_ACCESS_READWRITE, the xAccess method checks to see
74483 ** if the file is both readable and writable.  {F11194} With
74484 ** SQLITE_ACCESS_READ the xAccess method
74485 ** checks to see if the file is readable.
74486 */
74487 #define SQLITE_ACCESS_EXISTS    0
74488 #define SQLITE_ACCESS_READWRITE 1
74489 #define SQLITE_ACCESS_READ      2
74490
74491 /*
74492 ** CAPI3REF: Enable Or Disable Extended Result Codes {F12200}
74493 **
74494 ** {F12201} The sqlite3_extended_result_codes() routine enables or disables the
74495 ** [SQLITE_IOERR_READ | extended result codes] feature on a database
74496 ** connection if its 2nd parameter is
74497 ** non-zero or zero, respectively. {F12202}
74498 ** By default, SQLite API routines return one of only 26 integer
74499 ** [SQLITE_OK | result codes].  {F12203} When extended result codes
74500 ** are enabled by this routine, the repetoire of result codes can be
74501 ** much larger and can (hopefully) provide more detailed information
74502 ** about the cause of an error.
74503 **
74504 ** {F12204} The second argument is a boolean value that turns extended result
74505 ** codes on and off. {F12205} Extended result codes are off by default for
74506 ** backwards compatibility with older versions of SQLite.
74507 */
74508 int sqlite3_extended_result_codes(sqlite3*, int onoff);
74509
74510 /*
74511 ** CAPI3REF: Last Insert Rowid {F12220}
74512 **
74513 ** {F12221} Each entry in an SQLite table has a unique 64-bit signed
74514 ** integer key called the "rowid".  {F12222} The rowid is always available
74515 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
74516 ** names are not also used by explicitly declared columns. {F12223} If
74517 ** the table has a column of type INTEGER PRIMARY KEY then that column
74518 ** is another an alias for the rowid.
74519 **
74520 ** {F12224} This routine returns the rowid of the most recent
74521 ** successful INSERT into the database from the database connection
74522 ** shown in the first argument.  {F12225} If no successful inserts
74523 ** have ever occurred on this database connection, zero is returned.
74524 **
74525 ** {F12226} If an INSERT occurs within a trigger, then the rowid of the
74526 ** inserted row is returned by this routine as long as the trigger
74527 ** is running.  {F12227} But once the trigger terminates, the value returned
74528 ** by this routine reverts to the last value inserted before the
74529 ** trigger fired.
74530 **
74531 ** {F12228} An INSERT that fails due to a constraint violation is not a
74532 ** successful insert and does not change the value returned by this
74533 ** routine.  {F12229} Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
74534 ** and INSERT OR ABORT make no changes to the return value of this
74535 ** routine when their insertion fails.  {F12231} When INSERT OR REPLACE 
74536 ** encounters a constraint violation, it does not fail.  The
74537 ** INSERT continues to completion after deleting rows that caused
74538 ** the constraint problem so INSERT OR REPLACE will always change
74539 ** the return value of this interface. 
74540 **
74541 ** {UF12232} If another thread does a new insert on the same database connection
74542 ** while this routine is running and thus changes the last insert rowid,
74543 ** then the return value of this routine is undefined.
74544 */
74545 sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
74546
74547 /*
74548 ** CAPI3REF: Count The Number Of Rows Modified {F12240}
74549 **
74550 ** {F12241} This function returns the number of database rows that were changed
74551 ** or inserted or deleted by the most recently completed SQL statement
74552 ** on the connection specified by the first parameter. {F12242} Only
74553 ** changes that are directly specified by the INSERT, UPDATE, or
74554 ** DELETE statement are counted.  Auxiliary changes caused by
74555 ** triggers are not counted. {F12243} Use the [sqlite3_total_changes()] function
74556 ** to find the total number of changes including changes caused by triggers.
74557 **
74558 ** {F12244} Within the body of a trigger, the sqlite3_changes() interface
74559 ** can be called to find the number of
74560 ** changes in the most recently completed INSERT, UPDATE, or DELETE
74561 ** statement within the body of the same trigger.
74562 **
74563 ** {F12245} All changes are counted, even if they are later undone by a
74564 ** ROLLBACK or ABORT.  {F12246} Except, changes associated with creating and
74565 ** dropping tables are not counted.
74566 **
74567 ** {F12247} If a callback invokes [sqlite3_exec()] or [sqlite3_step()]
74568 ** recursively, then the changes in the inner, recursive call are
74569 ** counted together with the changes in the outer call.
74570 **
74571 ** {F12248} SQLite implements the command "DELETE FROM table" without
74572 ** a WHERE clause by dropping and recreating the table.  (This is much
74573 ** faster than going through and deleting individual elements from the
74574 ** table.)  Because of this optimization, the change count for 
74575 ** "DELETE FROM table" will be zero regardless of the number of elements
74576 ** that were originally in the table. {F12251} To get an accurate count
74577 ** of the number of rows deleted, use
74578 ** "DELETE FROM table WHERE 1" instead.
74579 **
74580 ** {UF12252} If another thread makes changes on the same database connection
74581 ** while this routine is running then the return value of this routine
74582 ** is undefined.
74583 */
74584 int sqlite3_changes(sqlite3*);
74585
74586 /*
74587 ** CAPI3REF: Total Number Of Rows Modified {F12260}
74588 ***
74589 ** {F12261} This function returns the number of database rows that have been
74590 ** modified by INSERT, UPDATE or DELETE statements since the database handle
74591 ** was opened. {F12262} The count includes UPDATE, INSERT and DELETE 
74592 ** statements executed as part of trigger programs.  {F12263} All changes
74593 ** are counted as soon as the statement that makes them is completed 
74594 ** (when the statement handle is passed to [sqlite3_reset()] or 
74595 ** [sqlite3_finalize()]). {END}
74596 **
74597 ** See also the [sqlite3_change()] interface.
74598 **
74599 ** {F12265} SQLite implements the command "DELETE FROM table" without
74600 ** a WHERE clause by dropping and recreating the table.  (This is much
74601 ** faster than going
74602 ** through and deleting individual elements form the table.)  Because of
74603 ** this optimization, the change count for "DELETE FROM table" will be
74604 ** zero regardless of the number of elements that were originally in the
74605 ** table. To get an accurate count of the number of rows deleted, use
74606 ** "DELETE FROM table WHERE 1" instead.
74607 **
74608 ** {U12264} If another thread makes changes on the same database connection
74609 ** while this routine is running then the return value of this routine
74610 ** is undefined. {END}
74611 */
74612 int sqlite3_total_changes(sqlite3*);
74613
74614 /*
74615 ** CAPI3REF: Interrupt A Long-Running Query {F12270}
74616 **
74617 ** {F12271} This function causes any pending database operation to abort and
74618 ** return at its earliest opportunity. {END} This routine is typically
74619 ** called in response to a user action such as pressing "Cancel"
74620 ** or Ctrl-C where the user wants a long query operation to halt
74621 ** immediately.
74622 **
74623 ** {F12272} It is safe to call this routine from a thread different from the
74624 ** thread that is currently running the database operation. {U12273} But it
74625 ** is not safe to call this routine with a database connection that
74626 ** is closed or might close before sqlite3_interrupt() returns.
74627 **
74628 ** If an SQL is very nearly finished at the time when sqlite3_interrupt()
74629 ** is called, then it might not have an opportunity to be interrupted.
74630 ** It might continue to completion.
74631 ** {F12274} The SQL operation that is interrupted will return
74632 ** [SQLITE_INTERRUPT].  {F12275} If the interrupted SQL operation is an
74633 ** INSERT, UPDATE, or DELETE that is inside an explicit transaction, 
74634 ** then the entire transaction will be rolled back automatically.
74635 ** {F12276} A call to sqlite3_interrupt() has no effect on SQL statements
74636 ** that are started after sqlite3_interrupt() returns.
74637 */
74638 void sqlite3_interrupt(sqlite3*);
74639
74640 /*
74641 ** CAPI3REF: Determine If An SQL Statement Is Complete {F10510}
74642 **
74643 ** These routines are useful for command-line input to determine if the
74644 ** currently entered text seems to form complete a SQL statement or
74645 ** if additional input is needed before sending the text into
74646 ** SQLite for parsing.  These routines return true if the input string
74647 ** appears to be a complete SQL statement.  A statement is judged to be
74648 ** complete if it ends with a semicolon and is not a fragment of a
74649 ** CREATE TRIGGER statement.  These routines do not parse the SQL and
74650 ** so will not detect syntactically incorrect SQL.
74651 **
74652 ** {F10511} These functions return true if the given input string 
74653 ** ends with a semicolon optionally followed by whitespace or
74654 ** comments. {F10512} For sqlite3_complete(),
74655 ** the parameter must be a zero-terminated UTF-8 string. {F10513} For
74656 ** sqlite3_complete16(), a zero-terminated machine byte order UTF-16 string
74657 ** is required.  {F10514} These routines return false if the terminal
74658 ** semicolon is within a comment, a string literal or a quoted identifier
74659 ** (in other words if the final semicolon is not really a separate token
74660 ** but part of a larger token) or if the final semicolon is
74661 ** in between the BEGIN and END keywords of a CREATE TRIGGER statement.
74662 ** {END}
74663 */
74664 int sqlite3_complete(const char *sql);
74665 int sqlite3_complete16(const void *sql);
74666
74667 /*
74668 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310}
74669 **
74670 ** {F12311} This routine identifies a callback function that might be
74671 ** invoked whenever an attempt is made to open a database table 
74672 ** that another thread or process has locked.
74673 ** {F12312} If the busy callback is NULL, then [SQLITE_BUSY]
74674 ** or [SQLITE_IOERR_BLOCKED]
74675 ** is returned immediately upon encountering the lock.
74676 ** {F12313} If the busy callback is not NULL, then the
74677 ** callback will be invoked with two arguments.  {F12314} The
74678 ** first argument to the handler is a copy of the void* pointer which
74679 ** is the third argument to this routine.  {F12315} The second argument to
74680 ** the handler is the number of times that the busy handler has
74681 ** been invoked for this locking event.  {F12316} If the
74682 ** busy callback returns 0, then no additional attempts are made to
74683 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
74684 ** {F12317} If the callback returns non-zero, then another attempt
74685 ** is made to open the database for reading and the cycle repeats.
74686 **
74687 ** The presence of a busy handler does not guarantee that
74688 ** it will be invoked when there is lock contention. {F12319}
74689 ** If SQLite determines that invoking the busy handler could result in
74690 ** a deadlock, it will go ahead and return [SQLITE_BUSY] or
74691 ** [SQLITE_IOERR_BLOCKED] instead of invoking the
74692 ** busy handler. {END}
74693 ** Consider a scenario where one process is holding a read lock that
74694 ** it is trying to promote to a reserved lock and
74695 ** a second process is holding a reserved lock that it is trying
74696 ** to promote to an exclusive lock.  The first process cannot proceed
74697 ** because it is blocked by the second and the second process cannot
74698 ** proceed because it is blocked by the first.  If both processes
74699 ** invoke the busy handlers, neither will make any progress.  Therefore,
74700 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
74701 ** will induce the first process to release its read lock and allow
74702 ** the second process to proceed.
74703 **
74704 ** {F12321} The default busy callback is NULL. {END}
74705 **
74706 ** {F12322} The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
74707 ** when SQLite is in the middle of a large transaction where all the
74708 ** changes will not fit into the in-memory cache.  {F12323} SQLite will
74709 ** already hold a RESERVED lock on the database file, but it needs
74710 ** to promote this lock to EXCLUSIVE so that it can spill cache
74711 ** pages into the database file without harm to concurrent
74712 ** readers.  {F12324} If it is unable to promote the lock, then the in-memory
74713 ** cache will be left in an inconsistent state and so the error
74714 ** code is promoted from the relatively benign [SQLITE_BUSY] to
74715 ** the more severe [SQLITE_IOERR_BLOCKED].  {F12325} This error code promotion
74716 ** forces an automatic rollback of the changes. {END} See the
74717 ** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError">
74718 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
74719 ** this is important.
74720 **      
74721 ** {F12326} Sqlite is re-entrant, so the busy handler may start a new
74722 ** query. {END} (It is not clear why anyone would every want to do this,
74723 ** but it is allowed, in theory.) {U12327} But the busy handler may not
74724 ** close the database.  Closing the database from a busy handler will delete 
74725 ** data structures out from under the executing query and will 
74726 ** probably result in a segmentation fault or other runtime error. {END}
74727 **
74728 ** {F12328} There can only be a single busy handler defined for each database
74729 ** connection.  Setting a new busy handler clears any previous one. 
74730 ** {F12329} Note that calling [sqlite3_busy_timeout()] will also set or clear
74731 ** the busy handler.
74732 **
74733 ** {F12331} When operating in [sqlite3_enable_shared_cache | shared cache mode],
74734 ** only a single busy handler can be defined for each database file.
74735 ** So if two database connections share a single cache, then changing
74736 ** the busy handler on one connection will also change the busy
74737 ** handler in the other connection.  {F12332} The busy handler is invoked
74738 ** in the thread that was running when the lock contention occurs.
74739 */
74740 int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
74741
74742 /*
74743 ** CAPI3REF: Set A Busy Timeout {F12340}
74744 **
74745 ** {F12341} This routine sets a [sqlite3_busy_handler | busy handler]
74746 ** that sleeps for a while when a
74747 ** table is locked.  {F12342} The handler will sleep multiple times until 
74748 ** at least "ms" milliseconds of sleeping have been done. {F12343} After
74749 ** "ms" milliseconds of sleeping, the handler returns 0 which
74750 ** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
74751 **
74752 ** {F12344} Calling this routine with an argument less than or equal to zero
74753 ** turns off all busy handlers.
74754 **
74755 ** {F12345} There can only be a single busy handler for a particular database
74756 ** connection.  If another busy handler was defined  
74757 ** (using [sqlite3_busy_handler()]) prior to calling
74758 ** this routine, that other busy handler is cleared.
74759 */
74760 int sqlite3_busy_timeout(sqlite3*, int ms);
74761
74762 /*
74763 ** CAPI3REF: Convenience Routines For Running Queries {F12370}
74764 **
74765 ** This next routine is a convenience wrapper around [sqlite3_exec()].
74766 ** {F12371} Instead of invoking a user-supplied callback for each row of the
74767 ** result, this routine remembers each row of the result in memory
74768 ** obtained from [sqlite3_malloc()], then returns all of the result after the
74769 ** query has finished. {F12372}
74770 **
74771 ** As an example, suppose the query result where this table:
74772 **
74773 ** <blockquote><pre>
74774 **        Name        | Age
74775 **        -----------------------
74776 **        Alice       | 43
74777 **        Bob         | 28
74778 **        Cindy       | 21
74779 ** </pre></blockquote>
74780 **
74781 ** If the 3rd argument were &azResult then after the function returns
74782 ** azResult will contain the following data:
74783 **
74784 ** <blockquote><pre>
74785 **        azResult&#91;0] = "Name";
74786 **        azResult&#91;1] = "Age";
74787 **        azResult&#91;2] = "Alice";
74788 **        azResult&#91;3] = "43";
74789 **        azResult&#91;4] = "Bob";
74790 **        azResult&#91;5] = "28";
74791 **        azResult&#91;6] = "Cindy";
74792 **        azResult&#91;7] = "21";
74793 ** </pre></blockquote>
74794 **
74795 ** Notice that there is an extra row of data containing the column
74796 ** headers.  But the *nrow return value is still 3.  *ncolumn is
74797 ** set to 2.  In general, the number of values inserted into azResult
74798 ** will be ((*nrow) + 1)*(*ncolumn).
74799 **
74800 ** {U12374} After the calling function has finished using the result, it should 
74801 ** pass the result data pointer to sqlite3_free_table() in order to 
74802 ** release the memory that was malloc-ed.  Because of the way the 
74803 ** [sqlite3_malloc()] happens, the calling function must not try to call 
74804 ** [sqlite3_free()] directly.  Only [sqlite3_free_table()] is able to release 
74805 ** the memory properly and safely. {END}
74806 **
74807 ** {F12373} The return value of this routine is the same as
74808 ** from [sqlite3_exec()].
74809 */
74810 int sqlite3_get_table(
74811   sqlite3*,              /* An open database */
74812   const char *sql,       /* SQL to be executed */
74813   char ***resultp,       /* Result written to a char *[]  that this points to */
74814   int *nrow,             /* Number of result rows written here */
74815   int *ncolumn,          /* Number of result columns written here */
74816   char **errmsg          /* Error msg written here */
74817 );
74818 void sqlite3_free_table(char **result);
74819
74820 /*
74821 ** CAPI3REF: Formatted String Printing Functions {F17400}
74822 **
74823 ** These routines are workalikes of the "printf()" family of functions
74824 ** from the standard C library.
74825 **
74826 ** {F17401} The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
74827 ** results into memory obtained from [sqlite3_malloc()].
74828 ** {U17402} The strings returned by these two routines should be
74829 ** released by [sqlite3_free()]. {F17403}  Both routines return a
74830 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
74831 ** memory to hold the resulting string.
74832 **
74833 ** {F17404} In sqlite3_snprintf() routine is similar to "snprintf()" from
74834 ** the standard C library.  The result is written into the
74835 ** buffer supplied as the second parameter whose size is given by
74836 ** the first parameter. {END} Note that the order of the
74837 ** first two parameters is reversed from snprintf().  This is an
74838 ** historical accident that cannot be fixed without breaking
74839 ** backwards compatibility.  {F17405} Note also that sqlite3_snprintf()
74840 ** returns a pointer to its buffer instead of the number of
74841 ** characters actually written into the buffer. {END} We admit that
74842 ** the number of characters written would be a more useful return
74843 ** value but we cannot change the implementation of sqlite3_snprintf()
74844 ** now without breaking compatibility.
74845 **
74846 ** {F17406} As long as the buffer size is greater than zero, sqlite3_snprintf()
74847 ** guarantees that the buffer is always zero-terminated. {F17407} The first
74848 ** parameter "n" is the total size of the buffer, including space for
74849 ** the zero terminator.  {END} So the longest string that can be completely
74850 ** written will be n-1 characters.
74851 **
74852 ** These routines all implement some additional formatting
74853 ** options that are useful for constructing SQL statements.
74854 ** All of the usual printf formatting options apply.  In addition, there
74855 ** is are "%q", "%Q", and "%z" options.
74856 **
74857 ** {F17410} The %q option works like %s in that it substitutes a null-terminated
74858 ** string from the argument list.  But %q also doubles every '\'' character.
74859 ** %q is designed for use inside a string literal. {END} By doubling each '\''
74860 ** character it escapes that character and allows it to be inserted into
74861 ** the string.
74862 **
74863 ** For example, so some string variable contains text as follows:
74864 **
74865 ** <blockquote><pre>
74866 **  char *zText = "It's a happy day!";
74867 ** </pre></blockquote>
74868 **
74869 ** One can use this text in an SQL statement as follows:
74870 **
74871 ** <blockquote><pre>
74872 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
74873 **  sqlite3_exec(db, zSQL, 0, 0, 0);
74874 **  sqlite3_free(zSQL);
74875 ** </pre></blockquote>
74876 **
74877 ** Because the %q format string is used, the '\'' character in zText
74878 ** is escaped and the SQL generated is as follows:
74879 **
74880 ** <blockquote><pre>
74881 **  INSERT INTO table1 VALUES('It''s a happy day!')
74882 ** </pre></blockquote>
74883 **
74884 ** This is correct.  Had we used %s instead of %q, the generated SQL
74885 ** would have looked like this:
74886 **
74887 ** <blockquote><pre>
74888 **  INSERT INTO table1 VALUES('It's a happy day!');
74889 ** </pre></blockquote>
74890 **
74891 ** This second example is an SQL syntax error.  As a general rule you
74892 ** should always use %q instead of %s when inserting text into a string 
74893 ** literal.
74894 **
74895 ** {F17411} The %Q option works like %q except it also adds single quotes around
74896 ** the outside of the total string.  Or if the parameter in the argument
74897 ** list is a NULL pointer, %Q substitutes the text "NULL" (without single
74898 ** quotes) in place of the %Q option. {END}  So, for example, one could say:
74899 **
74900 ** <blockquote><pre>
74901 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
74902 **  sqlite3_exec(db, zSQL, 0, 0, 0);
74903 **  sqlite3_free(zSQL);
74904 ** </pre></blockquote>
74905 **
74906 ** The code above will render a correct SQL statement in the zSQL
74907 ** variable even if the zText variable is a NULL pointer.
74908 **
74909 ** {F17412} The "%z" formatting option works exactly like "%s" with the
74910 ** addition that after the string has been read and copied into
74911 ** the result, [sqlite3_free()] is called on the input string. {END}
74912 */
74913 char *sqlite3_mprintf(const char*,...);
74914 char *sqlite3_vmprintf(const char*, va_list);
74915 char *sqlite3_snprintf(int,char*,const char*, ...);
74916
74917 /*
74918 ** CAPI3REF: Memory Allocation Subsystem {F17300}
74919 **
74920 ** {F17301} The SQLite core  uses these three routines for all of its own
74921 ** internal memory allocation needs. {END}  "Core" in the previous sentence
74922 ** does not include operating-system specific VFS implementation.  The
74923 ** windows VFS uses native malloc and free for some operations.
74924 **
74925 ** {F17302} The sqlite3_malloc() routine returns a pointer to a block
74926 ** of memory at least N bytes in length, where N is the parameter.
74927 ** {F17303} If sqlite3_malloc() is unable to obtain sufficient free
74928 ** memory, it returns a NULL pointer.  {F17304} If the parameter N to
74929 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
74930 ** a NULL pointer.
74931 **
74932 ** {F17305} Calling sqlite3_free() with a pointer previously returned
74933 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
74934 ** that it might be reused.  {F17306} The sqlite3_free() routine is
74935 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
74936 ** to sqlite3_free() is harmless.  {U17307} After being freed, memory
74937 ** should neither be read nor written.  Even reading previously freed
74938 ** memory might result in a segmentation fault or other severe error.
74939 ** {U17309} Memory corruption, a segmentation fault, or other severe error
74940 ** might result if sqlite3_free() is called with a non-NULL pointer that
74941 ** was not obtained from sqlite3_malloc() or sqlite3_free().
74942 **
74943 ** {F17310} The sqlite3_realloc() interface attempts to resize a
74944 ** prior memory allocation to be at least N bytes, where N is the
74945 ** second parameter.  The memory allocation to be resized is the first
74946 ** parameter.  {F17311} If the first parameter to sqlite3_realloc()
74947 ** is a NULL pointer then its behavior is identical to calling
74948 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
74949 ** {F17312} If the second parameter to sqlite3_realloc() is zero or
74950 ** negative then the behavior is exactly the same as calling
74951 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
74952 ** {F17313} Sqlite3_realloc() returns a pointer to a memory allocation
74953 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
74954 ** {F17314} If M is the size of the prior allocation, then min(N,M) bytes
74955 ** of the prior allocation are copied into the beginning of buffer returned
74956 ** by sqlite3_realloc() and the prior allocation is freed.
74957 ** {F17315} If sqlite3_realloc() returns NULL, then the prior allocation
74958 ** is not freed.
74959 **
74960 ** {F17316} The memory returned by sqlite3_malloc() and sqlite3_realloc()
74961 ** is always aligned to at least an 8 byte boundary. {END}
74962 **
74963 ** {F17381} The default implementation
74964 ** of the memory allocation subsystem uses the malloc(), realloc()
74965 ** and free() provided by the standard C library. {F17382} However, if 
74966 ** SQLite is compiled with the following C preprocessor macro
74967 **
74968 ** <blockquote> SQLITE_MEMORY_SIZE=<i>NNN</i> </blockquote>
74969 **
74970 ** where <i>NNN</i> is an integer, then SQLite create a static
74971 ** array of at least <i>NNN</i> bytes in size and use that array
74972 ** for all of its dynamic memory allocation needs. {END}  Additional
74973 ** memory allocator options may be added in future releases.
74974 **
74975 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
74976 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
74977 ** implementation of these routines to be omitted.  That capability
74978 ** is no longer provided.  Only built-in memory allocators can be
74979 ** used.
74980 **
74981 ** The windows OS interface layer calls
74982 ** the system malloc() and free() directly when converting
74983 ** filenames between the UTF-8 encoding used by SQLite
74984 ** and whatever filename encoding is used by the particular windows
74985 ** installation.  Memory allocation errors are detected, but
74986 ** they are reported back as [SQLITE_CANTOPEN] or
74987 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
74988 */
74989 void *sqlite3_malloc(int);
74990 void *sqlite3_realloc(void*, int);
74991 void sqlite3_free(void*);
74992
74993 /*
74994 ** CAPI3REF: Memory Allocator Statistics {F17370}
74995 **
74996 ** In addition to the basic three allocation routines 
74997 ** [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()],
74998 ** the memory allocation subsystem included with the SQLite
74999 ** sources provides the interfaces shown here.
75000 **
75001 ** {F17371} The sqlite3_memory_used() routine returns the
75002 ** number of bytes of memory currently outstanding (malloced but not freed).
75003 ** {F17372} The value returned by sqlite3_memory_used() includes
75004 ** any overhead added by SQLite, but not overhead added by the
75005 ** library malloc() that backs the sqlite3_malloc() implementation.
75006 ** {F17373} The sqlite3_memory_highwater() routines returns the
75007 ** maximum number of bytes that have been outstanding at any time
75008 ** since the highwater mark was last reset.
75009 ** {F17374} The byte count returned by sqlite3_memory_highwater()
75010 ** uses the same byte counting rules as sqlite3_memory_used(). {END}
75011 ** In other words, overhead added internally by SQLite is counted,
75012 ** but overhead from the underlying system malloc is not.
75013 ** {F17375} If the parameter to sqlite3_memory_highwater() is true,
75014 ** then the highwater mark is reset to the current value of
75015 ** sqlite3_memory_used() and the prior highwater mark (before the
75016 ** reset) is returned.  {F17376}  If the parameter to 
75017 ** sqlite3_memory_highwater() is zero, then the highwater mark is
75018 ** unchanged.
75019 */
75020 sqlite3_int64 sqlite3_memory_used(void);
75021 sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
75022
75023 /*
75024 ** CAPI3REF: Compile-Time Authorization Callbacks {F12500}
75025 **
75026 ** {F12501} This routine registers a authorizer callback with a particular
75027 ** database connection, supplied in the first argument. {F12502}
75028 ** The authorizer callback is invoked as SQL statements are being compiled
75029 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
75030 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  {F12503} At various
75031 ** points during the compilation process, as logic is being created
75032 ** to perform various actions, the authorizer callback is invoked to
75033 ** see if those actions are allowed.  The authorizer callback should
75034 ** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the
75035 ** specific action but allow the SQL statement to continue to be
75036 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
75037 ** rejected with an error.  {F12504} If the authorizer callback returns
75038 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
75039 ** then [sqlite3_prepare_v2()] or equivalent call that triggered
75040 ** the authorizer shall
75041 ** fail with an SQLITE_ERROR error code and an appropriate error message. {END}
75042 **
75043 ** When the callback returns [SQLITE_OK], that means the operation
75044 ** requested is ok.  {F12505} When the callback returns [SQLITE_DENY], the
75045 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
75046 ** authorizer shall fail
75047 ** with an SQLITE_ERROR error code and an error message explaining that
75048 ** access is denied. {F12506} If the authorizer code (the 2nd parameter
75049 ** to the authorizer callback is anything other than [SQLITE_READ], then
75050 ** a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. 
75051 ** If the authorizer code is [SQLITE_READ] and the callback returns
75052 ** [SQLITE_IGNORE] then the prepared statement is constructed to
75053 ** insert a NULL value in place of the table column that would have
75054 ** been read if [SQLITE_OK] had been returned. {END}
75055 **
75056 ** {F12510} The first parameter to the authorizer callback is a copy of
75057 ** the third parameter to the sqlite3_set_authorizer() interface.
75058 ** {F12511} The second parameter to the callback is an integer 
75059 ** [SQLITE_COPY | action code] that specifies the particular action
75060 ** to be authorized. {END} The available action codes are
75061 ** [SQLITE_COPY | documented separately].  {F12512} The third through sixth
75062 ** parameters to the callback are zero-terminated strings that contain 
75063 ** additional details about the action to be authorized. {END}
75064 **
75065 ** An authorizer is used when preparing SQL statements from an untrusted
75066 ** source, to ensure that the SQL statements do not try to access data
75067 ** that they are not allowed to see, or that they do not try to
75068 ** execute malicious statements that damage the database.  For
75069 ** example, an application may allow a user to enter arbitrary
75070 ** SQL queries for evaluation by a database.  But the application does
75071 ** not want the user to be able to make arbitrary changes to the
75072 ** database.  An authorizer could then be put in place while the
75073 ** user-entered SQL is being prepared that disallows everything
75074 ** except SELECT statements.  
75075 **
75076 ** {F12520} Only a single authorizer can be in place on a database connection
75077 ** at a time.  Each call to sqlite3_set_authorizer overrides the
75078 ** previous call. {F12521}  A NULL authorizer means that no authorization
75079 ** callback is invoked.  {F12522} The default authorizer is NULL. {END}
75080 **
75081 ** Note that the authorizer callback is invoked only during 
75082 ** [sqlite3_prepare()] or its variants.  {F12523} Authorization is not
75083 ** performed during statement evaluation in [sqlite3_step()]. {END}
75084 */
75085 int sqlite3_set_authorizer(
75086   sqlite3*,
75087   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
75088   void *pUserData
75089 );
75090
75091 /*
75092 ** CAPI3REF: Authorizer Return Codes {F12590}
75093 **
75094 ** The [sqlite3_set_authorizer | authorizer callback function] must
75095 ** return either [SQLITE_OK] or one of these two constants in order
75096 ** to signal SQLite whether or not the action is permitted.  See the
75097 ** [sqlite3_set_authorizer | authorizer documentation] for additional
75098 ** information.
75099 */
75100 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
75101 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
75102
75103 /*
75104 ** CAPI3REF: Authorizer Action Codes {F12550}
75105 **
75106 ** The [sqlite3_set_authorizer()] interface registers a callback function
75107 ** that is invoked to authorizer certain SQL statement actions.  {F12551} The
75108 ** second parameter to the callback is an integer code that specifies
75109 ** what action is being authorized.  These are the integer action codes that
75110 ** the authorizer callback may be passed. {END}
75111 **
75112 ** These action code values signify what kind of operation is to be 
75113 ** authorized.  {F12552} The 3rd and 4th parameters to the authorization
75114 ** callback function will be parameters or NULL depending on which of these
75115 ** codes is used as the second parameter. {F12553} The 5th parameter to the
75116 ** authorizer callback is the name of the database ("main", "temp", 
75117 ** etc.) if applicable. {F12554} The 6th parameter to the authorizer callback
75118 ** is the name of the inner-most trigger or view that is responsible for
75119 ** the access attempt or NULL if this access attempt is directly from 
75120 ** top-level SQL code.
75121 */
75122 /******************************************* 3rd ************ 4th ***********/
75123 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
75124 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
75125 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
75126 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
75127 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
75128 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
75129 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
75130 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
75131 #define SQLITE_DELETE                9   /* Table Name      NULL            */
75132 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
75133 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
75134 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
75135 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
75136 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
75137 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
75138 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
75139 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
75140 #define SQLITE_INSERT               18   /* Table Name      NULL            */
75141 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
75142 #define SQLITE_READ                 20   /* Table Name      Column Name     */
75143 #define SQLITE_SELECT               21   /* NULL            NULL            */
75144 #define SQLITE_TRANSACTION          22   /* NULL            NULL            */
75145 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
75146 #define SQLITE_ATTACH               24   /* Filename        NULL            */
75147 #define SQLITE_DETACH               25   /* Database Name   NULL            */
75148 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
75149 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
75150 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
75151 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
75152 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
75153 #define SQLITE_FUNCTION             31   /* Function Name   NULL            */
75154 #define SQLITE_COPY                  0   /* No longer used */
75155
75156 /*
75157 ** CAPI3REF: Tracing And Profiling Functions {F12280}
75158 **
75159 ** These routines register callback functions that can be used for
75160 ** tracing and profiling the execution of SQL statements.
75161 **
75162 ** {F12281} The callback function registered by sqlite3_trace() is invoked
75163 ** at the first [sqlite3_step()] for the evaluation of an SQL statement.
75164 ** {F12282} Only a single trace callback can be registered at a time.
75165 ** Each call to sqlite3_trace() overrides the previous.  {F12283} A
75166 ** NULL callback for sqlite3_trace() disables tracing.  {F12284} The
75167 ** first argument to the trace callback is a copy of the pointer which
75168 ** was the 3rd argument to sqlite3_trace.  {F12285} The second argument
75169 ** to the trace callback is a zero-terminated UTF8 string containing
75170 ** the original text of the SQL statement as it was passed into
75171 ** [sqlite3_prepare_v2()] or the equivalent. {END}  Note that the
75172 ** host parameter are not expanded in the SQL statement text.
75173 **
75174 ** {F12287} The callback function registered by sqlite3_profile() is invoked
75175 ** as each SQL statement finishes.  {F12288} The first parameter to the
75176 ** profile callback is a copy of the 3rd parameter to sqlite3_profile().
75177 ** {F12289} The second parameter to the profile callback is a
75178 ** zero-terminated UTF-8 string that contains the complete text of
75179 ** the SQL statement as it was processed by [sqlite3_prepare_v2()] or
75180 ** the equivalent.  {F12290} The third parameter to the profile 
75181 ** callback is an estimate of the number of nanoseconds of
75182 ** wall-clock time required to run the SQL statement from start
75183 ** to finish. {END}  
75184 **
75185 ** The sqlite3_profile() API is currently considered experimental and
75186 ** is subject to change.
75187 */
75188 void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
75189 void *sqlite3_profile(sqlite3*,
75190    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
75191
75192 /*
75193 ** CAPI3REF: Query Progress Callbacks {F12910}
75194 **
75195 ** {F12911} This routine configures a callback function - the
75196 ** progress callback - that is invoked periodically during long
75197 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
75198 ** [sqlite3_get_table()]. {END}  An example use for this 
75199 ** interface is to keep a GUI updated during a large query.
75200 **
75201 ** {F12912} The progress callback is invoked once for every N virtual
75202 ** machine opcodes, where N is the second argument to this function.
75203 ** {F12913} The progress callback itself is identified by the third
75204 ** argument to this function. {F12914} The fourth argument to this
75205 ** function is a void pointer passed to the progress callback
75206 ** function each time it is invoked. {END}
75207 **
75208 ** {F12915} If a call to [sqlite3_exec()], [sqlite3_step()], or
75209 ** [sqlite3_get_table()] results in fewer than N opcodes being executed,
75210 ** then the progress callback is never invoked. {END}
75211 ** 
75212 ** {F12916} Only a single progress callback function may be registered for each
75213 ** open database connection.  Every call to sqlite3_progress_handler()
75214 ** overwrites the results of the previous call. {F12917}
75215 ** To remove the progress callback altogether, pass NULL as the third
75216 ** argument to this function. {END}
75217 **
75218 ** {F12918} If the progress callback returns a result other than 0, then
75219 ** the current query is immediately terminated and any database changes
75220 ** rolled back. {F12919}
75221 ** The containing [sqlite3_exec()], [sqlite3_step()], or
75222 ** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. {END}  This feature
75223 ** can be used, for example, to implement the "Cancel" button on a
75224 ** progress dialog box in a GUI.
75225 */
75226 void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
75227
75228 /*
75229 ** CAPI3REF: Opening A New Database Connection {F12700}
75230 **
75231 ** {F12701} These routines open an SQLite database file whose name
75232 ** is given by the filename argument.
75233 ** {F12702} The filename argument is interpreted as UTF-8
75234 ** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16
75235 ** in the native byte order for [sqlite3_open16()].
75236 ** {F12703} An [sqlite3*] handle is returned in *ppDb, even
75237 ** if an error occurs.  {F12723} (Exception: if SQLite is unable
75238 ** to allocate memory to hold the [sqlite3] object, a NULL will
75239 ** be written into *ppDb instead of a pointer to the [sqlite3] object.)
75240 ** {F12704} If the database is opened (and/or created)
75241 ** successfully, then [SQLITE_OK] is returned.  {F12705} Otherwise an
75242 ** error code is returned.  {F12706} The
75243 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()]  routines can be used to obtain
75244 ** an English language description of the error.
75245 **
75246 ** {F12707} The default encoding for the database will be UTF-8 if
75247 ** [sqlite3_open()] or [sqlite3_open_v2()] is called and
75248 ** UTF-16 in the native byte order if [sqlite3_open16()] is used.
75249 **
75250 ** {F12708} Whether or not an error occurs when it is opened, resources
75251 ** associated with the [sqlite3*] handle should be released by passing it
75252 ** to [sqlite3_close()] when it is no longer required.
75253 **
75254 ** {F12709} The [sqlite3_open_v2()] interface works like [sqlite3_open()] 
75255 ** except that it acccepts two additional parameters for additional control
75256 ** over the new database connection.  {F12710} The flags parameter can be
75257 ** one of:
75258 **
75259 ** <ol>
75260 ** <li>  [SQLITE_OPEN_READONLY]
75261 ** <li>  [SQLITE_OPEN_READWRITE]
75262 ** <li>  [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
75263 ** </ol>
75264 **
75265 ** {F12711} The first value opens the database read-only. 
75266 ** {F12712} If the database does not previously exist, an error is returned.
75267 ** {F12713} The second option opens
75268 ** the database for reading and writing if possible, or reading only if
75269 ** if the file is write protected.  {F12714} In either case the database
75270 ** must already exist or an error is returned.  {F12715} The third option
75271 ** opens the database for reading and writing and creates it if it does
75272 ** not already exist. {F12716}
75273 ** The third options is behavior that is always used for [sqlite3_open()]
75274 ** and [sqlite3_open16()].
75275 **
75276 ** {F12717} If the filename is ":memory:", then an private
75277 ** in-memory database is created for the connection. {F12718} This in-memory
75278 ** database will vanish when the database connection is closed. {END}  Future
75279 ** version of SQLite might make use of additional special filenames
75280 ** that begin with the ":" character.  It is recommended that 
75281 ** when a database filename really does begin with
75282 ** ":" that you prefix the filename with a pathname like "./" to
75283 ** avoid ambiguity.
75284 **
75285 ** {F12719} If the filename is an empty string, then a private temporary
75286 ** on-disk database will be created.  {F12720} This private database will be
75287 ** automatically deleted as soon as the database connection is closed.
75288 **
75289 ** {F12721} The fourth parameter to sqlite3_open_v2() is the name of the
75290 ** [sqlite3_vfs] object that defines the operating system 
75291 ** interface that the new database connection should use.  {F12722} If the
75292 ** fourth parameter is a NULL pointer then the default [sqlite3_vfs]
75293 ** object is used. {END}
75294 **
75295 ** <b>Note to windows users:</b>  The encoding used for the filename argument
75296 ** of [sqlite3_open()] and [sqlite3_open_v2()] must be UTF-8, not whatever
75297 ** codepage is currently defined.  Filenames containing international
75298 ** characters must be converted to UTF-8 prior to passing them into
75299 ** [sqlite3_open()] or [sqlite3_open_v2()].
75300 */
75301 int sqlite3_open(
75302   const char *filename,   /* Database filename (UTF-8) */
75303   sqlite3 **ppDb          /* OUT: SQLite db handle */
75304 );
75305 int sqlite3_open16(
75306   const void *filename,   /* Database filename (UTF-16) */
75307   sqlite3 **ppDb          /* OUT: SQLite db handle */
75308 );
75309 int sqlite3_open_v2(
75310   const char *filename,   /* Database filename (UTF-8) */
75311   sqlite3 **ppDb,         /* OUT: SQLite db handle */
75312   int flags,              /* Flags */
75313   const char *zVfs        /* Name of VFS module to use */
75314 );
75315
75316 /*
75317 ** CAPI3REF: Error Codes And Messages {F12800}
75318 **
75319 ** {F12801} The sqlite3_errcode() interface returns the numeric
75320 ** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code]
75321 ** for the most recent failed sqlite3_* API call associated
75322 ** with [sqlite3] handle 'db'. {U12802} If a prior API call failed but the
75323 ** most recent API call succeeded, the return value from sqlite3_errcode()
75324 ** is undefined. {END}
75325 **
75326 ** {F12803} The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
75327 ** text that describes the error, as either UTF8 or UTF16 respectively.
75328 ** {F12804} Memory to hold the error message string is managed internally.
75329 ** {U12805} The 
75330 ** string may be overwritten or deallocated by subsequent calls to SQLite
75331 ** interface functions. {END}
75332 **
75333 ** {F12806} Calls to many sqlite3_* functions set the error code and
75334 ** string returned by [sqlite3_errcode()], [sqlite3_errmsg()], and
75335 ** [sqlite3_errmsg16()] overwriting the previous values.  {F12807}
75336 ** Except, calls to [sqlite3_errcode()],
75337 ** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the
75338 ** results of future invocations.  {F12808} Calls to API routines that
75339 ** do not return an error code (example: [sqlite3_data_count()]) do not
75340 ** change the error code returned by this routine.  {F12809} Interfaces that
75341 ** are not associated with a specific database connection (examples:
75342 ** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change
75343 ** the return code. {END}
75344 **
75345 ** {F12810} Assuming no other intervening sqlite3_* API calls are made,
75346 ** the error code returned by this function is associated with the same
75347 ** error as the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()].
75348 */
75349 int sqlite3_errcode(sqlite3 *db);
75350 const char *sqlite3_errmsg(sqlite3*);
75351 const void *sqlite3_errmsg16(sqlite3*);
75352
75353 /*
75354 ** CAPI3REF: SQL Statement Object {F13000}
75355 **
75356 ** An instance of this object represent single SQL statements.  This
75357 ** object is variously known as a "prepared statement" or a 
75358 ** "compiled SQL statement" or simply as a "statement".
75359 ** 
75360 ** The life of a statement object goes something like this:
75361 **
75362 ** <ol>
75363 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
75364 **      function.
75365 ** <li> Bind values to host parameters using
75366 **      [sqlite3_bind_blob | sqlite3_bind_* interfaces].
75367 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
75368 ** <li> Reset the statement using [sqlite3_reset()] then go back
75369 **      to step 2.  Do this zero or more times.
75370 ** <li> Destroy the object using [sqlite3_finalize()].
75371 ** </ol>
75372 **
75373 ** Refer to documentation on individual methods above for additional
75374 ** information.
75375 */
75376 typedef struct sqlite3_stmt sqlite3_stmt;
75377
75378 /*
75379 ** CAPI3REF: Compiling An SQL Statement {F13010}
75380 **
75381 ** To execute an SQL query, it must first be compiled into a byte-code
75382 ** program using one of these routines. 
75383 **
75384 ** {F13011} The first argument "db" is an [sqlite3 | SQLite database handle] 
75385 ** obtained from a prior call to [sqlite3_open()], [sqlite3_open_v2()]
75386 ** or [sqlite3_open16()]. {F13012}
75387 ** The second argument "zSql" is the statement to be compiled, encoded
75388 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
75389 ** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2()
75390 ** use UTF-16. {END}
75391 **
75392 ** {F13013} If the nByte argument is less
75393 ** than zero, then zSql is read up to the first zero terminator.
75394 ** {F13014} If nByte is non-negative, then it is the maximum number of 
75395 ** bytes read from zSql.  When nByte is non-negative, the
75396 ** zSql string ends at either the first '\000' or '\u0000' character or 
75397 ** until the nByte-th byte, whichever comes first. {END}
75398 **
75399 ** {F13015} *pzTail is made to point to the first byte past the end of the
75400 ** first SQL statement in zSql.  These routines only compiles the first
75401 ** statement in zSql, so *pzTail is left pointing to what remains
75402 ** uncompiled. {END}
75403 **
75404 ** {F13016} *ppStmt is left pointing to a compiled 
75405 ** [sqlite3_stmt | SQL statement structure] that can be
75406 ** executed using [sqlite3_step()].  Or if there is an error, *ppStmt may be
75407 ** set to NULL.  {F13017} If the input text contains no SQL (if the input
75408 ** is and empty string or a comment) then *ppStmt is set to NULL.
75409 ** {U13018} The calling procedure is responsible for deleting the
75410 ** compiled SQL statement
75411 ** using [sqlite3_finalize()] after it has finished with it.
75412 **
75413 ** {F13019} On success, [SQLITE_OK] is returned.  Otherwise an 
75414 ** [SQLITE_ERROR | error code] is returned. {END}
75415 **
75416 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
75417 ** recommended for all new programs. The two older interfaces are retained
75418 ** for backwards compatibility, but their use is discouraged.
75419 ** {F13020} In the "v2" interfaces, the prepared statement
75420 ** that is returned (the [sqlite3_stmt] object) contains a copy of the 
75421 ** original SQL text. {END} This causes the [sqlite3_step()] interface to
75422 ** behave a differently in two ways:
75423 **
75424 ** <ol>
75425 ** <li>{F13022}
75426 ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
75427 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
75428 ** statement and try to run it again. {F12023} If the schema has changed in
75429 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
75430 ** return [SQLITE_SCHEMA].  {END} But unlike the legacy behavior, 
75431 ** [SQLITE_SCHEMA] is now a fatal error.  {F12024} Calling
75432 ** [sqlite3_prepare_v2()] again will not make the
75433 ** error go away.  {F12025} Note: use [sqlite3_errmsg()] to find the text
75434 ** of the parsing error that results in an [SQLITE_SCHEMA] return. {END}
75435 ** </li>
75436 **
75437 ** <li>
75438 ** {F13030} When an error occurs, 
75439 ** [sqlite3_step()] will return one of the detailed 
75440 ** [SQLITE_ERROR | result codes] or
75441 ** [SQLITE_IOERR_READ | extended result codes].  {F13031}
75442 ** The legacy behavior was that [sqlite3_step()] would only return a generic
75443 ** [SQLITE_ERROR] result code and you would have to make a second call to
75444 ** [sqlite3_reset()] in order to find the underlying cause of the problem.
75445 ** {F13032}
75446 ** With the "v2" prepare interfaces, the underlying reason for the error is
75447 ** returned immediately. {END}
75448 ** </li>
75449 ** </ol>
75450 */
75451 int sqlite3_prepare(
75452   sqlite3 *db,            /* Database handle */
75453   const char *zSql,       /* SQL statement, UTF-8 encoded */
75454   int nByte,              /* Maximum length of zSql in bytes. */
75455   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
75456   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
75457 );
75458 int sqlite3_prepare_v2(
75459   sqlite3 *db,            /* Database handle */
75460   const char *zSql,       /* SQL statement, UTF-8 encoded */
75461   int nByte,              /* Maximum length of zSql in bytes. */
75462   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
75463   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
75464 );
75465 int sqlite3_prepare16(
75466   sqlite3 *db,            /* Database handle */
75467   const void *zSql,       /* SQL statement, UTF-16 encoded */
75468   int nByte,              /* Maximum length of zSql in bytes. */
75469   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
75470   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
75471 );
75472 int sqlite3_prepare16_v2(
75473   sqlite3 *db,            /* Database handle */
75474   const void *zSql,       /* SQL statement, UTF-16 encoded */
75475   int nByte,              /* Maximum length of zSql in bytes. */
75476   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
75477   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
75478 );
75479
75480 /*
75481 ** CAPIREF: Retrieving Statement SQL {F13100}
75482 **
75483 ** {F13101} If the compiled SQL statement passed as an argument was
75484 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()],
75485 ** then this function returns a pointer to a zero-terminated string
75486 ** containing a copy of the original SQL statement. {F13102} The
75487 ** pointer is valid until the statement
75488 ** is deleted using sqlite3_finalize().
75489 ** {F13103} The string returned by sqlite3_sql() is always UTF8 even
75490 ** if a UTF16 string was originally entered using [sqlite3_prepare16_v2()]
75491 ** or the equivalent.
75492 **
75493 ** {F13104} If the statement was compiled using either of the legacy
75494 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this
75495 ** function returns NULL.
75496 */
75497 const char *sqlite3_sql(sqlite3_stmt *pStmt);
75498
75499 /*
75500 ** CAPI3REF:  Dynamically Typed Value Object  {F15000}
75501 **
75502 ** {F15001} SQLite uses the sqlite3_value object to represent all values
75503 ** that are or can be stored in a database table. {END}
75504 ** SQLite uses dynamic typing for the values it stores.  
75505 ** {F15002} Values stored in sqlite3_value objects can be
75506 ** be integers, floating point values, strings, BLOBs, or NULL.
75507 */
75508 typedef struct Mem sqlite3_value;
75509
75510 /*
75511 ** CAPI3REF:  SQL Function Context Object {F16001}
75512 **
75513 ** The context in which an SQL function executes is stored in an
75514 ** sqlite3_context object.  {F16002} A pointer to an sqlite3_context
75515 ** object is always first parameter to application-defined SQL functions.
75516 */
75517 typedef struct sqlite3_context sqlite3_context;
75518
75519 /*
75520 ** CAPI3REF:  Binding Values To Prepared Statements {F13500}
75521 **
75522 ** {F13501} In the SQL strings input to [sqlite3_prepare_v2()] and its
75523 ** variants, literals may be replace by a parameter in one
75524 ** of these forms:
75525 **
75526 ** <ul>
75527 ** <li>  ?
75528 ** <li>  ?NNN
75529 ** <li>  :AAA
75530 ** <li>  @AAA
75531 ** <li>  $VVV
75532 ** </ul>
75533 **
75534 ** In the parameter forms shown above NNN is an integer literal,
75535 ** AAA is an alphanumeric identifier and VVV is a variable name according
75536 ** to the syntax rules of the TCL programming language. {END}
75537 ** The values of these parameters (also called "host parameter names")
75538 ** can be set using the sqlite3_bind_*() routines defined here.
75539 **
75540 ** {F13502} The first argument to the sqlite3_bind_*() routines always
75541 ** is a pointer to the [sqlite3_stmt] object returned from
75542 ** [sqlite3_prepare_v2()] or its variants.  {F13503} The second
75543 ** argument is the index of the parameter to be set.  {F13504} The
75544 ** first parameter has an index of 1.  {F13505} When the same named
75545 ** parameter is used more than once, second and subsequent
75546 ** occurrences have the same index as the first occurrence. 
75547 ** {F13506} The index for named parameters can be looked up using the
75548 ** [sqlite3_bind_parameter_name()] API if desired.  {F13507} The index
75549 ** for "?NNN" parameters is the value of NNN.
75550 ** {F13508} The NNN value must be between 1 and the compile-time
75551 ** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). {END}
75552 ** See <a href="limits.html">limits.html</a> for additional information.
75553 **
75554 ** {F13509} The third argument is the value to bind to the parameter. {END}
75555 **
75556 ** {F13510} In those
75557 ** routines that have a fourth argument, its value is the number of bytes
75558 ** in the parameter.  To be clear: the value is the number of bytes in the
75559 ** string, not the number of characters. {F13511}  The number
75560 ** of bytes does not include the zero-terminator at the end of strings.
75561 ** {F13512}
75562 ** If the fourth parameter is negative, the length of the string is
75563 ** number of bytes up to the first zero terminator. {END}
75564 **
75565 ** {F13513}
75566 ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
75567 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
75568 ** text after SQLite has finished with it. {F13514} If the fifth argument is
75569 ** the special value [SQLITE_STATIC], then the library assumes that the
75570 ** information is in static, unmanaged space and does not need to be freed.
75571 ** {F13515} If the fifth argument has the value [SQLITE_TRANSIENT], then
75572 ** SQLite makes its own private copy of the data immediately, before
75573 ** the sqlite3_bind_*() routine returns. {END}
75574 **
75575 ** {F13520} The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
75576 ** is filled with zeros.  {F13521} A zeroblob uses a fixed amount of memory
75577 ** (just an integer to hold it size) while it is being processed. {END}
75578 ** Zeroblobs are intended to serve as place-holders for BLOBs whose
75579 ** content is later written using 
75580 ** [sqlite3_blob_open | increment BLOB I/O] routines. {F13522} A negative
75581 ** value for the zeroblob results in a zero-length BLOB. {END}
75582 **
75583 ** {F13530} The sqlite3_bind_*() routines must be called after
75584 ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and
75585 ** before [sqlite3_step()]. {F13531}
75586 ** Bindings are not cleared by the [sqlite3_reset()] routine.
75587 ** {F13532} Unbound parameters are interpreted as NULL. {END}
75588 **
75589 ** {F13540} These routines return [SQLITE_OK] on success or an error code if
75590 ** anything goes wrong.  {F13541} [SQLITE_RANGE] is returned if the parameter
75591 ** index is out of range.  {F13542} [SQLITE_NOMEM] is returned if malloc fails.
75592 ** {F13543} [SQLITE_MISUSE] is returned if these routines are called on a
75593 ** virtual machine that is the wrong state or which has already been finalized.
75594 */
75595 int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
75596 int sqlite3_bind_double(sqlite3_stmt*, int, double);
75597 int sqlite3_bind_int(sqlite3_stmt*, int, int);
75598 int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
75599 int sqlite3_bind_null(sqlite3_stmt*, int);
75600 int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
75601 int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
75602 int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
75603 int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
75604
75605 /*
75606 ** CAPI3REF: Number Of Host Parameters {F13600}
75607 **
75608 ** {F13601} Return the largest host parameter index in the precompiled
75609 ** statement given as the argument. {F13602} When the host parameters
75610 ** are of the forms like ":AAA", "$VVV", "@AAA", or "?",
75611 ** then they are assigned sequential increasing numbers beginning
75612 ** with one, so the value returned is the number of parameters.
75613 ** {F13603} However
75614 ** if the same host parameter name is used multiple times, each occurrance
75615 ** is given the same number, so the value returned in that case is the number
75616 ** of unique host parameter names. {F13604} If host parameters of the
75617 ** form "?NNN" are used (where NNN is an integer) then there might be
75618 ** gaps in the numbering and the value returned by this interface is
75619 ** the index of the host parameter with the largest index value. {END}
75620 **
75621 ** {U13605} The prepared statement must not be [sqlite3_finalize | finalized]
75622 ** prior to this routine returning.  Otherwise the results are undefined
75623 ** and probably undesirable.
75624 */
75625 int sqlite3_bind_parameter_count(sqlite3_stmt*);
75626
75627 /*
75628 ** CAPI3REF: Name Of A Host Parameter {F13620}
75629 **
75630 ** {F13621} This routine returns a pointer to the name of the n-th
75631 ** parameter in a [sqlite3_stmt | prepared statement]. {F13622}
75632 ** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name
75633 ** which is the string ":AAA" or "@AAA" or "$VVV". 
75634 ** In other words, the initial ":" or "$" or "@"
75635 ** is included as part of the name.  {F13626}
75636 ** Parameters of the form "?" or "?NNN" have no name.
75637 **
75638 ** {F13623} The first host parameter has an index of 1, not 0.
75639 **
75640 ** {F13624} If the value n is out of range or if the n-th parameter is
75641 ** nameless, then NULL is returned.  {F13625} The returned string is
75642 ** always in the UTF-8 encoding even if the named parameter was
75643 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
75644 ** [sqlite3_prepare16_v2()].
75645 */
75646 const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
75647
75648 /*
75649 ** CAPI3REF: Index Of A Parameter With A Given Name {F13640}
75650 **
75651 ** {F13641} This routine returns the index of a host parameter with the
75652 ** given name.  {F13642} The name must match exactly.  {F13643}
75653 ** If no parameter with the given name is found, return 0.
75654 ** {F13644} Parameter names must be UTF8.
75655 */
75656 int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
75657
75658 /*
75659 ** CAPI3REF: Reset All Bindings On A Prepared Statement {F13660}
75660 **
75661 ** {F13661} Contrary to the intuition of many, [sqlite3_reset()] does not
75662 ** reset the [sqlite3_bind_blob | bindings] on a 
75663 ** [sqlite3_stmt | prepared statement]. {F13662} Use this routine to
75664 ** reset all host parameters to NULL.
75665 */
75666 int sqlite3_clear_bindings(sqlite3_stmt*);
75667
75668 /*
75669 ** CAPI3REF: Number Of Columns In A Result Set {F13710}
75670 **
75671 ** {F13711} Return the number of columns in the result set returned by the 
75672 ** [sqlite3_stmt | compiled SQL statement]. {F13712} This routine returns 0
75673 ** if pStmt is an SQL statement that does not return data (for 
75674 ** example an UPDATE).
75675 */
75676 int sqlite3_column_count(sqlite3_stmt *pStmt);
75677
75678 /*
75679 ** CAPI3REF: Column Names In A Result Set {F13720}
75680 **
75681 ** {F13721} These routines return the name assigned to a particular column
75682 ** in the result set of a SELECT statement.  {F13722} The sqlite3_column_name()
75683 ** interface returns a pointer to a zero-terminated UTF8 string
75684 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
75685 ** UTF16 string. {F13723}  The first parameter is the
75686 ** [sqlite3_stmt | prepared statement] that implements the SELECT statement.
75687 ** The second parameter is the column number.  The left-most column is
75688 ** number 0.
75689 **
75690 ** {F13724} The returned string pointer is valid until either the 
75691 ** [sqlite3_stmt | prepared statement] is destroyed by [sqlite3_finalize()]
75692 ** or until the next call sqlite3_column_name() or sqlite3_column_name16()
75693 ** on the same column.
75694 **
75695 ** {F13725} If sqlite3_malloc() fails during the processing of either routine
75696 ** (for example during a conversion from UTF-8 to UTF-16) then a
75697 ** NULL pointer is returned.
75698 */
75699 const char *sqlite3_column_name(sqlite3_stmt*, int N);
75700 const void *sqlite3_column_name16(sqlite3_stmt*, int N);
75701
75702 /*
75703 ** CAPI3REF: Source Of Data In A Query Result {F13740}
75704 **
75705 ** {F13741} These routines provide a means to determine what column of what
75706 ** table in which database a result of a SELECT statement comes from.
75707 ** {F13742} The name of the database or table or column can be returned as
75708 ** either a UTF8 or UTF16 string.  {F13743} The _database_ routines return
75709 ** the database name, the _table_ routines return the table name, and
75710 ** the origin_ routines return the column name. {F13744}
75711 ** The returned string is valid until
75712 ** the [sqlite3_stmt | prepared statement] is destroyed using
75713 ** [sqlite3_finalize()] or until the same information is requested
75714 ** again in a different encoding.
75715 **
75716 ** {F13745} The names returned are the original un-aliased names of the
75717 ** database, table, and column.
75718 **
75719 ** {F13746} The first argument to the following calls is a 
75720 ** [sqlite3_stmt | compiled SQL statement].
75721 ** {F13747} These functions return information about the Nth column returned by 
75722 ** the statement, where N is the second function argument.
75723 **
75724 ** {F13748} If the Nth column returned by the statement is an expression
75725 ** or subquery and is not a column value, then all of these functions
75726 ** return NULL.  {F13749} Otherwise, they return the 
75727 ** name of the attached database, table and column that query result
75728 ** column was extracted from.
75729 **
75730 ** {F13750} As with all other SQLite APIs, those postfixed with "16" return
75731 ** UTF-16 encoded strings, the other functions return UTF-8. {END}
75732 **
75733 ** These APIs are only available if the library was compiled with the 
75734 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
75735 **
75736 ** {U13751}
75737 ** If two or more threads call one or more of these routines against the same
75738 ** prepared statement and column at the same time then the results are
75739 ** undefined.
75740 */
75741 const char *sqlite3_column_database_name(sqlite3_stmt*,int);
75742 const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
75743 const char *sqlite3_column_table_name(sqlite3_stmt*,int);
75744 const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
75745 const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
75746 const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
75747
75748 /*
75749 ** CAPI3REF: Declared Datatype Of A Query Result {F13760}
75750 **
75751 ** The first parameter is a [sqlite3_stmt | compiled SQL statement]. 
75752 ** {F13761} If this statement is a SELECT statement and the Nth column of the 
75753 ** returned result set of that SELECT is a table column (not an
75754 ** expression or subquery) then the declared type of the table
75755 ** column is returned.  {F13762} If the Nth column of the result set is an
75756 ** expression or subquery, then a NULL pointer is returned.
75757 ** {F13763} The returned string is always UTF-8 encoded.  {END} 
75758 ** For example, in the database schema:
75759 **
75760 ** CREATE TABLE t1(c1 VARIANT);
75761 **
75762 ** And the following statement compiled:
75763 **
75764 ** SELECT c1 + 1, c1 FROM t1;
75765 **
75766 ** Then this routine would return the string "VARIANT" for the second
75767 ** result column (i==1), and a NULL pointer for the first result column
75768 ** (i==0).
75769 **
75770 ** SQLite uses dynamic run-time typing.  So just because a column
75771 ** is declared to contain a particular type does not mean that the
75772 ** data stored in that column is of the declared type.  SQLite is
75773 ** strongly typed, but the typing is dynamic not static.  Type
75774 ** is associated with individual values, not with the containers
75775 ** used to hold those values.
75776 */
75777 const char *sqlite3_column_decltype(sqlite3_stmt *, int i);
75778 const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
75779
75780 /* 
75781 ** CAPI3REF:  Evaluate An SQL Statement {F13200}
75782 **
75783 ** After an [sqlite3_stmt | SQL statement] has been prepared with a call
75784 ** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of
75785 ** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()],
75786 ** then this function must be called one or more times to evaluate the 
75787 ** statement.
75788 **
75789 ** The details of the behavior of this sqlite3_step() interface depend
75790 ** on whether the statement was prepared using the newer "v2" interface
75791 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
75792 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
75793 ** new "v2" interface is recommended for new applications but the legacy
75794 ** interface will continue to be supported.
75795 **
75796 ** In the lagacy interface, the return value will be either [SQLITE_BUSY], 
75797 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
75798 ** With the "v2" interface, any of the other [SQLITE_OK | result code]
75799 ** or [SQLITE_IOERR_READ | extended result code] might be returned as
75800 ** well.
75801 **
75802 ** [SQLITE_BUSY] means that the database engine was unable to acquire the
75803 ** database locks it needs to do its job.  If the statement is a COMMIT
75804 ** or occurs outside of an explicit transaction, then you can retry the
75805 ** statement.  If the statement is not a COMMIT and occurs within a
75806 ** explicit transaction then you should rollback the transaction before
75807 ** continuing.
75808 **
75809 ** [SQLITE_DONE] means that the statement has finished executing
75810 ** successfully.  sqlite3_step() should not be called again on this virtual
75811 ** machine without first calling [sqlite3_reset()] to reset the virtual
75812 ** machine back to its initial state.
75813 **
75814 ** If the SQL statement being executed returns any data, then 
75815 ** [SQLITE_ROW] is returned each time a new row of data is ready
75816 ** for processing by the caller. The values may be accessed using
75817 ** the [sqlite3_column_int | column access functions].
75818 ** sqlite3_step() is called again to retrieve the next row of data.
75819 ** 
75820 ** [SQLITE_ERROR] means that a run-time error (such as a constraint
75821 ** violation) has occurred.  sqlite3_step() should not be called again on
75822 ** the VM. More information may be found by calling [sqlite3_errmsg()].
75823 ** With the legacy interface, a more specific error code (example:
75824 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
75825 ** can be obtained by calling [sqlite3_reset()] on the
75826 ** [sqlite3_stmt | prepared statement].  In the "v2" interface,
75827 ** the more specific error code is returned directly by sqlite3_step().
75828 **
75829 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
75830 ** Perhaps it was called on a [sqlite3_stmt | prepared statement] that has
75831 ** already been [sqlite3_finalize | finalized] or on one that had 
75832 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
75833 ** be the case that the same database connection is being used by two or
75834 ** more threads at the same moment in time.
75835 **
75836 ** <b>Goofy Interface Alert:</b>
75837 ** In the legacy interface, 
75838 ** the sqlite3_step() API always returns a generic error code,
75839 ** [SQLITE_ERROR], following any error other than [SQLITE_BUSY]
75840 ** and [SQLITE_MISUSE].  You must call [sqlite3_reset()] or
75841 ** [sqlite3_finalize()] in order to find one of the specific
75842 ** [SQLITE_ERROR | result codes] that better describes the error.
75843 ** We admit that this is a goofy design.  The problem has been fixed
75844 ** with the "v2" interface.  If you prepare all of your SQL statements
75845 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
75846 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the 
75847 ** more specific [SQLITE_ERROR | result codes] are returned directly
75848 ** by sqlite3_step().  The use of the "v2" interface is recommended.
75849 */
75850 int sqlite3_step(sqlite3_stmt*);
75851
75852 /*
75853 ** CAPI3REF: Number of columns in a result set {F13770}
75854 **
75855 ** Return the number of values in the current row of the result set.
75856 **
75857 ** {F13771} After a call to [sqlite3_step()] that returns [SQLITE_ROW],
75858 ** this routine
75859 ** will return the same value as the [sqlite3_column_count()] function.
75860 ** {F13772}
75861 ** After [sqlite3_step()] has returned an [SQLITE_DONE], [SQLITE_BUSY], or
75862 ** a [SQLITE_ERROR | error code], or before [sqlite3_step()] has been 
75863 ** called on the [sqlite3_stmt | prepared statement] for the first time,
75864 ** this routine returns zero.
75865 */
75866 int sqlite3_data_count(sqlite3_stmt *pStmt);
75867
75868 /*
75869 ** CAPI3REF: Fundamental Datatypes {F10265}
75870 **
75871 ** {F10266}Every value in SQLite has one of five fundamental datatypes:
75872 **
75873 ** <ul>
75874 ** <li> 64-bit signed integer
75875 ** <li> 64-bit IEEE floating point number
75876 ** <li> string
75877 ** <li> BLOB
75878 ** <li> NULL
75879 ** </ul> {END}
75880 **
75881 ** These constants are codes for each of those types.
75882 **
75883 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
75884 ** for a completely different meaning.  Software that links against both
75885 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not
75886 ** SQLITE_TEXT.
75887 */
75888 #define SQLITE_INTEGER  1
75889 #define SQLITE_FLOAT    2
75890 #define SQLITE_BLOB     4
75891 #define SQLITE_NULL     5
75892 #ifdef SQLITE_TEXT
75893 # undef SQLITE_TEXT
75894 #else
75895 # define SQLITE_TEXT     3
75896 #endif
75897 #define SQLITE3_TEXT     3
75898
75899 /*
75900 ** CAPI3REF: Results Values From A Query {F13800}
75901 **
75902 ** These routines return information about
75903 ** a single column of the current result row of a query.  In every
75904 ** case the first argument is a pointer to the 
75905 ** [sqlite3_stmt | SQL statement] that is being
75906 ** evaluated (the [sqlite3_stmt*] that was returned from 
75907 ** [sqlite3_prepare_v2()] or one of its variants) and
75908 ** the second argument is the index of the column for which information 
75909 ** should be returned.  The left-most column of the result set
75910 ** has an index of 0.
75911 **
75912 ** If the SQL statement is not currently point to a valid row, or if the
75913 ** the column index is out of range, the result is undefined. 
75914 ** These routines may only be called when the most recent call to
75915 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
75916 ** [sqlite3_reset()] nor [sqlite3_finalize()] has been call subsequently.
75917 ** If any of these routines are called after [sqlite3_reset()] or
75918 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
75919 ** something other than [SQLITE_ROW], the results are undefined.
75920 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
75921 ** are called from a different thread while any of these routines
75922 ** are pending, then the results are undefined.  
75923 **
75924 ** The sqlite3_column_type() routine returns 
75925 ** [SQLITE_INTEGER | datatype code] for the initial data type
75926 ** of the result column.  The returned value is one of [SQLITE_INTEGER],
75927 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
75928 ** returned by sqlite3_column_type() is only meaningful if no type
75929 ** conversions have occurred as described below.  After a type conversion,
75930 ** the value returned by sqlite3_column_type() is undefined.  Future
75931 ** versions of SQLite may change the behavior of sqlite3_column_type()
75932 ** following a type conversion.
75933 **
75934 ** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() 
75935 ** routine returns the number of bytes in that BLOB or string.
75936 ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
75937 ** the string to UTF-8 and then returns the number of bytes.
75938 ** If the result is a numeric value then sqlite3_column_bytes() uses
75939 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
75940 ** the number of bytes in that string.
75941 ** The value returned does not include the zero terminator at the end
75942 ** of the string.  For clarity: the value returned is the number of
75943 ** bytes in the string, not the number of characters.
75944 **
75945 ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
75946 ** even zero-length strings, are always zero terminated.  The return
75947 ** value from sqlite3_column_blob() for a zero-length blob is an arbitrary
75948 ** pointer, possibly even a NULL pointer.
75949 **
75950 ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
75951 ** but leaves the result in UTF-16 instead of UTF-8.  
75952 ** The zero terminator is not included in this count.
75953 **
75954 ** These routines attempt to convert the value where appropriate.  For
75955 ** example, if the internal representation is FLOAT and a text result
75956 ** is requested, [sqlite3_snprintf()] is used internally to do the conversion
75957 ** automatically.  The following table details the conversions that
75958 ** are applied:
75959 **
75960 ** <blockquote>
75961 ** <table border="1">
75962 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
75963 **
75964 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
75965 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
75966 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
75967 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
75968 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
75969 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
75970 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as for INTEGER->TEXT
75971 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
75972 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
75973 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
75974 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
75975 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
75976 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
75977 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
75978 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
75979 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
75980 ** </table>
75981 ** </blockquote>
75982 **
75983 ** The table above makes reference to standard C library functions atoi()
75984 ** and atof().  SQLite does not really use these functions.  It has its
75985 ** on equavalent internal routines.  The atoi() and atof() names are
75986 ** used in the table for brevity and because they are familiar to most
75987 ** C programmers.
75988 **
75989 ** Note that when type conversions occur, pointers returned by prior
75990 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
75991 ** sqlite3_column_text16() may be invalidated. 
75992 ** Type conversions and pointer invalidations might occur
75993 ** in the following cases:
75994 **
75995 ** <ul>
75996 ** <li><p>  The initial content is a BLOB and sqlite3_column_text() 
75997 **          or sqlite3_column_text16() is called.  A zero-terminator might
75998 **          need to be added to the string.</p></li>
75999 **
76000 ** <li><p>  The initial content is UTF-8 text and sqlite3_column_bytes16() or
76001 **          sqlite3_column_text16() is called.  The content must be converted
76002 **          to UTF-16.</p></li>
76003 **
76004 ** <li><p>  The initial content is UTF-16 text and sqlite3_column_bytes() or
76005 **          sqlite3_column_text() is called.  The content must be converted
76006 **          to UTF-8.</p></li>
76007 ** </ul>
76008 **
76009 ** Conversions between UTF-16be and UTF-16le are always done in place and do
76010 ** not invalidate a prior pointer, though of course the content of the buffer
76011 ** that the prior pointer points to will have been modified.  Other kinds
76012 ** of conversion are done in place when it is possible, but sometime it is
76013 ** not possible and in those cases prior pointers are invalidated.  
76014 **
76015 ** The safest and easiest to remember policy is to invoke these routines
76016 ** in one of the following ways:
76017 **
76018 **  <ul>
76019 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
76020 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
76021 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
76022 **  </ul>
76023 **
76024 ** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(),
76025 ** or sqlite3_column_text16() first to force the result into the desired
76026 ** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to
76027 ** find the size of the result.  Do not mix call to sqlite3_column_text() or
76028 ** sqlite3_column_blob() with calls to sqlite3_column_bytes16().  And do not
76029 ** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes().
76030 **
76031 ** The pointers returned are valid until a type conversion occurs as
76032 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
76033 ** [sqlite3_finalize()] is called.  The memory space used to hold strings
76034 ** and blobs is freed automatically.  Do <b>not</b> pass the pointers returned
76035 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into 
76036 ** [sqlite3_free()].
76037 **
76038 ** If a memory allocation error occurs during the evaluation of any
76039 ** of these routines, a default value is returned.  The default value
76040 ** is either the integer 0, the floating point number 0.0, or a NULL
76041 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
76042 ** [SQLITE_NOMEM].
76043 */
76044 const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
76045 int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
76046 int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
76047 double sqlite3_column_double(sqlite3_stmt*, int iCol);
76048 int sqlite3_column_int(sqlite3_stmt*, int iCol);
76049 sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
76050 const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
76051 const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
76052 int sqlite3_column_type(sqlite3_stmt*, int iCol);
76053 sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
76054
76055 /*
76056 ** CAPI3REF: Destroy A Prepared Statement Object {F13300}
76057 **
76058 ** The sqlite3_finalize() function is called to delete a 
76059 ** [sqlite3_stmt | compiled SQL statement]. If the statement was
76060 ** executed successfully, or not executed at all, then SQLITE_OK is returned.
76061 ** If execution of the statement failed then an 
76062 ** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code]
76063 ** is returned. 
76064 **
76065 ** This routine can be called at any point during the execution of the
76066 ** [sqlite3_stmt | virtual machine].  If the virtual machine has not 
76067 ** completed execution when this routine is called, that is like
76068 ** encountering an error or an interrupt.  (See [sqlite3_interrupt()].) 
76069 ** Incomplete updates may be rolled back and transactions cancelled,  
76070 ** depending on the circumstances, and the 
76071 ** [SQLITE_ERROR | result code] returned will be [SQLITE_ABORT].
76072 */
76073 int sqlite3_finalize(sqlite3_stmt *pStmt);
76074
76075 /*
76076 ** CAPI3REF: Reset A Prepared Statement Object {F13330}
76077 **
76078 ** The sqlite3_reset() function is called to reset a 
76079 ** [sqlite3_stmt | compiled SQL statement] object.
76080 ** back to its initial state, ready to be re-executed.
76081 ** Any SQL statement variables that had values bound to them using
76082 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
76083 ** Use [sqlite3_clear_bindings()] to reset the bindings.
76084 */
76085 int sqlite3_reset(sqlite3_stmt *pStmt);
76086
76087 /*
76088 ** CAPI3REF: Create Or Redefine SQL Functions {F16100}
76089 **
76090 ** The following two functions are used to add SQL functions or aggregates
76091 ** or to redefine the behavior of existing SQL functions or aggregates.  The
76092 ** difference only between the two is that the second parameter, the
76093 ** name of the (scalar) function or aggregate, is encoded in UTF-8 for
76094 ** sqlite3_create_function() and UTF-16 for sqlite3_create_function16().
76095 **
76096 ** The first argument is the [sqlite3 | database handle] that holds the
76097 ** SQL function or aggregate is to be added or redefined. If a single
76098 ** program uses more than one database handle internally, then SQL
76099 ** functions or aggregates must be added individually to each database
76100 ** handle with which they will be used.
76101 **
76102 ** The second parameter is the name of the SQL function to be created
76103 ** or redefined.
76104 ** The length of the name is limited to 255 bytes, exclusive of the 
76105 ** zero-terminator.  Note that the name length limit is in bytes, not
76106 ** characters.  Any attempt to create a function with a longer name
76107 ** will result in an SQLITE_ERROR error.
76108 **
76109 ** The third parameter is the number of arguments that the SQL function or
76110 ** aggregate takes. If this parameter is negative, then the SQL function or
76111 ** aggregate may take any number of arguments.
76112 **
76113 ** The fourth parameter, eTextRep, specifies what 
76114 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
76115 ** its parameters.  Any SQL function implementation should be able to work
76116 ** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
76117 ** more efficient with one encoding than another.  It is allowed to
76118 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
76119 ** times with the same function but with different values of eTextRep.
76120 ** When multiple implementations of the same function are available, SQLite
76121 ** will pick the one that involves the least amount of data conversion.
76122 ** If there is only a single implementation which does not care what
76123 ** text encoding is used, then the fourth argument should be
76124 ** [SQLITE_ANY].
76125 **
76126 ** The fifth parameter is an arbitrary pointer.  The implementation
76127 ** of the function can gain access to this pointer using
76128 ** [sqlite3_user_data()].
76129 **
76130 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
76131 ** pointers to C-language functions that implement the SQL
76132 ** function or aggregate. A scalar SQL function requires an implementation of
76133 ** the xFunc callback only, NULL pointers should be passed as the xStep
76134 ** and xFinal parameters. An aggregate SQL function requires an implementation
76135 ** of xStep and xFinal and NULL should be passed for xFunc. To delete an
76136 ** existing SQL function or aggregate, pass NULL for all three function
76137 ** callback.
76138 **
76139 ** It is permitted to register multiple implementations of the same
76140 ** functions with the same name but with either differing numbers of
76141 ** arguments or differing perferred text encodings.  SQLite will use
76142 ** the implementation most closely matches the way in which the
76143 ** SQL function is used.
76144 */
76145 int sqlite3_create_function(
76146   sqlite3 *,
76147   const char *zFunctionName,
76148   int nArg,
76149   int eTextRep,
76150   void*,
76151   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
76152   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
76153   void (*xFinal)(sqlite3_context*)
76154 );
76155 int sqlite3_create_function16(
76156   sqlite3*,
76157   const void *zFunctionName,
76158   int nArg,
76159   int eTextRep,
76160   void*,
76161   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
76162   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
76163   void (*xFinal)(sqlite3_context*)
76164 );
76165
76166 /*
76167 ** CAPI3REF: Text Encodings {F10267}
76168 **
76169 ** These constant define integer codes that represent the various
76170 ** text encodings supported by SQLite.
76171 */
76172 #define SQLITE_UTF8           1
76173 #define SQLITE_UTF16LE        2
76174 #define SQLITE_UTF16BE        3
76175 #define SQLITE_UTF16          4    /* Use native byte order */
76176 #define SQLITE_ANY            5    /* sqlite3_create_function only */
76177 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
76178
76179 /*
76180 ** CAPI3REF: Obsolete Functions
76181 **
76182 ** These functions are all now obsolete.  In order to maintain
76183 ** backwards compatibility with older code, we continue to support
76184 ** these functions.  However, new development projects should avoid
76185 ** the use of these functions.  To help encourage people to avoid
76186 ** using these functions, we are not going to tell you want they do.
76187 */
76188 int sqlite3_aggregate_count(sqlite3_context*);
76189 int sqlite3_expired(sqlite3_stmt*);
76190 int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
76191 int sqlite3_global_recover(void);
76192 void sqlite3_thread_cleanup(void);
76193 int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
76194
76195 /*
76196 ** CAPI3REF: Obtaining SQL Function Parameter Values {F15100}
76197 **
76198 ** The C-language implementation of SQL functions and aggregates uses
76199 ** this set of interface routines to access the parameter values on
76200 ** the function or aggregate.
76201 **
76202 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
76203 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
76204 ** define callbacks that implement the SQL functions and aggregates.
76205 ** The 4th parameter to these callbacks is an array of pointers to
76206 ** [sqlite3_value] objects.  There is one [sqlite3_value] object for
76207 ** each parameter to the SQL function.  These routines are used to
76208 ** extract values from the [sqlite3_value] objects.
76209 **
76210 ** These routines work just like the corresponding 
76211 ** [sqlite3_column_blob | sqlite3_column_* routines] except that 
76212 ** these routines take a single [sqlite3_value*] pointer instead
76213 ** of an [sqlite3_stmt*] pointer and an integer column number.
76214 **
76215 ** The sqlite3_value_text16() interface extracts a UTF16 string
76216 ** in the native byte-order of the host machine.  The
76217 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
76218 ** extract UTF16 strings as big-endian and little-endian respectively.
76219 **
76220 ** The sqlite3_value_numeric_type() interface attempts to apply
76221 ** numeric affinity to the value.  This means that an attempt is
76222 ** made to convert the value to an integer or floating point.  If
76223 ** such a conversion is possible without loss of information (in other
76224 ** words if the value is a string that looks like a number)
76225 ** then the conversion is done.  Otherwise no conversion occurs.  The 
76226 ** [SQLITE_INTEGER | datatype] after conversion is returned.
76227 **
76228 ** Please pay particular attention to the fact that the pointer that
76229 ** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or
76230 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
76231 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
76232 ** or [sqlite3_value_text16()].  
76233 **
76234 ** These routines must be called from the same thread as
76235 ** the SQL function that supplied the sqlite3_value* parameters.
76236 ** Or, if the sqlite3_value* argument comes from the [sqlite3_column_value()]
76237 ** interface, then these routines should be called from the same thread
76238 ** that ran [sqlite3_column_value()].
76239 **
76240 */
76241 const void *sqlite3_value_blob(sqlite3_value*);
76242 int sqlite3_value_bytes(sqlite3_value*);
76243 int sqlite3_value_bytes16(sqlite3_value*);
76244 double sqlite3_value_double(sqlite3_value*);
76245 int sqlite3_value_int(sqlite3_value*);
76246 sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
76247 const unsigned char *sqlite3_value_text(sqlite3_value*);
76248 const void *sqlite3_value_text16(sqlite3_value*);
76249 const void *sqlite3_value_text16le(sqlite3_value*);
76250 const void *sqlite3_value_text16be(sqlite3_value*);
76251 int sqlite3_value_type(sqlite3_value*);
76252 int sqlite3_value_numeric_type(sqlite3_value*);
76253
76254 /*
76255 ** CAPI3REF: Obtain Aggregate Function Context {F16210}
76256 **
76257 ** The implementation of aggregate SQL functions use this routine to allocate
76258 ** a structure for storing their state.  
76259 ** {F16211} The first time the sqlite3_aggregate_context() routine is
76260 ** is called for a particular aggregate, SQLite allocates nBytes of memory
76261 ** zeros that memory, and returns a pointer to it.
76262 ** {F16212} On second and subsequent calls to sqlite3_aggregate_context()
76263 ** for the same aggregate function index, the same buffer is returned. {END}
76264 ** The implementation
76265 ** of the aggregate can use the returned buffer to accumulate data.
76266 **
76267 ** {F16213} SQLite automatically frees the allocated buffer when the aggregate
76268 ** query concludes. {END}
76269 **
76270 ** The first parameter should be a copy of the 
76271 ** [sqlite3_context | SQL function context] that is the first
76272 ** parameter to the callback routine that implements the aggregate
76273 ** function.
76274 **
76275 ** This routine must be called from the same thread in which
76276 ** the aggregate SQL function is running.
76277 */
76278 void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
76279
76280 /*
76281 ** CAPI3REF: User Data For Functions {F16240}
76282 **
76283 ** {F16241} The sqlite3_user_data() interface returns a copy of
76284 ** the pointer that was the pUserData parameter (the 5th parameter)
76285 ** of the the [sqlite3_create_function()]
76286 ** and [sqlite3_create_function16()] routines that originally
76287 ** registered the application defined function. {END}
76288 **
76289 ** {U16243} This routine must be called from the same thread in which
76290 ** the application-defined function is running.
76291 */
76292 void *sqlite3_user_data(sqlite3_context*);
76293
76294 /*
76295 ** CAPI3REF: Function Auxiliary Data {F16270}
76296 **
76297 ** The following two functions may be used by scalar SQL functions to
76298 ** associate meta-data with argument values. If the same value is passed to
76299 ** multiple invocations of the same SQL function during query execution, under
76300 ** some circumstances the associated meta-data may be preserved. This may
76301 ** be used, for example, to add a regular-expression matching scalar
76302 ** function. The compiled version of the regular expression is stored as
76303 ** meta-data associated with the SQL value passed as the regular expression
76304 ** pattern.  The compiled regular expression can be reused on multiple
76305 ** invocations of the same function so that the original pattern string
76306 ** does not need to be recompiled on each invocation.
76307 **
76308 ** {F16271}
76309 ** The sqlite3_get_auxdata() interface returns a pointer to the meta-data
76310 ** associated by the sqlite3_set_auxdata() function with the Nth argument
76311 ** value to the application-defined function.
76312 ** {F16272} If no meta-data has been ever been set for the Nth
76313 ** argument of the function, or if the cooresponding function parameter
76314 ** has changed since the meta-data was set, then sqlite3_get_auxdata()
76315 ** returns a NULL pointer.
76316 **
76317 ** {F16275} The sqlite3_set_auxdata() interface saves the meta-data
76318 ** pointed to by its 3rd parameter as the meta-data for the N-th
76319 ** argument of the application-defined function. {END} Subsequent
76320 ** calls to sqlite3_get_auxdata() might return this data, if it has
76321 ** not been destroyed. 
76322 ** {F16277} If it is not NULL, SQLite will invoke the destructor 
76323 ** function given by the 4th parameter to sqlite3_set_auxdata() on
76324 ** the meta-data when the corresponding function parameter changes
76325 ** or when the SQL statement completes, whichever comes first. {END}
76326 **
76327 ** In practice, meta-data is preserved between function calls for
76328 ** expressions that are constant at compile time. This includes literal
76329 ** values and SQL variables.
76330 **
76331 ** These routines must be called from the same thread in which
76332 ** the SQL function is running.
76333 */
76334 void *sqlite3_get_auxdata(sqlite3_context*, int N);
76335 void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
76336
76337
76338 /*
76339 ** CAPI3REF: Constants Defining Special Destructor Behavior {F10280}
76340 **
76341 ** These are special value for the destructor that is passed in as the
76342 ** final argument to routines like [sqlite3_result_blob()].  If the destructor
76343 ** argument is SQLITE_STATIC, it means that the content pointer is constant
76344 ** and will never change.  It does not need to be destroyed.  The 
76345 ** SQLITE_TRANSIENT value means that the content will likely change in
76346 ** the near future and that SQLite should make its own private copy of
76347 ** the content before returning.
76348 **
76349 ** The typedef is necessary to work around problems in certain
76350 ** C++ compilers.  See ticket #2191.
76351 */
76352 typedef void (*sqlite3_destructor_type)(void*);
76353 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
76354 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
76355
76356 /*
76357 ** CAPI3REF: Setting The Result Of An SQL Function {F16400}
76358 **
76359 ** These routines are used by the xFunc or xFinal callbacks that
76360 ** implement SQL functions and aggregates.  See
76361 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
76362 ** for additional information.
76363 **
76364 ** These functions work very much like the 
76365 ** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used
76366 ** to bind values to host parameters in prepared statements.
76367 ** Refer to the
76368 ** [sqlite3_bind_blob | sqlite3_bind_* documentation] for
76369 ** additional information.
76370 **
76371 ** {F16402} The sqlite3_result_blob() interface sets the result from
76372 ** an application defined function to be the BLOB whose content is pointed
76373 ** to by the second parameter and which is N bytes long where N is the
76374 ** third parameter. 
76375 ** {F16403} The sqlite3_result_zeroblob() inerfaces set the result of
76376 ** the application defined function to be a BLOB containing all zero
76377 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
76378 **
76379 ** {F16407} The sqlite3_result_double() interface sets the result from
76380 ** an application defined function to be a floating point value specified
76381 ** by its 2nd argument.
76382 **
76383 ** {F16409} The sqlite3_result_error() and sqlite3_result_error16() functions
76384 ** cause the implemented SQL function to throw an exception.
76385 ** {F16411} SQLite uses the string pointed to by the
76386 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
76387 ** as the text of an error message. {F16412} SQLite interprets the error
76388 ** message string from sqlite3_result_error() as UTF8.  {F16413} SQLite
76389 ** interprets the string from sqlite3_result_error16() as UTF16 in native
76390 ** byte order.  {F16414} If the third parameter to sqlite3_result_error()
76391 ** or sqlite3_result_error16() is negative then SQLite takes as the error
76392 ** message all text up through the first zero character.
76393 ** {F16415} If the third parameter to sqlite3_result_error() or
76394 ** sqlite3_result_error16() is non-negative then SQLite takes that many
76395 ** bytes (not characters) from the 2nd parameter as the error message.
76396 ** {F16417} The sqlite3_result_error() and sqlite3_result_error16()
76397 ** routines make a copy private copy of the error message text before
76398 ** they return.  {END} Hence, the calling function can deallocate or
76399 ** modify the text after they return without harm.
76400 **
76401 ** {F16421} The sqlite3_result_toobig() interface causes SQLite
76402 ** to throw an error indicating that a string or BLOB is to long
76403 ** to represent.  {F16422} The sqlite3_result_nomem() interface
76404 ** causes SQLite to throw an exception indicating that the a
76405 ** memory allocation failed.
76406 **
76407 ** {F16431} The sqlite3_result_int() interface sets the return value
76408 ** of the application-defined function to be the 32-bit signed integer
76409 ** value given in the 2nd argument.
76410 ** {F16432} The sqlite3_result_int64() interface sets the return value
76411 ** of the application-defined function to be the 64-bit signed integer
76412 ** value given in the 2nd argument.
76413 **
76414 ** {F16437} The sqlite3_result_null() interface sets the return value
76415 ** of the application-defined function to be NULL.
76416 **
76417 ** {F16441} The sqlite3_result_text(), sqlite3_result_text16(), 
76418 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
76419 ** set the return value of the application-defined function to be
76420 ** a text string which is represented as UTF-8, UTF-16 native byte order,
76421 ** UTF-16 little endian, or UTF-16 big endian, respectively.
76422 ** {F16442} SQLite takes the text result from the application from
76423 ** the 2nd parameter of the sqlite3_result_text* interfaces.
76424 ** {F16444} If the 3rd parameter to the sqlite3_result_text* interfaces
76425 ** is negative, then SQLite takes result text from the 2nd parameter 
76426 ** through the first zero character.
76427 ** {F16447} If the 3rd parameter to the sqlite3_result_text* interfaces
76428 ** is non-negative, then as many bytes (not characters) of the text
76429 ** pointed to by the 2nd parameter are taken as the application-defined
76430 ** function result.
76431 ** {F16451} If the 4th parameter to the sqlite3_result_text* interfaces
76432 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
76433 ** function as the destructor on the text or blob result when it has
76434 ** finished using that result.
76435 ** {F16453} If the 4th parameter to the sqlite3_result_text* interfaces
76436 ** or sqlite3_result_blob is the special constant SQLITE_STATIC, then
76437 ** SQLite assumes that the text or blob result is constant space and
76438 ** does not copy the space or call a destructor when it has
76439 ** finished using that result.
76440 ** {F16454} If the 4th parameter to the sqlite3_result_text* interfaces
76441 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
76442 ** then SQLite makes a copy of the result into space obtained from
76443 ** from [sqlite3_malloc()] before it returns.
76444 **
76445 ** {F16461} The sqlite3_result_value() interface sets the result of
76446 ** the application-defined function to be a copy the [sqlite3_value]
76447 ** object specified by the 2nd parameter.  {F16463} The
76448 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
76449 ** so that [sqlite3_value] specified in the parameter may change or
76450 ** be deallocated after sqlite3_result_value() returns without harm.
76451 **
76452 ** {U16491} These routines are called from within the different thread 
76453 ** than the one containing the application-defined function that recieved
76454 ** the [sqlite3_context] pointer, the results are undefined.
76455 */
76456 void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
76457 void sqlite3_result_double(sqlite3_context*, double);
76458 void sqlite3_result_error(sqlite3_context*, const char*, int);
76459 void sqlite3_result_error16(sqlite3_context*, const void*, int);
76460 void sqlite3_result_error_toobig(sqlite3_context*);
76461 void sqlite3_result_error_nomem(sqlite3_context*);
76462 void sqlite3_result_int(sqlite3_context*, int);
76463 void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
76464 void sqlite3_result_null(sqlite3_context*);
76465 void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
76466 void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
76467 void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
76468 void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
76469 void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
76470 void sqlite3_result_zeroblob(sqlite3_context*, int n);
76471
76472 /*
76473 ** CAPI3REF: Define New Collating Sequences {F16600}
76474 **
76475 ** {F16601}
76476 ** These functions are used to add new collation sequences to the
76477 ** [sqlite3*] handle specified as the first argument. 
76478 **
76479 ** {F16602}
76480 ** The name of the new collation sequence is specified as a UTF-8 string
76481 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
76482 ** and a UTF-16 string for sqlite3_create_collation16(). {F16603} In all cases
76483 ** the name is passed as the second function argument.
76484 **
76485 ** {F16604}
76486 ** The third argument may be one of the constants [SQLITE_UTF8],
76487 ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
76488 ** routine expects to be passed pointers to strings encoded using UTF-8,
76489 ** UTF-16 little-endian or UTF-16 big-endian respectively. {F16605} The
76490 ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that
76491 ** the routine expects pointers to 16-bit word aligned strings
76492 ** of UTF16 in the native byte order of the host computer.
76493 **
76494 ** {F16607}
76495 ** A pointer to the user supplied routine must be passed as the fifth
76496 ** argument. {F16609} If it is NULL, this is the same as deleting the collation
76497 ** sequence (so that SQLite cannot call it anymore).
76498 ** {F16611} Each time the application
76499 ** supplied function is invoked, it is passed a copy of the void* passed as
76500 ** the fourth argument to sqlite3_create_collation() or
76501 ** sqlite3_create_collation16() as its first parameter.
76502 **
76503 ** {F16612}
76504 ** The remaining arguments to the application-supplied routine are two strings,
76505 ** each represented by a [length, data] pair and encoded in the encoding
76506 ** that was passed as the third argument when the collation sequence was
76507 ** registered. {END} The application defined collation routine should
76508 ** return negative, zero or positive if
76509 ** the first string is less than, equal to, or greater than the second
76510 ** string. i.e. (STRING1 - STRING2).
76511 **
76512 ** {F16615}
76513 ** The sqlite3_create_collation_v2() works like sqlite3_create_collation()
76514 ** excapt that it takes an extra argument which is a destructor for
76515 ** the collation.  {F16617} The destructor is called when the collation is
76516 ** destroyed and is passed a copy of the fourth parameter void* pointer
76517 ** of the sqlite3_create_collation_v2().
76518 ** {F16618}  Collations are destroyed when
76519 ** they are overridden by later calls to the collation creation functions
76520 ** or when the [sqlite3*] database handle is closed using [sqlite3_close()].
76521 */
76522 int sqlite3_create_collation(
76523   sqlite3*, 
76524   const char *zName, 
76525   int eTextRep, 
76526   void*,
76527   int(*xCompare)(void*,int,const void*,int,const void*)
76528 );
76529 int sqlite3_create_collation_v2(
76530   sqlite3*, 
76531   const char *zName, 
76532   int eTextRep, 
76533   void*,
76534   int(*xCompare)(void*,int,const void*,int,const void*),
76535   void(*xDestroy)(void*)
76536 );
76537 int sqlite3_create_collation16(
76538   sqlite3*, 
76539   const char *zName, 
76540   int eTextRep, 
76541   void*,
76542   int(*xCompare)(void*,int,const void*,int,const void*)
76543 );
76544
76545 /*
76546 ** CAPI3REF: Collation Needed Callbacks {F16700}
76547 **
76548 ** {F16701}
76549 ** To avoid having to register all collation sequences before a database
76550 ** can be used, a single callback function may be registered with the
76551 ** database handle to be called whenever an undefined collation sequence is
76552 ** required.
76553 **
76554 ** {F16702}
76555 ** If the function is registered using the sqlite3_collation_needed() API,
76556 ** then it is passed the names of undefined collation sequences as strings
76557 ** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, the names
76558 ** are passed as UTF-16 in machine native byte order. {F16704} A call to either
76559 ** function replaces any existing callback.
76560 **
76561 ** {F16705} When the callback is invoked, the first argument passed is a copy
76562 ** of the second argument to sqlite3_collation_needed() or
76563 ** sqlite3_collation_needed16(). {F16706} The second argument is the database
76564 ** handle.  {F16707} The third argument is one of [SQLITE_UTF8],
76565 ** [SQLITE_UTF16BE], or [SQLITE_UTF16LE], indicating the most
76566 ** desirable form of the collation sequence function required.
76567 ** {F16708} The fourth parameter is the name of the
76568 ** required collation sequence. {END}
76569 **
76570 ** The callback function should register the desired collation using
76571 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
76572 ** [sqlite3_create_collation_v2()].
76573 */
76574 int sqlite3_collation_needed(
76575   sqlite3*, 
76576   void*, 
76577   void(*)(void*,sqlite3*,int eTextRep,const char*)
76578 );
76579 int sqlite3_collation_needed16(
76580   sqlite3*, 
76581   void*,
76582   void(*)(void*,sqlite3*,int eTextRep,const void*)
76583 );
76584
76585 /*
76586 ** Specify the key for an encrypted database.  This routine should be
76587 ** called right after sqlite3_open().
76588 **
76589 ** The code to implement this API is not available in the public release
76590 ** of SQLite.
76591 */
76592 int sqlite3_key(
76593   sqlite3 *db,                   /* Database to be rekeyed */
76594   const void *pKey, int nKey     /* The key */
76595 );
76596
76597 /*
76598 ** Change the key on an open database.  If the current database is not
76599 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
76600 ** database is decrypted.
76601 **
76602 ** The code to implement this API is not available in the public release
76603 ** of SQLite.
76604 */
76605 int sqlite3_rekey(
76606   sqlite3 *db,                   /* Database to be rekeyed */
76607   const void *pKey, int nKey     /* The new key */
76608 );
76609
76610 /*
76611 ** CAPI3REF:  Suspend Execution For A Short Time {F10530}
76612 **
76613 ** {F10531} The sqlite3_sleep() function
76614 ** causes the current thread to suspend execution
76615 ** for at least a number of milliseconds specified in its parameter.
76616 **
76617 ** {F10532} If the operating system does not support sleep requests with 
76618 ** millisecond time resolution, then the time will be rounded up to 
76619 ** the nearest second. {F10533} The number of milliseconds of sleep actually 
76620 ** requested from the operating system is returned.
76621 **
76622 ** {F10534} SQLite implements this interface by calling the xSleep()
76623 ** method of the default [sqlite3_vfs] object. {END}
76624 */
76625 int sqlite3_sleep(int);
76626
76627 /*
76628 ** CAPI3REF:  Name Of The Folder Holding Temporary Files {F10310}
76629 **
76630 ** If this global variable is made to point to a string which is
76631 ** the name of a folder (a.ka. directory), then all temporary files
76632 ** created by SQLite will be placed in that directory.  If this variable
76633 ** is NULL pointer, then SQLite does a search for an appropriate temporary
76634 ** file directory.
76635 **
76636 ** It is not safe to modify this variable once a database connection
76637 ** has been opened.  It is intended that this variable be set once
76638 ** as part of process initialization and before any SQLite interface
76639 ** routines have been call and remain unchanged thereafter.
76640 */
76641 SQLITE_EXTERN char *sqlite3_temp_directory;
76642
76643 /*
76644 ** CAPI3REF:  Test To See If The Database Is In Auto-Commit Mode {F12930}
76645 **
76646 ** {F12931} The sqlite3_get_autocommit() interfaces returns non-zero or
76647 ** zero if the given database connection is or is not in autocommit mode,
76648 ** respectively. {F12932}  Autocommit mode is on
76649 ** by default.  {F12933} Autocommit mode is disabled by a BEGIN statement.
76650 ** {F12934} Autocommit mode is reenabled by a COMMIT or ROLLBACK. {END}
76651 **
76652 ** If certain kinds of errors occur on a statement within a multi-statement
76653 ** transactions (errors including [SQLITE_FULL], [SQLITE_IOERR], 
76654 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
76655 ** transaction might be rolled back automatically.  {F12935} The only way to
76656 ** find out if SQLite automatically rolled back the transaction after
76657 ** an error is to use this function. {END}
76658 **
76659 ** {U12936} If another thread changes the autocommit status of the database
76660 ** connection while this routine is running, then the return value
76661 ** is undefined. {END}
76662 */
76663 int sqlite3_get_autocommit(sqlite3*);
76664
76665 /*
76666 ** CAPI3REF:  Find The Database Handle Of A Prepared Statement {F13120}
76667 **
76668 ** {F13121} The sqlite3_db_handle interface
76669 ** returns the [sqlite3*] database handle to which a
76670 ** [sqlite3_stmt | prepared statement] belongs.
76671 ** {F13122} the database handle returned by sqlite3_db_handle
76672 ** is the same database handle that was
76673 ** the first argument to the [sqlite3_prepare_v2()] or its variants
76674 ** that was used to create the statement in the first place.
76675 */
76676 sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
76677
76678
76679 /*
76680 ** CAPI3REF: Commit And Rollback Notification Callbacks {F12950}
76681 **
76682 ** {F12951} The sqlite3_commit_hook() interface registers a callback
76683 ** function to be invoked whenever a transaction is committed.
76684 ** {F12952} Any callback set by a previous call to sqlite3_commit_hook()
76685 ** for the same database connection is overridden.
76686 ** {F12953} The sqlite3_rollback_hook() interface registers a callback
76687 ** function to be invoked whenever a transaction is committed.
76688 ** {F12954} Any callback set by a previous call to sqlite3_commit_hook()
76689 ** for the same database connection is overridden.
76690 ** {F12956} The pArg argument is passed through
76691 ** to the callback.  {F12957} If the callback on a commit hook function 
76692 ** returns non-zero, then the commit is converted into a rollback.
76693 **
76694 ** {F12958} If another function was previously registered, its
76695 ** pArg value is returned.  Otherwise NULL is returned.
76696 **
76697 ** {F12959} Registering a NULL function disables the callback.
76698 **
76699 ** {F12961} For the purposes of this API, a transaction is said to have been 
76700 ** rolled back if an explicit "ROLLBACK" statement is executed, or
76701 ** an error or constraint causes an implicit rollback to occur.
76702 ** {F12962} The rollback callback is not invoked if a transaction is
76703 ** automatically rolled back because the database connection is closed.
76704 ** {F12964} The rollback callback is not invoked if a transaction is
76705 ** rolled back because a commit callback returned non-zero.
76706 ** <todo> Check on this </todo> {END}
76707 **
76708 ** These are experimental interfaces and are subject to change.
76709 */
76710 void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
76711 void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
76712
76713 /*
76714 ** CAPI3REF: Data Change Notification Callbacks {F12970}
76715 **
76716 ** {F12971} The sqlite3_update_hook() interface
76717 ** registers a callback function with the database connection identified by the 
76718 ** first argument to be invoked whenever a row is updated, inserted or deleted.
76719 ** {F12972} Any callback set by a previous call to this function for the same 
76720 ** database connection is overridden.
76721 **
76722 ** {F12974} The second argument is a pointer to the function to invoke when a 
76723 ** row is updated, inserted or deleted. 
76724 ** {F12976} The first argument to the callback is
76725 ** a copy of the third argument to sqlite3_update_hook().
76726 ** {F12977} The second callback 
76727 ** argument is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
76728 ** depending on the operation that caused the callback to be invoked.
76729 ** {F12978} The third and 
76730 ** fourth arguments to the callback contain pointers to the database and 
76731 ** table name containing the affected row.
76732 ** {F12979} The final callback parameter is 
76733 ** the rowid of the row.
76734 ** {F12981} In the case of an update, this is the rowid after 
76735 ** the update takes place.
76736 **
76737 ** {F12983} The update hook is not invoked when internal system tables are
76738 ** modified (i.e. sqlite_master and sqlite_sequence).
76739 **
76740 ** {F12984} If another function was previously registered, its pArg value
76741 ** is returned.  {F12985} Otherwise NULL is returned.
76742 */
76743 void *sqlite3_update_hook(
76744   sqlite3*, 
76745   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
76746   void*
76747 );
76748
76749 /*
76750 ** CAPI3REF:  Enable Or Disable Shared Pager Cache {F10330}
76751 **
76752 ** {F10331}
76753 ** This routine enables or disables the sharing of the database cache
76754 ** and schema data structures between connections to the same database.
76755 ** {F10332}
76756 ** Sharing is enabled if the argument is true and disabled if the argument
76757 ** is false.
76758 **
76759 ** {F10333} Cache sharing is enabled and disabled
76760 ** for an entire process. {END} This is a change as of SQLite version 3.5.0.
76761 ** In prior versions of SQLite, sharing was
76762 ** enabled or disabled for each thread separately.
76763 **
76764 ** {F10334}
76765 ** The cache sharing mode set by this interface effects all subsequent
76766 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
76767 ** {F10335} Existing database connections continue use the sharing mode
76768 ** that was in effect at the time they were opened. {END}
76769 **
76770 ** Virtual tables cannot be used with a shared cache.  {F10336} When shared
76771 ** cache is enabled, the [sqlite3_create_module()] API used to register
76772 ** virtual tables will always return an error. {END}
76773 **
76774 ** {F10337} This routine returns [SQLITE_OK] if shared cache was
76775 ** enabled or disabled successfully.  {F10338} An [SQLITE_ERROR | error code]
76776 ** is returned otherwise. {END}
76777 **
76778 ** {F10339} Shared cache is disabled by default. {END} But this might change in
76779 ** future releases of SQLite.  Applications that care about shared
76780 ** cache setting should set it explicitly.
76781 */
76782 int sqlite3_enable_shared_cache(int);
76783
76784 /*
76785 ** CAPI3REF:  Attempt To Free Heap Memory {F17340}
76786 **
76787 ** {F17341} The sqlite3_release_memory() interface attempts to
76788 ** free N bytes of heap memory by deallocating non-essential memory
76789 ** allocations held by the database labrary. {END}  Memory used
76790 ** to cache database pages to improve performance is an example of
76791 ** non-essential memory.  {F16342} sqlite3_release_memory() returns
76792 ** the number of bytes actually freed, which might be more or less
76793 ** than the amount requested.
76794 */
76795 int sqlite3_release_memory(int);
76796
76797 /*
76798 ** CAPI3REF:  Impose A Limit On Heap Size {F17350}
76799 **
76800 ** {F16351} The sqlite3_soft_heap_limit() interface
76801 ** places a "soft" limit on the amount of heap memory that may be allocated
76802 ** by SQLite. {F16352} If an internal allocation is requested 
76803 ** that would exceed the soft heap limit, [sqlite3_release_memory()] is
76804 ** invoked one or more times to free up some space before the allocation
76805 ** is made. {END}
76806 **
76807 ** {F16353} The limit is called "soft", because if
76808 ** [sqlite3_release_memory()] cannot
76809 ** free sufficient memory to prevent the limit from being exceeded,
76810 ** the memory is allocated anyway and the current operation proceeds.
76811 **
76812 ** {F16354}
76813 ** A negative or zero value for N means that there is no soft heap limit and
76814 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
76815 ** {F16355} The default value for the soft heap limit is zero.
76816 **
76817 ** SQLite makes a best effort to honor the soft heap limit.  
76818 ** {F16356} But if the soft heap limit cannot honored, execution will
76819 ** continue without error or notification. {END}  This is why the limit is 
76820 ** called a "soft" limit.  It is advisory only.
76821 **
76822 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
76823 ** allocated by a single thread - the same thread in which this routine
76824 ** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
76825 ** applied to all threads. {F16357} The value specified for the soft heap limit
76826 ** is an upper bound on the total memory allocation for all threads. {END}  In
76827 ** version 3.5.0 there is no mechanism for limiting the heap usage for
76828 ** individual threads.
76829 */
76830 void sqlite3_soft_heap_limit(int);
76831
76832 /*
76833 ** CAPI3REF:  Extract Metadata About A Column Of A Table {F12850}
76834 **
76835 ** This routine
76836 ** returns meta-data about a specific column of a specific database
76837 ** table accessible using the connection handle passed as the first function 
76838 ** argument.
76839 **
76840 ** The column is identified by the second, third and fourth parameters to 
76841 ** this function. The second parameter is either the name of the database
76842 ** (i.e. "main", "temp" or an attached database) containing the specified
76843 ** table or NULL. If it is NULL, then all attached databases are searched
76844 ** for the table using the same algorithm as the database engine uses to 
76845 ** resolve unqualified table references.
76846 **
76847 ** The third and fourth parameters to this function are the table and column 
76848 ** name of the desired column, respectively. Neither of these parameters 
76849 ** may be NULL.
76850 **
76851 ** Meta information is returned by writing to the memory locations passed as
76852 ** the 5th and subsequent parameters to this function. Any of these 
76853 ** arguments may be NULL, in which case the corresponding element of meta 
76854 ** information is ommitted.
76855 **
76856 ** <pre>
76857 ** Parameter     Output Type      Description
76858 ** -----------------------------------
76859 **
76860 **   5th         const char*      Data type
76861 **   6th         const char*      Name of the default collation sequence 
76862 **   7th         int              True if the column has a NOT NULL constraint
76863 **   8th         int              True if the column is part of the PRIMARY KEY
76864 **   9th         int              True if the column is AUTOINCREMENT
76865 ** </pre>
76866 **
76867 **
76868 ** The memory pointed to by the character pointers returned for the 
76869 ** declaration type and collation sequence is valid only until the next 
76870 ** call to any sqlite API function.
76871 **
76872 ** If the specified table is actually a view, then an error is returned.
76873 **
76874 ** If the specified column is "rowid", "oid" or "_rowid_" and an 
76875 ** INTEGER PRIMARY KEY column has been explicitly declared, then the output 
76876 ** parameters are set for the explicitly declared column. If there is no
76877 ** explicitly declared IPK column, then the output parameters are set as 
76878 ** follows:
76879 **
76880 ** <pre>
76881 **     data type: "INTEGER"
76882 **     collation sequence: "BINARY"
76883 **     not null: 0
76884 **     primary key: 1
76885 **     auto increment: 0
76886 ** </pre>
76887 **
76888 ** This function may load one or more schemas from database files. If an
76889 ** error occurs during this process, or if the requested table or column
76890 ** cannot be found, an SQLITE error code is returned and an error message
76891 ** left in the database handle (to be retrieved using sqlite3_errmsg()).
76892 **
76893 ** This API is only available if the library was compiled with the
76894 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
76895 */
76896 int sqlite3_table_column_metadata(
76897   sqlite3 *db,                /* Connection handle */
76898   const char *zDbName,        /* Database name or NULL */
76899   const char *zTableName,     /* Table name */
76900   const char *zColumnName,    /* Column name */
76901   char const **pzDataType,    /* OUTPUT: Declared data type */
76902   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
76903   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
76904   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
76905   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
76906 );
76907
76908 /*
76909 ** CAPI3REF: Load An Extension {F12600}
76910 **
76911 ** {F12601} The sqlite3_load_extension() interface
76912 ** attempts to load an SQLite extension library contained in the file
76913 ** zFile. {F12602} The entry point is zProc. {F12603} zProc may be 0
76914 ** in which case the name of the entry point defaults
76915 ** to "sqlite3_extension_init".
76916 **
76917 ** {F12604} The sqlite3_load_extension() interface shall
76918 ** return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
76919 **
76920 ** {F12605}
76921 ** If an error occurs and pzErrMsg is not 0, then the
76922 ** sqlite3_load_extension() interface shall attempt to fill *pzErrMsg with 
76923 ** error message text stored in memory obtained from [sqlite3_malloc()].
76924 ** {END}  The calling function should free this memory
76925 ** by calling [sqlite3_free()].
76926 **
76927 ** {F12606}
76928 ** Extension loading must be enabled using [sqlite3_enable_load_extension()]
76929 ** prior to calling this API or an error will be returned.
76930 */
76931 int sqlite3_load_extension(
76932   sqlite3 *db,          /* Load the extension into this database connection */
76933   const char *zFile,    /* Name of the shared library containing extension */
76934   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
76935   char **pzErrMsg       /* Put error message here if not 0 */
76936 );
76937
76938 /*
76939 ** CAPI3REF:  Enable Or Disable Extension Loading {F12620}
76940 **
76941 ** So as not to open security holes in older applications that are
76942 ** unprepared to deal with extension loading, and as a means of disabling
76943 ** extension loading while evaluating user-entered SQL, the following
76944 ** API is provided to turn the [sqlite3_load_extension()] mechanism on and
76945 ** off.  {F12622} It is off by default. {END} See ticket #1863.
76946 **
76947 ** {F12621} Call the sqlite3_enable_load_extension() routine
76948 ** with onoff==1 to turn extension loading on
76949 ** and call it with onoff==0 to turn it back off again. {END}
76950 */
76951 int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
76952
76953 /*
76954 ** CAPI3REF: Make Arrangements To Automatically Load An Extension {F12640}
76955 **
76956 ** {F12641} This function
76957 ** registers an extension entry point that is automatically invoked
76958 ** whenever a new database connection is opened using
76959 ** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. {END}
76960 **
76961 ** This API can be invoked at program startup in order to register
76962 ** one or more statically linked extensions that will be available
76963 ** to all new database connections.
76964 **
76965 ** {F12642} Duplicate extensions are detected so calling this routine multiple
76966 ** times with the same extension is harmless.
76967 **
76968 ** {F12643} This routine stores a pointer to the extension in an array
76969 ** that is obtained from sqlite_malloc(). {END} If you run a memory leak
76970 ** checker on your program and it reports a leak because of this
76971 ** array, then invoke [sqlite3_reset_auto_extension()] prior
76972 ** to shutdown to free the memory.
76973 **
76974 ** {F12644} Automatic extensions apply across all threads. {END}
76975 **
76976 ** This interface is experimental and is subject to change or
76977 ** removal in future releases of SQLite.
76978 */
76979 int sqlite3_auto_extension(void *xEntryPoint);
76980
76981
76982 /*
76983 ** CAPI3REF: Reset Automatic Extension Loading {F12660}
76984 **
76985 ** {F12661} This function disables all previously registered
76986 ** automatic extensions. {END}  This
76987 ** routine undoes the effect of all prior [sqlite3_automatic_extension()]
76988 ** calls.
76989 **
76990 ** {F12662} This call disabled automatic extensions in all threads. {END}
76991 **
76992 ** This interface is experimental and is subject to change or
76993 ** removal in future releases of SQLite.
76994 */
76995 void sqlite3_reset_auto_extension(void);
76996
76997
76998 /*
76999 ****** EXPERIMENTAL - subject to change without notice **************
77000 **
77001 ** The interface to the virtual-table mechanism is currently considered
77002 ** to be experimental.  The interface might change in incompatible ways.
77003 ** If this is a problem for you, do not use the interface at this time.
77004 **
77005 ** When the virtual-table mechanism stablizes, we will declare the
77006 ** interface fixed, support it indefinitely, and remove this comment.
77007 */
77008
77009 /*
77010 ** Structures used by the virtual table interface
77011 */
77012 typedef struct sqlite3_vtab sqlite3_vtab;
77013 typedef struct sqlite3_index_info sqlite3_index_info;
77014 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
77015 typedef struct sqlite3_module sqlite3_module;
77016
77017 /*
77018 ** A module is a class of virtual tables.  Each module is defined
77019 ** by an instance of the following structure.  This structure consists
77020 ** mostly of methods for the module.
77021 */
77022 struct sqlite3_module {
77023   int iVersion;
77024   int (*xCreate)(sqlite3*, void *pAux,
77025                int argc, const char *const*argv,
77026                sqlite3_vtab **ppVTab, char**);
77027   int (*xConnect)(sqlite3*, void *pAux,
77028                int argc, const char *const*argv,
77029                sqlite3_vtab **ppVTab, char**);
77030   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
77031   int (*xDisconnect)(sqlite3_vtab *pVTab);
77032   int (*xDestroy)(sqlite3_vtab *pVTab);
77033   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
77034   int (*xClose)(sqlite3_vtab_cursor*);
77035   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
77036                 int argc, sqlite3_value **argv);
77037   int (*xNext)(sqlite3_vtab_cursor*);
77038   int (*xEof)(sqlite3_vtab_cursor*);
77039   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
77040   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
77041   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
77042   int (*xBegin)(sqlite3_vtab *pVTab);
77043   int (*xSync)(sqlite3_vtab *pVTab);
77044   int (*xCommit)(sqlite3_vtab *pVTab);
77045   int (*xRollback)(sqlite3_vtab *pVTab);
77046   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
77047                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
77048                        void **ppArg);
77049
77050   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
77051 };
77052
77053 /*
77054 ** The sqlite3_index_info structure and its substructures is used to
77055 ** pass information into and receive the reply from the xBestIndex
77056 ** method of an sqlite3_module.  The fields under **Inputs** are the
77057 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
77058 ** results into the **Outputs** fields.
77059 **
77060 ** The aConstraint[] array records WHERE clause constraints of the
77061 ** form:
77062 **
77063 **         column OP expr
77064 **
77065 ** Where OP is =, &lt;, &lt;=, &gt;, or &gt;=.  
77066 ** The particular operator is stored
77067 ** in aConstraint[].op.  The index of the column is stored in 
77068 ** aConstraint[].iColumn.  aConstraint[].usable is TRUE if the
77069 ** expr on the right-hand side can be evaluated (and thus the constraint
77070 ** is usable) and false if it cannot.
77071 **
77072 ** The optimizer automatically inverts terms of the form "expr OP column"
77073 ** and makes other simplifications to the WHERE clause in an attempt to
77074 ** get as many WHERE clause terms into the form shown above as possible.
77075 ** The aConstraint[] array only reports WHERE clause terms in the correct
77076 ** form that refer to the particular virtual table being queried.
77077 **
77078 ** Information about the ORDER BY clause is stored in aOrderBy[].
77079 ** Each term of aOrderBy records a column of the ORDER BY clause.
77080 **
77081 ** The xBestIndex method must fill aConstraintUsage[] with information
77082 ** about what parameters to pass to xFilter.  If argvIndex>0 then
77083 ** the right-hand side of the corresponding aConstraint[] is evaluated
77084 ** and becomes the argvIndex-th entry in argv.  If aConstraintUsage[].omit
77085 ** is true, then the constraint is assumed to be fully handled by the
77086 ** virtual table and is not checked again by SQLite.
77087 **
77088 ** The idxNum and idxPtr values are recorded and passed into xFilter.
77089 ** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
77090 **
77091 ** The orderByConsumed means that output from xFilter will occur in
77092 ** the correct order to satisfy the ORDER BY clause so that no separate
77093 ** sorting step is required.
77094 **
77095 ** The estimatedCost value is an estimate of the cost of doing the
77096 ** particular lookup.  A full scan of a table with N entries should have
77097 ** a cost of N.  A binary search of a table of N entries should have a
77098 ** cost of approximately log(N).
77099 */
77100 struct sqlite3_index_info {
77101   /* Inputs */
77102   int nConstraint;           /* Number of entries in aConstraint */
77103   struct sqlite3_index_constraint {
77104      int iColumn;              /* Column on left-hand side of constraint */
77105      unsigned char op;         /* Constraint operator */
77106      unsigned char usable;     /* True if this constraint is usable */
77107      int iTermOffset;          /* Used internally - xBestIndex should ignore */
77108   } *aConstraint;            /* Table of WHERE clause constraints */
77109   int nOrderBy;              /* Number of terms in the ORDER BY clause */
77110   struct sqlite3_index_orderby {
77111      int iColumn;              /* Column number */
77112      unsigned char desc;       /* True for DESC.  False for ASC. */
77113   } *aOrderBy;               /* The ORDER BY clause */
77114
77115   /* Outputs */
77116   struct sqlite3_index_constraint_usage {
77117     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
77118     unsigned char omit;      /* Do not code a test for this constraint */
77119   } *aConstraintUsage;
77120   int idxNum;                /* Number used to identify the index */
77121   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
77122   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
77123   int orderByConsumed;       /* True if output is already ordered */
77124   double estimatedCost;      /* Estimated cost of using this index */
77125 };
77126 #define SQLITE_INDEX_CONSTRAINT_EQ    2
77127 #define SQLITE_INDEX_CONSTRAINT_GT    4
77128 #define SQLITE_INDEX_CONSTRAINT_LE    8
77129 #define SQLITE_INDEX_CONSTRAINT_LT    16
77130 #define SQLITE_INDEX_CONSTRAINT_GE    32
77131 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
77132
77133 /*
77134 ** This routine is used to register a new module name with an SQLite
77135 ** connection.  Module names must be registered before creating new
77136 ** virtual tables on the module, or before using preexisting virtual
77137 ** tables of the module.
77138 */
77139 int sqlite3_create_module(
77140   sqlite3 *db,               /* SQLite connection to register module with */
77141   const char *zName,         /* Name of the module */
77142   const sqlite3_module *,    /* Methods for the module */
77143   void *                     /* Client data for xCreate/xConnect */
77144 );
77145
77146 /*
77147 ** This routine is identical to the sqlite3_create_module() method above,
77148 ** except that it allows a destructor function to be specified. It is
77149 ** even more experimental than the rest of the virtual tables API.
77150 */
77151 int sqlite3_create_module_v2(
77152   sqlite3 *db,               /* SQLite connection to register module with */
77153   const char *zName,         /* Name of the module */
77154   const sqlite3_module *,    /* Methods for the module */
77155   void *,                    /* Client data for xCreate/xConnect */
77156   void(*xDestroy)(void*)     /* Module destructor function */
77157 );
77158
77159 /*
77160 ** Every module implementation uses a subclass of the following structure
77161 ** to describe a particular instance of the module.  Each subclass will
77162 ** be tailored to the specific needs of the module implementation.   The
77163 ** purpose of this superclass is to define certain fields that are common
77164 ** to all module implementations.
77165 **
77166 ** Virtual tables methods can set an error message by assigning a
77167 ** string obtained from sqlite3_mprintf() to zErrMsg.  The method should
77168 ** take care that any prior string is freed by a call to sqlite3_free()
77169 ** prior to assigning a new string to zErrMsg.  After the error message
77170 ** is delivered up to the client application, the string will be automatically
77171 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.  Note
77172 ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
77173 ** since virtual tables are commonly implemented in loadable extensions which
77174 ** do not have access to sqlite3MPrintf() or sqlite3Free().
77175 */
77176 struct sqlite3_vtab {
77177   const sqlite3_module *pModule;  /* The module for this virtual table */
77178   int nRef;                       /* Used internally */
77179   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
77180   /* Virtual table implementations will typically add additional fields */
77181 };
77182
77183 /* Every module implementation uses a subclass of the following structure
77184 ** to describe cursors that point into the virtual table and are used
77185 ** to loop through the virtual table.  Cursors are created using the
77186 ** xOpen method of the module.  Each module implementation will define
77187 ** the content of a cursor structure to suit its own needs.
77188 **
77189 ** This superclass exists in order to define fields of the cursor that
77190 ** are common to all implementations.
77191 */
77192 struct sqlite3_vtab_cursor {
77193   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
77194   /* Virtual table implementations will typically add additional fields */
77195 };
77196
77197 /*
77198 ** The xCreate and xConnect methods of a module use the following API
77199 ** to declare the format (the names and datatypes of the columns) of
77200 ** the virtual tables they implement.
77201 */
77202 int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
77203
77204 /*
77205 ** Virtual tables can provide alternative implementations of functions
77206 ** using the xFindFunction method.  But global versions of those functions
77207 ** must exist in order to be overloaded.
77208 **
77209 ** This API makes sure a global version of a function with a particular
77210 ** name and number of parameters exists.  If no such function exists
77211 ** before this API is called, a new function is created.  The implementation
77212 ** of the new function always causes an exception to be thrown.  So
77213 ** the new function is not good for anything by itself.  Its only
77214 ** purpose is to be a place-holder function that can be overloaded
77215 ** by virtual tables.
77216 **
77217 ** This API should be considered part of the virtual table interface,
77218 ** which is experimental and subject to change.
77219 */
77220 int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
77221
77222 /*
77223 ** The interface to the virtual-table mechanism defined above (back up
77224 ** to a comment remarkably similar to this one) is currently considered
77225 ** to be experimental.  The interface might change in incompatible ways.
77226 ** If this is a problem for you, do not use the interface at this time.
77227 **
77228 ** When the virtual-table mechanism stabilizes, we will declare the
77229 ** interface fixed, support it indefinitely, and remove this comment.
77230 **
77231 ****** EXPERIMENTAL - subject to change without notice **************
77232 */
77233
77234 /*
77235 ** CAPI3REF: A Handle To An Open BLOB {F17800}
77236 **
77237 ** An instance of the following opaque structure is used to 
77238 ** represent an blob-handle.  A blob-handle is created by
77239 ** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()].
77240 ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
77241 ** can be used to read or write small subsections of the blob.
77242 ** The [sqlite3_blob_bytes()] interface returns the size of the
77243 ** blob in bytes.
77244 */
77245 typedef struct sqlite3_blob sqlite3_blob;
77246
77247 /*
77248 ** CAPI3REF: Open A BLOB For Incremental I/O {F17810}
77249 **
77250 ** {F17811} This interfaces opens a handle to the blob located
77251 ** in row iRow,, column zColumn, table zTable in database zDb;
77252 ** in other words,  the same blob that would be selected by:
77253 **
77254 ** <pre>
77255 **     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
77256 ** </pre> {END}
77257 **
77258 ** {F17812} If the flags parameter is non-zero, the blob is opened for 
77259 ** read and write access. If it is zero, the blob is opened for read 
77260 ** access. {END}
77261 **
77262 ** {F17813} On success, [SQLITE_OK] is returned and the new 
77263 ** [sqlite3_blob | blob handle] is written to *ppBlob. 
77264 ** {F17814} Otherwise an error code is returned and 
77265 ** any value written to *ppBlob should not be used by the caller.
77266 ** {F17815} This function sets the database-handle error code and message
77267 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()].
77268 ** <todo>We should go through and mark all interfaces that behave this
77269 ** way with a similar statement</todo>
77270 */
77271 int sqlite3_blob_open(
77272   sqlite3*,
77273   const char *zDb,
77274   const char *zTable,
77275   const char *zColumn,
77276   sqlite3_int64 iRow,
77277   int flags,
77278   sqlite3_blob **ppBlob
77279 );
77280
77281 /*
77282 ** CAPI3REF:  Close A BLOB Handle {F17830}
77283 **
77284 ** Close an open [sqlite3_blob | blob handle].
77285 **
77286 ** {F17831} Closing a BLOB shall cause the current transaction to commit
77287 ** if there are no other BLOBs, no pending prepared statements, and the
77288 ** database connection is in autocommit mode.
77289 ** {F17832} If any writes were made to the BLOB, they might be held in cache
77290 ** until the close operation if they will fit. {END}
77291 ** Closing the BLOB often forces the changes
77292 ** out to disk and so if any I/O errors occur, they will likely occur
77293 ** at the time when the BLOB is closed.  {F17833} Any errors that occur during
77294 ** closing are reported as a non-zero return value.
77295 **
77296 ** {F17839} The BLOB is closed unconditionally.  Even if this routine returns
77297 ** an error code, the BLOB is still closed.
77298 */
77299 int sqlite3_blob_close(sqlite3_blob *);
77300
77301 /*
77302 ** CAPI3REF:  Return The Size Of An Open BLOB {F17805}
77303 **
77304 ** {F16806} Return the size in bytes of the blob accessible via the open 
77305 ** [sqlite3_blob | blob-handle] passed as an argument.
77306 */
77307 int sqlite3_blob_bytes(sqlite3_blob *);
77308
77309 /*
77310 ** CAPI3REF:  Read Data From A BLOB Incrementally {F17850}
77311 **
77312 ** This function is used to read data from an open 
77313 ** [sqlite3_blob | blob-handle] into a caller supplied buffer.
77314 ** {F17851} n bytes of data are copied into buffer
77315 ** z from the open blob, starting at offset iOffset.
77316 **
77317 ** {F17852} If offset iOffset is less than n bytes from the end of the blob, 
77318 ** [SQLITE_ERROR] is returned and no data is read.  {F17853} If n is
77319 ** less than zero [SQLITE_ERROR] is returned and no data is read.
77320 **
77321 ** {F17854} On success, SQLITE_OK is returned. Otherwise, an 
77322 ** [SQLITE_ERROR | SQLite error code] or an
77323 ** [SQLITE_IOERR_READ | extended error code] is returned.
77324 */
77325 int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset);
77326
77327 /*
77328 ** CAPI3REF:  Write Data Into A BLOB Incrementally {F17870}
77329 **
77330 ** This function is used to write data into an open 
77331 ** [sqlite3_blob | blob-handle] from a user supplied buffer.
77332 ** {F17871} n bytes of data are copied from the buffer
77333 ** pointed to by z into the open blob, starting at offset iOffset.
77334 **
77335 ** {F17872} If the [sqlite3_blob | blob-handle] passed as the first argument
77336 ** was not opened for writing (the flags parameter to [sqlite3_blob_open()]
77337 *** was zero), this function returns [SQLITE_READONLY].
77338 **
77339 ** {F17873} This function may only modify the contents of the blob; it is
77340 ** not possible to increase the size of a blob using this API.
77341 ** {F17874} If offset iOffset is less than n bytes from the end of the blob, 
77342 ** [SQLITE_ERROR] is returned and no data is written.  {F17875} If n is
77343 ** less than zero [SQLITE_ERROR] is returned and no data is written.
77344 **
77345 ** {F17876} On success, SQLITE_OK is returned. Otherwise, an 
77346 ** [SQLITE_ERROR | SQLite error code] or an
77347 ** [SQLITE_IOERR_READ | extended error code] is returned.
77348 */
77349 int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
77350
77351 /*
77352 ** CAPI3REF:  Virtual File System Objects {F11200}
77353 **
77354 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
77355 ** that SQLite uses to interact
77356 ** with the underlying operating system.  Most builds come with a
77357 ** single default VFS that is appropriate for the host computer.
77358 ** New VFSes can be registered and existing VFSes can be unregistered.
77359 ** The following interfaces are provided.
77360 **
77361 ** {F11201} The sqlite3_vfs_find() interface returns a pointer to 
77362 ** a VFS given its name.  {F11202} Names are case sensitive.
77363 ** {F11203} Names are zero-terminated UTF-8 strings.
77364 ** {F11204} If there is no match, a NULL
77365 ** pointer is returned. {F11205} If zVfsName is NULL then the default 
77366 ** VFS is returned. {END}
77367 **
77368 ** {F11210} New VFSes are registered with sqlite3_vfs_register().
77369 ** {F11211} Each new VFS becomes the default VFS if the makeDflt flag is set.
77370 ** {F11212} The same VFS can be registered multiple times without injury.
77371 ** {F11213} To make an existing VFS into the default VFS, register it again
77372 ** with the makeDflt flag set. {U11214} If two different VFSes with the
77373 ** same name are registered, the behavior is undefined.  {U11215} If a
77374 ** VFS is registered with a name that is NULL or an empty string,
77375 ** then the behavior is undefined.
77376 ** 
77377 ** {F11220} Unregister a VFS with the sqlite3_vfs_unregister() interface.
77378 ** {F11221} If the default VFS is unregistered, another VFS is chosen as
77379 ** the default.  The choice for the new VFS is arbitrary.
77380 */
77381 sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
77382 int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
77383 int sqlite3_vfs_unregister(sqlite3_vfs*);
77384
77385 /*
77386 ** CAPI3REF: Mutexes {F17000}
77387 **
77388 ** The SQLite core uses these routines for thread
77389 ** synchronization.  Though they are intended for internal
77390 ** use by SQLite, code that links against SQLite is
77391 ** permitted to use any of these routines.
77392 **
77393 ** The SQLite source code contains multiple implementations 
77394 ** of these mutex routines.  An appropriate implementation
77395 ** is selected automatically at compile-time.  The following
77396 ** implementations are available in the SQLite core:
77397 **
77398 ** <ul>
77399 ** <li>   SQLITE_MUTEX_OS2
77400 ** <li>   SQLITE_MUTEX_PTHREAD
77401 ** <li>   SQLITE_MUTEX_W32
77402 ** <li>   SQLITE_MUTEX_NOOP
77403 ** </ul>
77404 **
77405 ** The SQLITE_MUTEX_NOOP implementation is a set of routines 
77406 ** that does no real locking and is appropriate for use in 
77407 ** a single-threaded application.  The SQLITE_MUTEX_OS2,
77408 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
77409 ** are appropriate for use on os/2, unix, and windows.
77410 ** 
77411 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
77412 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
77413 ** implementation is included with the library.  The
77414 ** mutex interface routines defined here become external
77415 ** references in the SQLite library for which implementations
77416 ** must be provided by the application.  This facility allows an
77417 ** application that links against SQLite to provide its own mutex
77418 ** implementation without having to modify the SQLite core.
77419 **
77420 ** {F17011} The sqlite3_mutex_alloc() routine allocates a new
77421 ** mutex and returns a pointer to it. {F17012} If it returns NULL
77422 ** that means that a mutex could not be allocated. {F17013} SQLite
77423 ** will unwind its stack and return an error. {F17014} The argument
77424 ** to sqlite3_mutex_alloc() is one of these integer constants:
77425 **
77426 ** <ul>
77427 ** <li>  SQLITE_MUTEX_FAST
77428 ** <li>  SQLITE_MUTEX_RECURSIVE
77429 ** <li>  SQLITE_MUTEX_STATIC_MASTER
77430 ** <li>  SQLITE_MUTEX_STATIC_MEM
77431 ** <li>  SQLITE_MUTEX_STATIC_MEM2
77432 ** <li>  SQLITE_MUTEX_STATIC_PRNG
77433 ** <li>  SQLITE_MUTEX_STATIC_LRU
77434 ** </ul> {END}
77435 **
77436 ** {F17015} The first two constants cause sqlite3_mutex_alloc() to create
77437 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
77438 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END}
77439 ** The mutex implementation does not need to make a distinction
77440 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
77441 ** not want to.  {F17016} But SQLite will only request a recursive mutex in
77442 ** cases where it really needs one.  {END} If a faster non-recursive mutex
77443 ** implementation is available on the host platform, the mutex subsystem
77444 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
77445 **
77446 ** {F17017} The other allowed parameters to sqlite3_mutex_alloc() each return
77447 ** a pointer to a static preexisting mutex. {END}  Four static mutexes are
77448 ** used by the current version of SQLite.  Future versions of SQLite
77449 ** may add additional static mutexes.  Static mutexes are for internal
77450 ** use by SQLite only.  Applications that use SQLite mutexes should
77451 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
77452 ** SQLITE_MUTEX_RECURSIVE.
77453 **
77454 ** {F17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
77455 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
77456 ** returns a different mutex on every call.  {F17034} But for the static 
77457 ** mutex types, the same mutex is returned on every call that has
77458 ** the same type number. {END}
77459 **
77460 ** {F17019} The sqlite3_mutex_free() routine deallocates a previously
77461 ** allocated dynamic mutex. {F17020} SQLite is careful to deallocate every
77462 ** dynamic mutex that it allocates. {U17021} The dynamic mutexes must not be in 
77463 ** use when they are deallocated. {U17022} Attempting to deallocate a static
77464 ** mutex results in undefined behavior. {F17023} SQLite never deallocates
77465 ** a static mutex. {END}
77466 **
77467 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
77468 ** to enter a mutex. {F17024} If another thread is already within the mutex,
77469 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
77470 ** SQLITE_BUSY. {F17025}  The sqlite3_mutex_try() interface returns SQLITE_OK
77471 ** upon successful entry.  {F17026} Mutexes created using
77472 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
77473 ** {F17027} In such cases the,
77474 ** mutex must be exited an equal number of times before another thread
77475 ** can enter.  {U17028} If the same thread tries to enter any other
77476 ** kind of mutex more than once, the behavior is undefined.
77477 ** {F17029} SQLite will never exhibit
77478 ** such behavior in its own use of mutexes. {END}
77479 **
77480 ** Some systems (ex: windows95) do not the operation implemented by
77481 ** sqlite3_mutex_try().  On those systems, sqlite3_mutex_try() will
77482 ** always return SQLITE_BUSY.  {F17030} The SQLite core only ever uses
77483 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior. {END}
77484 **
77485 ** {F17031} The sqlite3_mutex_leave() routine exits a mutex that was
77486 ** previously entered by the same thread.  {U17032} The behavior
77487 ** is undefined if the mutex is not currently entered by the
77488 ** calling thread or is not currently allocated.  {F17033} SQLite will
77489 ** never do either. {END}
77490 **
77491 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
77492 */
77493 sqlite3_mutex *sqlite3_mutex_alloc(int);
77494 void sqlite3_mutex_free(sqlite3_mutex*);
77495 void sqlite3_mutex_enter(sqlite3_mutex*);
77496 int sqlite3_mutex_try(sqlite3_mutex*);
77497 void sqlite3_mutex_leave(sqlite3_mutex*);
77498
77499 /*
77500 ** CAPI3REF: Mutex Verifcation Routines {F17080}
77501 **
77502 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
77503 ** are intended for use inside assert() statements. {F17081} The SQLite core
77504 ** never uses these routines except inside an assert() and applications
77505 ** are advised to follow the lead of the core.  {F17082} The core only
77506 ** provides implementations for these routines when it is compiled
77507 ** with the SQLITE_DEBUG flag.  {U17087} External mutex implementations
77508 ** are only required to provide these routines if SQLITE_DEBUG is
77509 ** defined and if NDEBUG is not defined.
77510 **
77511 ** {F17083} These routines should return true if the mutex in their argument
77512 ** is held or not held, respectively, by the calling thread. {END}
77513 **
77514 ** {X17084} The implementation is not required to provided versions of these
77515 ** routines that actually work.
77516 ** If the implementation does not provide working
77517 ** versions of these routines, it should at least provide stubs
77518 ** that always return true so that one does not get spurious
77519 ** assertion failures. {END}
77520 **
77521 ** {F17085} If the argument to sqlite3_mutex_held() is a NULL pointer then
77522 ** the routine should return 1.  {END} This seems counter-intuitive since
77523 ** clearly the mutex cannot be held if it does not exist.  But the
77524 ** the reason the mutex does not exist is because the build is not
77525 ** using mutexes.  And we do not want the assert() containing the
77526 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
77527 ** the appropriate thing to do.  {F17086} The sqlite3_mutex_notheld() 
77528 ** interface should also return 1 when given a NULL pointer.
77529 */
77530 int sqlite3_mutex_held(sqlite3_mutex*);
77531 int sqlite3_mutex_notheld(sqlite3_mutex*);
77532
77533 /*
77534 ** CAPI3REF: Mutex Types {F17001}
77535 **
77536 ** {F17002} The [sqlite3_mutex_alloc()] interface takes a single argument
77537 ** which is one of these integer constants. {END}
77538 */
77539 #define SQLITE_MUTEX_FAST             0
77540 #define SQLITE_MUTEX_RECURSIVE        1
77541 #define SQLITE_MUTEX_STATIC_MASTER    2
77542 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
77543 #define SQLITE_MUTEX_STATIC_MEM2      4  /* sqlite3_release_memory() */
77544 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
77545 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
77546
77547 /*
77548 ** CAPI3REF: Low-Level Control Of Database Files {F11300}
77549 **
77550 ** {F11301} The [sqlite3_file_control()] interface makes a direct call to the
77551 ** xFileControl method for the [sqlite3_io_methods] object associated
77552 ** with a particular database identified by the second argument. {F11302} The
77553 ** name of the database is the name assigned to the database by the
77554 ** <a href="lang_attach.html">ATTACH</a> SQL command that opened the
77555 ** database. {F11303} To control the main database file, use the name "main"
77556 ** or a NULL pointer. {F11304} The third and fourth parameters to this routine
77557 ** are passed directly through to the second and third parameters of
77558 ** the xFileControl method.  {F11305} The return value of the xFileControl
77559 ** method becomes the return value of this routine.
77560 **
77561 ** {F11306} If the second parameter (zDbName) does not match the name of any
77562 ** open database file, then SQLITE_ERROR is returned. {F11307} This error
77563 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
77564 ** or [sqlite3_errmsg()]. {U11308} The underlying xFileControl method might
77565 ** also return SQLITE_ERROR.  {U11309} There is no way to distinguish between
77566 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
77567 ** xFileControl method. {END}
77568 **
77569 ** See also: [SQLITE_FCNTL_LOCKSTATE]
77570 */
77571 int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
77572
77573 /*
77574 ** Undo the hack that converts floating point types to integer for
77575 ** builds on processors without floating point support.
77576 */
77577 #ifdef SQLITE_OMIT_FLOATING_POINT
77578 # undef double
77579 #endif
77580
77581 #if 0
77582 }  /* End of the 'extern "C"' block */
77583 #endif
77584 #endif
77585
77586 /************** End of sqlite3.h *********************************************/
77587 /************** Continuing where we left off in fts3.h ***********************/
77588
77589 #if 0
77590 extern "C" {
77591 #endif  /* __cplusplus */
77592
77593 int sqlite3Fts3Init(sqlite3 *db);
77594
77595 #if 0
77596 }  /* extern "C" */
77597 #endif  /* __cplusplus */
77598
77599 /************** End of fts3.h ************************************************/
77600 /************** Continuing where we left off in fts3.c ***********************/
77601 /************** Include fts3_hash.h in the middle of fts3.c ******************/
77602 /************** Begin file fts3_hash.h ***************************************/
77603 /*
77604 ** 2001 September 22
77605 **
77606 ** The author disclaims copyright to this source code.  In place of
77607 ** a legal notice, here is a blessing:
77608 **
77609 **    May you do good and not evil.
77610 **    May you find forgiveness for yourself and forgive others.
77611 **    May you share freely, never taking more than you give.
77612 **
77613 *************************************************************************
77614 ** This is the header file for the generic hash-table implemenation
77615 ** used in SQLite.  We've modified it slightly to serve as a standalone
77616 ** hash table implementation for the full-text indexing module.
77617 **
77618 */
77619 #ifndef _FTS3_HASH_H_
77620 #define _FTS3_HASH_H_
77621
77622 /* Forward declarations of structures. */
77623 typedef struct fts3Hash fts3Hash;
77624 typedef struct fts3HashElem fts3HashElem;
77625
77626 /* A complete hash table is an instance of the following structure.
77627 ** The internals of this structure are intended to be opaque -- client
77628 ** code should not attempt to access or modify the fields of this structure
77629 ** directly.  Change this structure only by using the routines below.
77630 ** However, many of the "procedures" and "functions" for modifying and
77631 ** accessing this structure are really macros, so we can't really make
77632 ** this structure opaque.
77633 */
77634 struct fts3Hash {
77635   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
77636   char copyKey;           /* True if copy of key made on insert */
77637   int count;              /* Number of entries in this table */
77638   fts3HashElem *first;    /* The first element of the array */
77639   int htsize;             /* Number of buckets in the hash table */
77640   struct _fts3ht {        /* the hash table */
77641     int count;               /* Number of entries with this hash */
77642     fts3HashElem *chain;     /* Pointer to first entry with this hash */
77643   } *ht;
77644 };
77645
77646 /* Each element in the hash table is an instance of the following 
77647 ** structure.  All elements are stored on a single doubly-linked list.
77648 **
77649 ** Again, this structure is intended to be opaque, but it can't really
77650 ** be opaque because it is used by macros.
77651 */
77652 struct fts3HashElem {
77653   fts3HashElem *next, *prev; /* Next and previous elements in the table */
77654   void *data;                /* Data associated with this element */
77655   void *pKey; int nKey;      /* Key associated with this element */
77656 };
77657
77658 /*
77659 ** There are 2 different modes of operation for a hash table:
77660 **
77661 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
77662 **                           (including the null-terminator, if any).  Case
77663 **                           is respected in comparisons.
77664 **
77665 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
77666 **                           memcmp() is used to compare keys.
77667 **
77668 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
77669 */
77670 #define FTS3_HASH_STRING    1
77671 #define FTS3_HASH_BINARY    2
77672
77673 /*
77674 ** Access routines.  To delete, insert a NULL pointer.
77675 */
77676 void sqlite3Fts3HashInit(fts3Hash*, int keytype, int copyKey);
77677 void *sqlite3Fts3HashInsert(fts3Hash*, const void *pKey, int nKey, void *pData);
77678 void *sqlite3Fts3HashFind(const fts3Hash*, const void *pKey, int nKey);
77679 void sqlite3Fts3HashClear(fts3Hash*);
77680
77681 /*
77682 ** Shorthand for the functions above
77683 */
77684 #define fts3HashInit   sqlite3Fts3HashInit
77685 #define fts3HashInsert sqlite3Fts3HashInsert
77686 #define fts3HashFind   sqlite3Fts3HashFind
77687 #define fts3HashClear  sqlite3Fts3HashClear
77688
77689 /*
77690 ** Macros for looping over all elements of a hash table.  The idiom is
77691 ** like this:
77692 **
77693 **   fts3Hash h;
77694 **   fts3HashElem *p;
77695 **   ...
77696 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
77697 **     SomeStructure *pData = fts3HashData(p);
77698 **     // do something with pData
77699 **   }
77700 */
77701 #define fts3HashFirst(H)  ((H)->first)
77702 #define fts3HashNext(E)   ((E)->next)
77703 #define fts3HashData(E)   ((E)->data)
77704 #define fts3HashKey(E)    ((E)->pKey)
77705 #define fts3HashKeysize(E) ((E)->nKey)
77706
77707 /*
77708 ** Number of entries in a hash table
77709 */
77710 #define fts3HashCount(H)  ((H)->count)
77711
77712 #endif /* _FTS3_HASH_H_ */
77713
77714 /************** End of fts3_hash.h *******************************************/
77715 /************** Continuing where we left off in fts3.c ***********************/
77716 /************** Include fts3_tokenizer.h in the middle of fts3.c *************/
77717 /************** Begin file fts3_tokenizer.h **********************************/
77718 /*
77719 ** 2006 July 10
77720 **
77721 ** The author disclaims copyright to this source code.
77722 **
77723 *************************************************************************
77724 ** Defines the interface to tokenizers used by fulltext-search.  There
77725 ** are three basic components:
77726 **
77727 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
77728 ** interface functions.  This is essentially the class structure for
77729 ** tokenizers.
77730 **
77731 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
77732 ** including customization information defined at creation time.
77733 **
77734 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
77735 ** tokens from a particular input.
77736 */
77737 #ifndef _FTS3_TOKENIZER_H_
77738 #define _FTS3_TOKENIZER_H_
77739
77740 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
77741 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
77742 ** we will need a way to register the API consistently.
77743 */
77744 /************** Include sqlite3.h in the middle of fts3_tokenizer.h **********/
77745 /************** Begin file sqlite3.h *****************************************/
77746 /*
77747 ** 2001 September 15
77748 **
77749 ** The author disclaims copyright to this source code.  In place of
77750 ** a legal notice, here is a blessing:
77751 **
77752 **    May you do good and not evil.
77753 **    May you find forgiveness for yourself and forgive others.
77754 **    May you share freely, never taking more than you give.
77755 **
77756 *************************************************************************
77757 ** This header file defines the interface that the SQLite library
77758 ** presents to client programs.  If a C-function, structure, datatype,
77759 ** or constant definition does not appear in this file, then it is
77760 ** not a published API of SQLite, is subject to change without
77761 ** notice, and should not be referenced by programs that use SQLite.
77762 **
77763 ** Some of the definitions that are in this file are marked as
77764 ** "experimental".  Experimental interfaces are normally new
77765 ** features recently added to SQLite.  We do not anticipate changes 
77766 ** to experimental interfaces but reserve to make minor changes if
77767 ** experience from use "in the wild" suggest such changes are prudent.
77768 **
77769 ** The official C-language API documentation for SQLite is derived
77770 ** from comments in this file.  This file is the authoritative source
77771 ** on how SQLite interfaces are suppose to operate.
77772 **
77773 ** The name of this file under configuration management is "sqlite.h.in".
77774 ** The makefile makes some minor changes to this file (such as inserting
77775 ** the version number) and changes its name to "sqlite3.h" as
77776 ** part of the build process.
77777 **
77778 ** @(#) $Id: sqlite.h.in,v 1.278 2007/12/13 21:54:11 drh Exp $
77779 */
77780 #ifndef _SQLITE3_H_
77781 #define _SQLITE3_H_
77782
77783 /*
77784 ** Make sure we can call this stuff from C++.
77785 */
77786 #if 0
77787 extern "C" {
77788 #endif
77789
77790
77791 /*
77792 ** Add the ability to override 'extern'
77793 */
77794 #ifndef SQLITE_EXTERN
77795 # define SQLITE_EXTERN extern
77796 #endif
77797
77798 /*
77799 ** Make sure these symbols where not defined by some previous header
77800 ** file.
77801 */
77802 #ifdef SQLITE_VERSION
77803 # undef SQLITE_VERSION
77804 #endif
77805 #ifdef SQLITE_VERSION_NUMBER
77806 # undef SQLITE_VERSION_NUMBER
77807 #endif
77808
77809 /*
77810 ** CAPI3REF: Compile-Time Library Version Numbers {F10010}
77811 **
77812 ** {F10011} The #define in the sqlite3.h header file named
77813 ** SQLITE_VERSION resolves to a string literal that identifies
77814 ** the version of the SQLite library in the format "X.Y.Z", where
77815 ** X is the major version number, Y is the minor version number and Z
77816 ** is the release number.  The X.Y.Z might be followed by "alpha" or "beta".
77817 ** {END} For example "3.1.1beta".
77818 **
77819 ** The X value is always 3 in SQLite.  The X value only changes when
77820 ** backwards compatibility is broken and we intend to never break
77821 ** backwards compatibility.  The Y value only changes when
77822 ** there are major feature enhancements that are forwards compatible
77823 ** but not backwards compatible.  The Z value is incremented with
77824 ** each release but resets back to 0 when Y is incremented.
77825 **
77826 ** {F10014} The SQLITE_VERSION_NUMBER #define resolves to an integer
77827 ** with the value  (X*1000000 + Y*1000 + Z) where X, Y, and Z are as
77828 ** with SQLITE_VERSION. {END} For example, for version "3.1.1beta", 
77829 ** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using 
77830 ** version 3.1.1 or greater at compile time, programs may use the test 
77831 ** (SQLITE_VERSION_NUMBER>=3001001).
77832 **
77833 ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
77834 */
77835 #define SQLITE_VERSION         "3.5.4"
77836 #define SQLITE_VERSION_NUMBER 3005004
77837
77838 /*
77839 ** CAPI3REF: Run-Time Library Version Numbers {F10020}
77840 **
77841 ** {F10021} The sqlite3_libversion_number() interface returns an integer
77842 ** equal to [SQLITE_VERSION_NUMBER].  {END} The value returned
77843 ** by this routine should only be different from the header values
77844 ** if the application is compiled using an sqlite3.h header from a
77845 ** different version of SQLite than library.  Cautious programmers might
77846 ** include a check in their application to verify that 
77847 ** sqlite3_libversion_number() always returns the value 
77848 ** [SQLITE_VERSION_NUMBER].
77849 **
77850 ** {F10022} The sqlite3_version[] string constant contains the text of the
77851 ** [SQLITE_VERSION] string. {F10023} The sqlite3_libversion() function returns
77852 ** a pointer to the sqlite3_version[] string constant. {END} The 
77853 ** sqlite3_libversion() function
77854 ** is provided for DLL users who can only access functions and not
77855 ** constants within the DLL.
77856 */
77857 SQLITE_EXTERN const char sqlite3_version[];
77858 const char *sqlite3_libversion(void);
77859 int sqlite3_libversion_number(void);
77860
77861 /*
77862 ** CAPI3REF: Test To See If The Library Is Threadsafe {F10100}
77863 **
77864 ** {F10101} The sqlite3_threadsafe() routine returns nonzero
77865 ** if SQLite was compiled with its mutexes enabled or zero if
77866 ** SQLite was compiled with mutexes disabled. {END}  If this
77867 ** routine returns false, then it is not safe for simultaneously
77868 ** running threads to both invoke SQLite interfaces.
77869 **
77870 ** Really all this routine does is return true if SQLite was
77871 ** compiled with the -DSQLITE_THREADSAFE=1 option and false if
77872 ** compiled with -DSQLITE_THREADSAFE=0.  If SQLite uses an
77873 ** application-defined mutex subsystem, malloc subsystem, collating
77874 ** sequence, VFS, SQL function, progress callback, commit hook,
77875 ** extension, or other accessories and these add-ons are not
77876 ** threadsafe, then clearly the combination will not be threadsafe
77877 ** either.  Hence, this routine never reports that the library
77878 ** is guaranteed to be threadsafe, only when it is guaranteed not
77879 ** to be.
77880 */
77881 int sqlite3_threadsafe(void);
77882
77883 /*
77884 ** CAPI3REF: Database Connection Handle {F12000}
77885 **
77886 ** Each open SQLite database is represented by pointer to an instance of the
77887 ** opaque structure named "sqlite3".  It is useful to think of an sqlite3
77888 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
77889 ** [sqlite3_open_v2()] interfaces are its constructors
77890 ** and [sqlite3_close()] is its destructor.  There are many other interfaces
77891 ** (such as [sqlite3_prepare_v2()], [sqlite3_create_function()], and
77892 ** [sqlite3_busy_timeout()] to name but three) that are methods on this
77893 ** object.
77894 */
77895 typedef struct sqlite3 sqlite3;
77896
77897
77898 /*
77899 ** CAPI3REF: 64-Bit Integer Types {F10200}
77900 **
77901 ** Because there is no cross-platform way to specify such types
77902 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
77903 ** {F10201} The sqlite_int64 and sqlite3_int64 types specify a
77904 ** 64-bit signed integer. {F10202} The sqlite_uint64 and
77905 ** sqlite3_uint64 types specify a 64-bit unsigned integer. {END}
77906 **
77907 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type
77908 ** definitions.  The sqlite_int64 and sqlite_uint64 types are
77909 ** supported for backwards compatibility only.
77910 */
77911 #ifdef SQLITE_INT64_TYPE
77912   typedef SQLITE_INT64_TYPE sqlite_int64;
77913   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
77914 #elif defined(_MSC_VER) || defined(__BORLANDC__)
77915   typedef __int64 sqlite_int64;
77916   typedef unsigned __int64 sqlite_uint64;
77917 #else
77918   typedef long long int sqlite_int64;
77919   typedef unsigned long long int sqlite_uint64;
77920 #endif
77921 typedef sqlite_int64 sqlite3_int64;
77922 typedef sqlite_uint64 sqlite3_uint64;
77923
77924 /*
77925 ** If compiling for a processor that lacks floating point support,
77926 ** substitute integer for floating-point
77927 */
77928 #ifdef SQLITE_OMIT_FLOATING_POINT
77929 # define double sqlite3_int64
77930 #endif
77931
77932 /*
77933 ** CAPI3REF: Closing A Database Connection {F12010}
77934 **
77935 ** {F12011} The sqlite3_close() interfaces destroys an [sqlite3] object
77936 ** allocated by a prior call to [sqlite3_open()], [sqlite3_open16()], or
77937 ** [sqlite3_open_v2()]. {F12012} Sqlite3_close() releases all
77938 ** memory used by the connection and closes all open files. {END}.
77939 **
77940 ** {F12013} If the database connection contains
77941 ** [sqlite3_stmt | prepared statements] that have not been finalized
77942 ** by [sqlite3_finalize()], then sqlite3_close() returns SQLITE_BUSY
77943 ** and leaves the connection open.  {F12014} Giving sqlite3_close()
77944 ** a NULL pointer is a harmless no-op. {END}
77945 **
77946 ** {U12015} Passing this routine a database connection that has already been
77947 ** closed results in undefined behavior. {U12016} If other interfaces that
77948 ** reference the same database connection are pending (either in the
77949 ** same thread or in different threads) when this routine is called,
77950 ** then the behavior is undefined and is almost certainly undesirable.
77951 */
77952 int sqlite3_close(sqlite3 *);
77953
77954 /*
77955 ** The type for a callback function.
77956 ** This is legacy and deprecated.  It is included for historical
77957 ** compatibility and is not documented.
77958 */
77959 typedef int (*sqlite3_callback)(void*,int,char**, char**);
77960
77961 /*
77962 ** CAPI3REF: One-Step Query Execution Interface {F12100}
77963 **
77964 ** {F12101} The sqlite3_exec() interface evaluates zero or more 
77965 ** UTF-8 encoded, semicolon-separated SQL statements in the zero-terminated
77966 ** string of its second argument.  {F12102} The SQL
77967 ** statements are evaluated in the context of the database connection
77968 ** specified by in the first argument.
77969 ** {F12103} SQL statements are prepared one by one using
77970 ** [sqlite3_prepare()] or the equivalent, evaluated
77971 ** using one or more calls to [sqlite3_step()], then destroyed
77972 ** using [sqlite3_finalize()]. {F12104} The return value of
77973 ** sqlite3_exec() is SQLITE_OK if all SQL statement run
77974 ** successfully.
77975 **
77976 ** {F12105} If one or more of the SQL statements handed to
77977 ** sqlite3_exec() are queries, then
77978 ** the callback function specified by the 3rd parameter is
77979 ** invoked once for each row of the query result. {F12106}
77980 ** If the callback returns a non-zero value then the query
77981 ** is aborted, all subsequent SQL statements
77982 ** are skipped and the sqlite3_exec() function returns the [SQLITE_ABORT].
77983 **
77984 ** {F12107} The 4th parameter to sqlite3_exec() is an arbitrary pointer
77985 ** that is passed through to the callback function as its first parameter.
77986 **
77987 ** {F12108} The 2nd parameter to the callback function is the number of
77988 ** columns in the query result.  {F12109} The 3rd parameter to the callback
77989 ** is an array of pointers to strings holding the values for each column
77990 ** as extracted using [sqlite3_column_text()].  NULL values in the result
77991 ** set result in a NULL pointer.  All other value are in their UTF-8
77992 ** string representation. {F12117}
77993 ** The 4th parameter to the callback is an array of strings
77994 ** obtained using [sqlite3_column_name()] and holding
77995 ** the names of each column, also in UTF-8.
77996 **
77997 ** {F12110} The callback function may be NULL, even for queries.  A NULL
77998 ** callback is not an error.  It just means that no callback
77999 ** will be invoked. 
78000 **
78001 ** {F12112} If an error occurs while parsing or evaluating the SQL
78002 ** then an appropriate error message is written into memory obtained
78003 ** from [sqlite3_malloc()] and *errmsg is made to point to that message
78004 ** assuming errmsg is not NULL.  
78005 ** {U12113} The calling function is responsible for freeing the memory
78006 ** using [sqlite3_free()].
78007 ** {F12116} If [sqlite3_malloc()] fails while attempting to generate
78008 ** the error message, *errmsg is set to NULL.
78009 ** {F12114} If errmsg is NULL then no attempt is made to generate an
78010 ** error message. <todo>Is the return code SQLITE_NOMEM or the original
78011 ** error code?</todo> <todo>What happens if there are multiple errors?
78012 ** Do we get code for the first error, or is the choice of reported
78013 ** error arbitrary?</todo>
78014 **
78015 ** {F12115} The return value is is SQLITE_OK if there are no errors and
78016 ** some other [SQLITE_OK | return code] if there is an error.  
78017 ** The particular return value depends on the type of error.  {END}
78018 */
78019 int sqlite3_exec(
78020   sqlite3*,                                  /* An open database */
78021   const char *sql,                           /* SQL to be evaluted */
78022   int (*callback)(void*,int,char**,char**),  /* Callback function */
78023   void *,                                    /* 1st argument to callback */
78024   char **errmsg                              /* Error msg written here */
78025 );
78026
78027 /*
78028 ** CAPI3REF: Result Codes {F10210}
78029 ** KEYWORDS: SQLITE_OK
78030 **
78031 ** Many SQLite functions return an integer result code from the set shown
78032 ** above in order to indicates success or failure.
78033 **
78034 ** {F10211} The result codes shown here are the only ones returned 
78035 ** by SQLite in its default configuration. {F10212} However, the
78036 ** [sqlite3_extended_result_codes()] API can be used to set a database
78037 ** connectoin to return more detailed result codes. {END}
78038 **
78039 ** See also: [SQLITE_IOERR_READ | extended result codes]
78040 **
78041 */
78042 #define SQLITE_OK           0   /* Successful result */
78043 /* beginning-of-error-codes */
78044 #define SQLITE_ERROR        1   /* SQL error or missing database */
78045 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
78046 #define SQLITE_PERM         3   /* Access permission denied */
78047 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
78048 #define SQLITE_BUSY         5   /* The database file is locked */
78049 #define SQLITE_LOCKED       6   /* A table in the database is locked */
78050 #define SQLITE_NOMEM        7   /* A malloc() failed */
78051 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
78052 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
78053 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
78054 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
78055 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
78056 #define SQLITE_FULL        13   /* Insertion failed because database is full */
78057 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
78058 #define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
78059 #define SQLITE_EMPTY       16   /* Database is empty */
78060 #define SQLITE_SCHEMA      17   /* The database schema changed */
78061 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
78062 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
78063 #define SQLITE_MISMATCH    20   /* Data type mismatch */
78064 #define SQLITE_MISUSE      21   /* Library used incorrectly */
78065 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
78066 #define SQLITE_AUTH        23   /* Authorization denied */
78067 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
78068 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
78069 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
78070 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
78071 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
78072 /* end-of-error-codes */
78073
78074 /*
78075 ** CAPI3REF: Extended Result Codes {F10220}
78076 **
78077 ** In its default configuration, SQLite API routines return one of 26 integer
78078 ** [SQLITE_OK | result codes].  However, experience has shown that
78079 ** many of these result codes are too course-grained.  They do not provide as
78080 ** much information about problems as programmers might like.  In an effort to
78081 ** address this, newer versions of SQLite (version 3.3.8 and later) include
78082 ** support for additional result codes that provide more detailed information
78083 ** about errors. {F10221} The extended result codes are enabled or disabled
78084 ** for each database connection using the [sqlite3_extended_result_codes()]
78085 ** API. {END}
78086 ** 
78087 ** Some of the available extended result codes are listed above.
78088 ** We expect the number of extended result codes will be expand
78089 ** over time.  {U10422} Software that uses extended result codes should expect
78090 ** to see new result codes in future releases of SQLite. {END}
78091 ** 
78092 ** {F10223} The symbolic name for an extended result code always contains
78093 ** a related primary result code as a prefix. {F10224} Primary result
78094 ** codes contain a single "_" character.  {F10225} Extended result codes
78095 ** contain two or more "_" characters. {F10226} The numeric value of an
78096 ** extended result code can be converted to its
78097 ** corresponding primary result code by masking off the lower 8 bytes. {END}
78098 **
78099 ** The SQLITE_OK result code will never be extended.  It will always
78100 ** be exactly zero.
78101 */
78102 #define SQLITE_IOERR_READ          (SQLITE_IOERR | (1<<8))
78103 #define SQLITE_IOERR_SHORT_READ    (SQLITE_IOERR | (2<<8))
78104 #define SQLITE_IOERR_WRITE         (SQLITE_IOERR | (3<<8))
78105 #define SQLITE_IOERR_FSYNC         (SQLITE_IOERR | (4<<8))
78106 #define SQLITE_IOERR_DIR_FSYNC     (SQLITE_IOERR | (5<<8))
78107 #define SQLITE_IOERR_TRUNCATE      (SQLITE_IOERR | (6<<8))
78108 #define SQLITE_IOERR_FSTAT         (SQLITE_IOERR | (7<<8))
78109 #define SQLITE_IOERR_UNLOCK        (SQLITE_IOERR | (8<<8))
78110 #define SQLITE_IOERR_RDLOCK        (SQLITE_IOERR | (9<<8))
78111 #define SQLITE_IOERR_DELETE        (SQLITE_IOERR | (10<<8))
78112 #define SQLITE_IOERR_BLOCKED       (SQLITE_IOERR | (11<<8))
78113 #define SQLITE_IOERR_NOMEM         (SQLITE_IOERR | (12<<8))
78114
78115 /*
78116 ** CAPI3REF: Flags For File Open Operations {F10230}
78117 **
78118 ** {F10231} Some combination of the these bit values are used as the
78119 ** third argument to the [sqlite3_open_v2()] interface and
78120 ** as fourth argument to the xOpen method of the
78121 ** [sqlite3_vfs] object.
78122 */
78123 #define SQLITE_OPEN_READONLY         0x00000001
78124 #define SQLITE_OPEN_READWRITE        0x00000002
78125 #define SQLITE_OPEN_CREATE           0x00000004
78126 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008
78127 #define SQLITE_OPEN_EXCLUSIVE        0x00000010
78128 #define SQLITE_OPEN_MAIN_DB          0x00000100
78129 #define SQLITE_OPEN_TEMP_DB          0x00000200
78130 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400
78131 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800
78132 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000
78133 #define SQLITE_OPEN_SUBJOURNAL       0x00002000
78134 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000
78135
78136 /*
78137 ** CAPI3REF: Device Characteristics {F10240}
78138 **
78139 ** {F10241} The xDeviceCapabilities method of the [sqlite3_io_methods]
78140 ** object returns an integer which is a vector of the these
78141 ** bit values expressing I/O characteristics of the mass storage
78142 ** device that holds the file that the [sqlite3_io_methods]
78143 ** refers to. {END}
78144 **
78145 ** {F10242} The SQLITE_IOCAP_ATOMIC property means that all writes of
78146 ** any size are atomic.  {F10243} The SQLITE_IOCAP_ATOMICnnn values
78147 ** mean that writes of blocks that are nnn bytes in size and
78148 ** are aligned to an address which is an integer multiple of
78149 ** nnn are atomic.  {F10244} The SQLITE_IOCAP_SAFE_APPEND value means
78150 ** that when data is appended to a file, the data is appended
78151 ** first then the size of the file is extended, never the other
78152 ** way around.  {F10245} The SQLITE_IOCAP_SEQUENTIAL property means that
78153 ** information is written to disk in the same order as calls
78154 ** to xWrite().
78155 */
78156 #define SQLITE_IOCAP_ATOMIC          0x00000001
78157 #define SQLITE_IOCAP_ATOMIC512       0x00000002
78158 #define SQLITE_IOCAP_ATOMIC1K        0x00000004
78159 #define SQLITE_IOCAP_ATOMIC2K        0x00000008
78160 #define SQLITE_IOCAP_ATOMIC4K        0x00000010
78161 #define SQLITE_IOCAP_ATOMIC8K        0x00000020
78162 #define SQLITE_IOCAP_ATOMIC16K       0x00000040
78163 #define SQLITE_IOCAP_ATOMIC32K       0x00000080
78164 #define SQLITE_IOCAP_ATOMIC64K       0x00000100
78165 #define SQLITE_IOCAP_SAFE_APPEND     0x00000200
78166 #define SQLITE_IOCAP_SEQUENTIAL      0x00000400
78167
78168 /*
78169 ** CAPI3REF: File Locking Levels {F10250}
78170 **
78171 ** {F10251} SQLite uses one of the following integer values as the second
78172 ** argument to calls it makes to the xLock() and xUnlock() methods
78173 ** of an [sqlite3_io_methods] object. {END}
78174 */
78175 #define SQLITE_LOCK_NONE          0
78176 #define SQLITE_LOCK_SHARED        1
78177 #define SQLITE_LOCK_RESERVED      2
78178 #define SQLITE_LOCK_PENDING       3
78179 #define SQLITE_LOCK_EXCLUSIVE     4
78180
78181 /*
78182 ** CAPI3REF: Synchronization Type Flags {F10260}
78183 **
78184 ** {F10261} When SQLite invokes the xSync() method of an
78185 ** [sqlite3_io_methods] object it uses a combination of the
78186 ** these integer values as the second argument.
78187 **
78188 ** {F10262} When the SQLITE_SYNC_DATAONLY flag is used, it means that the
78189 ** sync operation only needs to flush data to mass storage.  Inode
78190 ** information need not be flushed. {F10263} The SQLITE_SYNC_NORMAL means 
78191 ** to use normal fsync() semantics. {F10264} The SQLITE_SYNC_FULL flag means 
78192 ** to use Mac OS-X style fullsync instead of fsync().
78193 */
78194 #define SQLITE_SYNC_NORMAL        0x00002
78195 #define SQLITE_SYNC_FULL          0x00003
78196 #define SQLITE_SYNC_DATAONLY      0x00010
78197
78198
78199 /*
78200 ** CAPI3REF: OS Interface Open File Handle {F11110}
78201 **
78202 ** An [sqlite3_file] object represents an open file in the OS
78203 ** interface layer.  Individual OS interface implementations will
78204 ** want to subclass this object by appending additional fields
78205 ** for their own use.  The pMethods entry is a pointer to an
78206 ** [sqlite3_io_methods] object that defines methods for performing
78207 ** I/O operations on the open file.
78208 */
78209 typedef struct sqlite3_file sqlite3_file;
78210 struct sqlite3_file {
78211   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
78212 };
78213
78214 /*
78215 ** CAPI3REF: OS Interface File Virtual Methods Object {F11120}
78216 **
78217 ** Every file opened by the [sqlite3_vfs] xOpen method contains a pointer to
78218 ** an instance of the this object.  This object defines the
78219 ** methods used to perform various operations against the open file.
78220 **
78221 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
78222 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
78223 *  The second choice is an
78224 ** OS-X style fullsync.  The SQLITE_SYNC_DATA flag may be ORed in to
78225 ** indicate that only the data of the file and not its inode needs to be
78226 ** synced.
78227 ** 
78228 ** The integer values to xLock() and xUnlock() are one of
78229 ** <ul>
78230 ** <li> [SQLITE_LOCK_NONE],
78231 ** <li> [SQLITE_LOCK_SHARED],
78232 ** <li> [SQLITE_LOCK_RESERVED],
78233 ** <li> [SQLITE_LOCK_PENDING], or
78234 ** <li> [SQLITE_LOCK_EXCLUSIVE].
78235 ** </ul>
78236 ** xLock() increases the lock. xUnlock() decreases the lock.  
78237 ** The xCheckReservedLock() method looks
78238 ** to see if any database connection, either in this
78239 ** process or in some other process, is holding an RESERVED,
78240 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
78241 ** if such a lock exists and false if not.
78242 ** 
78243 ** The xFileControl() method is a generic interface that allows custom
78244 ** VFS implementations to directly control an open file using the
78245 ** [sqlite3_file_control()] interface.  The second "op" argument
78246 ** is an integer opcode.   The third
78247 ** argument is a generic pointer which is intended to be a pointer
78248 ** to a structure that may contain arguments or space in which to
78249 ** write return values.  Potential uses for xFileControl() might be
78250 ** functions to enable blocking locks with timeouts, to change the
78251 ** locking strategy (for example to use dot-file locks), to inquire
78252 ** about the status of a lock, or to break stale locks.  The SQLite
78253 ** core reserves opcodes less than 100 for its own use. 
78254 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
78255 ** Applications that define a custom xFileControl method should use opcodes 
78256 ** greater than 100 to avoid conflicts.
78257 **
78258 ** The xSectorSize() method returns the sector size of the
78259 ** device that underlies the file.  The sector size is the
78260 ** minimum write that can be performed without disturbing
78261 ** other bytes in the file.  The xDeviceCharacteristics()
78262 ** method returns a bit vector describing behaviors of the
78263 ** underlying device:
78264 **
78265 ** <ul>
78266 ** <li> [SQLITE_IOCAP_ATOMIC]
78267 ** <li> [SQLITE_IOCAP_ATOMIC512]
78268 ** <li> [SQLITE_IOCAP_ATOMIC1K]
78269 ** <li> [SQLITE_IOCAP_ATOMIC2K]
78270 ** <li> [SQLITE_IOCAP_ATOMIC4K]
78271 ** <li> [SQLITE_IOCAP_ATOMIC8K]
78272 ** <li> [SQLITE_IOCAP_ATOMIC16K]
78273 ** <li> [SQLITE_IOCAP_ATOMIC32K]
78274 ** <li> [SQLITE_IOCAP_ATOMIC64K]
78275 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
78276 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
78277 ** </ul>
78278 **
78279 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
78280 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
78281 ** mean that writes of blocks that are nnn bytes in size and
78282 ** are aligned to an address which is an integer multiple of
78283 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
78284 ** that when data is appended to a file, the data is appended
78285 ** first then the size of the file is extended, never the other
78286 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
78287 ** information is written to disk in the same order as calls
78288 ** to xWrite().
78289 */
78290 typedef struct sqlite3_io_methods sqlite3_io_methods;
78291 struct sqlite3_io_methods {
78292   int iVersion;
78293   int (*xClose)(sqlite3_file*);
78294   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
78295   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
78296   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
78297   int (*xSync)(sqlite3_file*, int flags);
78298   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
78299   int (*xLock)(sqlite3_file*, int);
78300   int (*xUnlock)(sqlite3_file*, int);
78301   int (*xCheckReservedLock)(sqlite3_file*);
78302   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
78303   int (*xSectorSize)(sqlite3_file*);
78304   int (*xDeviceCharacteristics)(sqlite3_file*);
78305   /* Additional methods may be added in future releases */
78306 };
78307
78308 /*
78309 ** CAPI3REF: Standard File Control Opcodes {F11310}
78310 **
78311 ** These integer constants are opcodes for the xFileControl method
78312 ** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()]
78313 ** interface.
78314 **
78315 ** {F11311} The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
78316 ** opcode cases the xFileControl method to write the current state of
78317 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
78318 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
78319 ** into an integer that the pArg argument points to. {F11312} This capability
78320 ** is used during testing and only needs to be supported when SQLITE_TEST
78321 ** is defined.
78322 */
78323 #define SQLITE_FCNTL_LOCKSTATE        1
78324
78325 /*
78326 ** CAPI3REF: Mutex Handle {F17110}
78327 **
78328 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
78329 ** abstract type for a mutex object.  {F17111} The SQLite core never looks
78330 ** at the internal representation of an [sqlite3_mutex]. {END} It only
78331 ** deals with pointers to the [sqlite3_mutex] object.
78332 **
78333 ** Mutexes are created using [sqlite3_mutex_alloc()].
78334 */
78335 typedef struct sqlite3_mutex sqlite3_mutex;
78336
78337 /*
78338 ** CAPI3REF: OS Interface Object {F11140}
78339 **
78340 ** An instance of this object defines the interface between the
78341 ** SQLite core and the underlying operating system.  The "vfs"
78342 ** in the name of the object stands for "virtual file system".
78343 **
78344 ** The iVersion field is initially 1 but may be larger for future
78345 ** versions of SQLite.  Additional fields may be appended to this
78346 ** object when the iVersion value is increased.
78347 **
78348 ** The szOsFile field is the size of the subclassed [sqlite3_file]
78349 ** structure used by this VFS.  mxPathname is the maximum length of
78350 ** a pathname in this VFS.
78351 **
78352 ** Registered vfs modules are kept on a linked list formed by
78353 ** the pNext pointer.  The [sqlite3_vfs_register()]
78354 ** and [sqlite3_vfs_unregister()] interfaces manage this list
78355 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
78356 ** searches the list.
78357 **
78358 ** The pNext field is the only fields in the sqlite3_vfs 
78359 ** structure that SQLite will ever modify.  SQLite will only access
78360 ** or modify this field while holding a particular static mutex.
78361 ** The application should never modify anything within the sqlite3_vfs
78362 ** object once the object has been registered.
78363 **
78364 ** The zName field holds the name of the VFS module.  The name must
78365 ** be unique across all VFS modules.
78366 **
78367 ** {F11141} SQLite will guarantee that the zFilename string passed to
78368 ** xOpen() is a full pathname as generated by xFullPathname() and
78369 ** that the string will be valid and unchanged until xClose() is
78370 ** called.  {END} So the [sqlite3_file] can store a pointer to the
78371 ** filename if it needs to remember the filename for some reason.
78372 **
78373 ** {F11142} The flags argument to xOpen() includes all bits set in
78374 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
78375 ** or [sqlite3_open16()] is used, then flags includes at least
78376 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END}
78377 ** If xOpen() opens a file read-only then it sets *pOutFlags to
78378 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be
78379 ** set.
78380 ** 
78381 ** {F11143} SQLite will also add one of the following flags to the xOpen()
78382 ** call, depending on the object being opened:
78383 ** 
78384 ** <ul>
78385 ** <li>  [SQLITE_OPEN_MAIN_DB]
78386 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
78387 ** <li>  [SQLITE_OPEN_TEMP_DB]
78388 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
78389 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
78390 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
78391 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
78392 ** </ul> {END}
78393 **
78394 ** The file I/O implementation can use the object type flags to
78395 ** changes the way it deals with files.  For example, an application
78396 ** that does not care about crash recovery or rollback, might make
78397 ** the open of a journal file a no-op.  Writes to this journal are
78398 ** also a no-op.  Any attempt to read the journal return SQLITE_IOERR.
78399 ** Or the implementation might recognize the a database file will
78400 ** be doing page-aligned sector reads and writes in a random order
78401 ** and set up its I/O subsystem accordingly.
78402 ** 
78403 ** {F11144} SQLite might also add one of the following flags to the xOpen
78404 ** method:
78405 ** 
78406 ** <ul>
78407 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
78408 ** <li> [SQLITE_OPEN_EXCLUSIVE]
78409 ** </ul>
78410 ** 
78411 ** {F11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
78412 ** deleted when it is closed.  {F11146} The [SQLITE_OPEN_DELETEONCLOSE]
78413 ** will be set for TEMP  databases, journals and for subjournals. 
78414 ** {F11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened
78415 ** for exclusive access.  This flag is set for all files except
78416 ** for the main database file. {END}
78417 ** 
78418 ** {F11148} At least szOsFile bytes of memory is allocated by SQLite 
78419 ** to hold the  [sqlite3_file] structure passed as the third 
78420 ** argument to xOpen.  {END}  The xOpen method does not have to
78421 ** allocate the structure; it should just fill it in.
78422 ** 
78423 ** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] 
78424 ** to test for the existance of a file,
78425 ** or [SQLITE_ACCESS_READWRITE] to test to see
78426 ** if a file is readable and writable, or [SQLITE_ACCESS_READ]
78427 ** to test to see if a file is at least readable.  {END} The file can be a 
78428 ** directory.
78429 ** 
78430 ** {F11150} SQLite will always allocate at least mxPathname+1 byte for
78431 ** the output buffers for xGetTempname and xFullPathname. {F11151} The exact
78432 ** size of the output buffer is also passed as a parameter to both 
78433 ** methods. {END} If the output buffer is not large enough, SQLITE_CANTOPEN
78434 ** should be returned. As this is handled as a fatal error by SQLite,
78435 ** vfs implementations should endeavor to prevent this by setting 
78436 ** mxPathname to a sufficiently large value.
78437 ** 
78438 ** The xRandomness(), xSleep(), and xCurrentTime() interfaces
78439 ** are not strictly a part of the filesystem, but they are
78440 ** included in the VFS structure for completeness.
78441 ** The xRandomness() function attempts to return nBytes bytes
78442 ** of good-quality randomness into zOut.  The return value is
78443 ** the actual number of bytes of randomness obtained.  The
78444 ** xSleep() method cause the calling thread to sleep for at
78445 ** least the number of microseconds given.  The xCurrentTime()
78446 ** method returns a Julian Day Number for the current date and
78447 ** time.
78448 */
78449 typedef struct sqlite3_vfs sqlite3_vfs;
78450 struct sqlite3_vfs {
78451   int iVersion;            /* Structure version number */
78452   int szOsFile;            /* Size of subclassed sqlite3_file */
78453   int mxPathname;          /* Maximum file pathname length */
78454   sqlite3_vfs *pNext;      /* Next registered VFS */
78455   const char *zName;       /* Name of this virtual file system */
78456   void *pAppData;          /* Pointer to application-specific data */
78457   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
78458                int flags, int *pOutFlags);
78459   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
78460   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags);
78461   int (*xGetTempname)(sqlite3_vfs*, int nOut, char *zOut);
78462   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
78463   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
78464   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
78465   void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol);
78466   void (*xDlClose)(sqlite3_vfs*, void*);
78467   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
78468   int (*xSleep)(sqlite3_vfs*, int microseconds);
78469   int (*xCurrentTime)(sqlite3_vfs*, double*);
78470   /* New fields may be appended in figure versions.  The iVersion
78471   ** value will increment whenever this happens. */
78472 };
78473
78474 /*
78475 ** CAPI3REF: Flags for the xAccess VFS method {F11190}
78476 **
78477 ** {F11191} These integer constants can be used as the third parameter to
78478 ** the xAccess method of an [sqlite3_vfs] object. {END}  They determine
78479 ** the kind of what kind of permissions the xAccess method is
78480 ** looking for.  {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method
78481 ** simply checks to see if the file exists. {F11193} With
78482 ** SQLITE_ACCESS_READWRITE, the xAccess method checks to see
78483 ** if the file is both readable and writable.  {F11194} With
78484 ** SQLITE_ACCESS_READ the xAccess method
78485 ** checks to see if the file is readable.
78486 */
78487 #define SQLITE_ACCESS_EXISTS    0
78488 #define SQLITE_ACCESS_READWRITE 1
78489 #define SQLITE_ACCESS_READ      2
78490
78491 /*
78492 ** CAPI3REF: Enable Or Disable Extended Result Codes {F12200}
78493 **
78494 ** {F12201} The sqlite3_extended_result_codes() routine enables or disables the
78495 ** [SQLITE_IOERR_READ | extended result codes] feature on a database
78496 ** connection if its 2nd parameter is
78497 ** non-zero or zero, respectively. {F12202}
78498 ** By default, SQLite API routines return one of only 26 integer
78499 ** [SQLITE_OK | result codes].  {F12203} When extended result codes
78500 ** are enabled by this routine, the repetoire of result codes can be
78501 ** much larger and can (hopefully) provide more detailed information
78502 ** about the cause of an error.
78503 **
78504 ** {F12204} The second argument is a boolean value that turns extended result
78505 ** codes on and off. {F12205} Extended result codes are off by default for
78506 ** backwards compatibility with older versions of SQLite.
78507 */
78508 int sqlite3_extended_result_codes(sqlite3*, int onoff);
78509
78510 /*
78511 ** CAPI3REF: Last Insert Rowid {F12220}
78512 **
78513 ** {F12221} Each entry in an SQLite table has a unique 64-bit signed
78514 ** integer key called the "rowid".  {F12222} The rowid is always available
78515 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
78516 ** names are not also used by explicitly declared columns. {F12223} If
78517 ** the table has a column of type INTEGER PRIMARY KEY then that column
78518 ** is another an alias for the rowid.
78519 **
78520 ** {F12224} This routine returns the rowid of the most recent
78521 ** successful INSERT into the database from the database connection
78522 ** shown in the first argument.  {F12225} If no successful inserts
78523 ** have ever occurred on this database connection, zero is returned.
78524 **
78525 ** {F12226} If an INSERT occurs within a trigger, then the rowid of the
78526 ** inserted row is returned by this routine as long as the trigger
78527 ** is running.  {F12227} But once the trigger terminates, the value returned
78528 ** by this routine reverts to the last value inserted before the
78529 ** trigger fired.
78530 **
78531 ** {F12228} An INSERT that fails due to a constraint violation is not a
78532 ** successful insert and does not change the value returned by this
78533 ** routine.  {F12229} Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
78534 ** and INSERT OR ABORT make no changes to the return value of this
78535 ** routine when their insertion fails.  {F12231} When INSERT OR REPLACE 
78536 ** encounters a constraint violation, it does not fail.  The
78537 ** INSERT continues to completion after deleting rows that caused
78538 ** the constraint problem so INSERT OR REPLACE will always change
78539 ** the return value of this interface. 
78540 **
78541 ** {UF12232} If another thread does a new insert on the same database connection
78542 ** while this routine is running and thus changes the last insert rowid,
78543 ** then the return value of this routine is undefined.
78544 */
78545 sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
78546
78547 /*
78548 ** CAPI3REF: Count The Number Of Rows Modified {F12240}
78549 **
78550 ** {F12241} This function returns the number of database rows that were changed
78551 ** or inserted or deleted by the most recently completed SQL statement
78552 ** on the connection specified by the first parameter. {F12242} Only
78553 ** changes that are directly specified by the INSERT, UPDATE, or
78554 ** DELETE statement are counted.  Auxiliary changes caused by
78555 ** triggers are not counted. {F12243} Use the [sqlite3_total_changes()] function
78556 ** to find the total number of changes including changes caused by triggers.
78557 **
78558 ** {F12244} Within the body of a trigger, the sqlite3_changes() interface
78559 ** can be called to find the number of
78560 ** changes in the most recently completed INSERT, UPDATE, or DELETE
78561 ** statement within the body of the same trigger.
78562 **
78563 ** {F12245} All changes are counted, even if they are later undone by a
78564 ** ROLLBACK or ABORT.  {F12246} Except, changes associated with creating and
78565 ** dropping tables are not counted.
78566 **
78567 ** {F12247} If a callback invokes [sqlite3_exec()] or [sqlite3_step()]
78568 ** recursively, then the changes in the inner, recursive call are
78569 ** counted together with the changes in the outer call.
78570 **
78571 ** {F12248} SQLite implements the command "DELETE FROM table" without
78572 ** a WHERE clause by dropping and recreating the table.  (This is much
78573 ** faster than going through and deleting individual elements from the
78574 ** table.)  Because of this optimization, the change count for 
78575 ** "DELETE FROM table" will be zero regardless of the number of elements
78576 ** that were originally in the table. {F12251} To get an accurate count
78577 ** of the number of rows deleted, use
78578 ** "DELETE FROM table WHERE 1" instead.
78579 **
78580 ** {UF12252} If another thread makes changes on the same database connection
78581 ** while this routine is running then the return value of this routine
78582 ** is undefined.
78583 */
78584 int sqlite3_changes(sqlite3*);
78585
78586 /*
78587 ** CAPI3REF: Total Number Of Rows Modified {F12260}
78588 ***
78589 ** {F12261} This function returns the number of database rows that have been
78590 ** modified by INSERT, UPDATE or DELETE statements since the database handle
78591 ** was opened. {F12262} The count includes UPDATE, INSERT and DELETE 
78592 ** statements executed as part of trigger programs.  {F12263} All changes
78593 ** are counted as soon as the statement that makes them is completed 
78594 ** (when the statement handle is passed to [sqlite3_reset()] or 
78595 ** [sqlite3_finalize()]). {END}
78596 **
78597 ** See also the [sqlite3_change()] interface.
78598 **
78599 ** {F12265} SQLite implements the command "DELETE FROM table" without
78600 ** a WHERE clause by dropping and recreating the table.  (This is much
78601 ** faster than going
78602 ** through and deleting individual elements form the table.)  Because of
78603 ** this optimization, the change count for "DELETE FROM table" will be
78604 ** zero regardless of the number of elements that were originally in the
78605 ** table. To get an accurate count of the number of rows deleted, use
78606 ** "DELETE FROM table WHERE 1" instead.
78607 **
78608 ** {U12264} If another thread makes changes on the same database connection
78609 ** while this routine is running then the return value of this routine
78610 ** is undefined. {END}
78611 */
78612 int sqlite3_total_changes(sqlite3*);
78613
78614 /*
78615 ** CAPI3REF: Interrupt A Long-Running Query {F12270}
78616 **
78617 ** {F12271} This function causes any pending database operation to abort and
78618 ** return at its earliest opportunity. {END} This routine is typically
78619 ** called in response to a user action such as pressing "Cancel"
78620 ** or Ctrl-C where the user wants a long query operation to halt
78621 ** immediately.
78622 **
78623 ** {F12272} It is safe to call this routine from a thread different from the
78624 ** thread that is currently running the database operation. {U12273} But it
78625 ** is not safe to call this routine with a database connection that
78626 ** is closed or might close before sqlite3_interrupt() returns.
78627 **
78628 ** If an SQL is very nearly finished at the time when sqlite3_interrupt()
78629 ** is called, then it might not have an opportunity to be interrupted.
78630 ** It might continue to completion.
78631 ** {F12274} The SQL operation that is interrupted will return
78632 ** [SQLITE_INTERRUPT].  {F12275} If the interrupted SQL operation is an
78633 ** INSERT, UPDATE, or DELETE that is inside an explicit transaction, 
78634 ** then the entire transaction will be rolled back automatically.
78635 ** {F12276} A call to sqlite3_interrupt() has no effect on SQL statements
78636 ** that are started after sqlite3_interrupt() returns.
78637 */
78638 void sqlite3_interrupt(sqlite3*);
78639
78640 /*
78641 ** CAPI3REF: Determine If An SQL Statement Is Complete {F10510}
78642 **
78643 ** These routines are useful for command-line input to determine if the
78644 ** currently entered text seems to form complete a SQL statement or
78645 ** if additional input is needed before sending the text into
78646 ** SQLite for parsing.  These routines return true if the input string
78647 ** appears to be a complete SQL statement.  A statement is judged to be
78648 ** complete if it ends with a semicolon and is not a fragment of a
78649 ** CREATE TRIGGER statement.  These routines do not parse the SQL and
78650 ** so will not detect syntactically incorrect SQL.
78651 **
78652 ** {F10511} These functions return true if the given input string 
78653 ** ends with a semicolon optionally followed by whitespace or
78654 ** comments. {F10512} For sqlite3_complete(),
78655 ** the parameter must be a zero-terminated UTF-8 string. {F10513} For
78656 ** sqlite3_complete16(), a zero-terminated machine byte order UTF-16 string
78657 ** is required.  {F10514} These routines return false if the terminal
78658 ** semicolon is within a comment, a string literal or a quoted identifier
78659 ** (in other words if the final semicolon is not really a separate token
78660 ** but part of a larger token) or if the final semicolon is
78661 ** in between the BEGIN and END keywords of a CREATE TRIGGER statement.
78662 ** {END}
78663 */
78664 int sqlite3_complete(const char *sql);
78665 int sqlite3_complete16(const void *sql);
78666
78667 /*
78668 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310}
78669 **
78670 ** {F12311} This routine identifies a callback function that might be
78671 ** invoked whenever an attempt is made to open a database table 
78672 ** that another thread or process has locked.
78673 ** {F12312} If the busy callback is NULL, then [SQLITE_BUSY]
78674 ** or [SQLITE_IOERR_BLOCKED]
78675 ** is returned immediately upon encountering the lock.
78676 ** {F12313} If the busy callback is not NULL, then the
78677 ** callback will be invoked with two arguments.  {F12314} The
78678 ** first argument to the handler is a copy of the void* pointer which
78679 ** is the third argument to this routine.  {F12315} The second argument to
78680 ** the handler is the number of times that the busy handler has
78681 ** been invoked for this locking event.  {F12316} If the
78682 ** busy callback returns 0, then no additional attempts are made to
78683 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
78684 ** {F12317} If the callback returns non-zero, then another attempt
78685 ** is made to open the database for reading and the cycle repeats.
78686 **
78687 ** The presence of a busy handler does not guarantee that
78688 ** it will be invoked when there is lock contention. {F12319}
78689 ** If SQLite determines that invoking the busy handler could result in
78690 ** a deadlock, it will go ahead and return [SQLITE_BUSY] or
78691 ** [SQLITE_IOERR_BLOCKED] instead of invoking the
78692 ** busy handler. {END}
78693 ** Consider a scenario where one process is holding a read lock that
78694 ** it is trying to promote to a reserved lock and
78695 ** a second process is holding a reserved lock that it is trying
78696 ** to promote to an exclusive lock.  The first process cannot proceed
78697 ** because it is blocked by the second and the second process cannot
78698 ** proceed because it is blocked by the first.  If both processes
78699 ** invoke the busy handlers, neither will make any progress.  Therefore,
78700 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
78701 ** will induce the first process to release its read lock and allow
78702 ** the second process to proceed.
78703 **
78704 ** {F12321} The default busy callback is NULL. {END}
78705 **
78706 ** {F12322} The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
78707 ** when SQLite is in the middle of a large transaction where all the
78708 ** changes will not fit into the in-memory cache.  {F12323} SQLite will
78709 ** already hold a RESERVED lock on the database file, but it needs
78710 ** to promote this lock to EXCLUSIVE so that it can spill cache
78711 ** pages into the database file without harm to concurrent
78712 ** readers.  {F12324} If it is unable to promote the lock, then the in-memory
78713 ** cache will be left in an inconsistent state and so the error
78714 ** code is promoted from the relatively benign [SQLITE_BUSY] to
78715 ** the more severe [SQLITE_IOERR_BLOCKED].  {F12325} This error code promotion
78716 ** forces an automatic rollback of the changes. {END} See the
78717 ** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError">
78718 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
78719 ** this is important.
78720 **      
78721 ** {F12326} Sqlite is re-entrant, so the busy handler may start a new
78722 ** query. {END} (It is not clear why anyone would every want to do this,
78723 ** but it is allowed, in theory.) {U12327} But the busy handler may not
78724 ** close the database.  Closing the database from a busy handler will delete 
78725 ** data structures out from under the executing query and will 
78726 ** probably result in a segmentation fault or other runtime error. {END}
78727 **
78728 ** {F12328} There can only be a single busy handler defined for each database
78729 ** connection.  Setting a new busy handler clears any previous one. 
78730 ** {F12329} Note that calling [sqlite3_busy_timeout()] will also set or clear
78731 ** the busy handler.
78732 **
78733 ** {F12331} When operating in [sqlite3_enable_shared_cache | shared cache mode],
78734 ** only a single busy handler can be defined for each database file.
78735 ** So if two database connections share a single cache, then changing
78736 ** the busy handler on one connection will also change the busy
78737 ** handler in the other connection.  {F12332} The busy handler is invoked
78738 ** in the thread that was running when the lock contention occurs.
78739 */
78740 int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
78741
78742 /*
78743 ** CAPI3REF: Set A Busy Timeout {F12340}
78744 **
78745 ** {F12341} This routine sets a [sqlite3_busy_handler | busy handler]
78746 ** that sleeps for a while when a
78747 ** table is locked.  {F12342} The handler will sleep multiple times until 
78748 ** at least "ms" milliseconds of sleeping have been done. {F12343} After
78749 ** "ms" milliseconds of sleeping, the handler returns 0 which
78750 ** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
78751 **
78752 ** {F12344} Calling this routine with an argument less than or equal to zero
78753 ** turns off all busy handlers.
78754 **
78755 ** {F12345} There can only be a single busy handler for a particular database
78756 ** connection.  If another busy handler was defined  
78757 ** (using [sqlite3_busy_handler()]) prior to calling
78758 ** this routine, that other busy handler is cleared.
78759 */
78760 int sqlite3_busy_timeout(sqlite3*, int ms);
78761
78762 /*
78763 ** CAPI3REF: Convenience Routines For Running Queries {F12370}
78764 **
78765 ** This next routine is a convenience wrapper around [sqlite3_exec()].
78766 ** {F12371} Instead of invoking a user-supplied callback for each row of the
78767 ** result, this routine remembers each row of the result in memory
78768 ** obtained from [sqlite3_malloc()], then returns all of the result after the
78769 ** query has finished. {F12372}
78770 **
78771 ** As an example, suppose the query result where this table:
78772 **
78773 ** <blockquote><pre>
78774 **        Name        | Age
78775 **        -----------------------
78776 **        Alice       | 43
78777 **        Bob         | 28
78778 **        Cindy       | 21
78779 ** </pre></blockquote>
78780 **
78781 ** If the 3rd argument were &azResult then after the function returns
78782 ** azResult will contain the following data:
78783 **
78784 ** <blockquote><pre>
78785 **        azResult&#91;0] = "Name";
78786 **        azResult&#91;1] = "Age";
78787 **        azResult&#91;2] = "Alice";
78788 **        azResult&#91;3] = "43";
78789 **        azResult&#91;4] = "Bob";
78790 **        azResult&#91;5] = "28";
78791 **        azResult&#91;6] = "Cindy";
78792 **        azResult&#91;7] = "21";
78793 ** </pre></blockquote>
78794 **
78795 ** Notice that there is an extra row of data containing the column
78796 ** headers.  But the *nrow return value is still 3.  *ncolumn is
78797 ** set to 2.  In general, the number of values inserted into azResult
78798 ** will be ((*nrow) + 1)*(*ncolumn).
78799 **
78800 ** {U12374} After the calling function has finished using the result, it should 
78801 ** pass the result data pointer to sqlite3_free_table() in order to 
78802 ** release the memory that was malloc-ed.  Because of the way the 
78803 ** [sqlite3_malloc()] happens, the calling function must not try to call 
78804 ** [sqlite3_free()] directly.  Only [sqlite3_free_table()] is able to release 
78805 ** the memory properly and safely. {END}
78806 **
78807 ** {F12373} The return value of this routine is the same as
78808 ** from [sqlite3_exec()].
78809 */
78810 int sqlite3_get_table(
78811   sqlite3*,              /* An open database */
78812   const char *sql,       /* SQL to be executed */
78813   char ***resultp,       /* Result written to a char *[]  that this points to */
78814   int *nrow,             /* Number of result rows written here */
78815   int *ncolumn,          /* Number of result columns written here */
78816   char **errmsg          /* Error msg written here */
78817 );
78818 void sqlite3_free_table(char **result);
78819
78820 /*
78821 ** CAPI3REF: Formatted String Printing Functions {F17400}
78822 **
78823 ** These routines are workalikes of the "printf()" family of functions
78824 ** from the standard C library.
78825 **
78826 ** {F17401} The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
78827 ** results into memory obtained from [sqlite3_malloc()].
78828 ** {U17402} The strings returned by these two routines should be
78829 ** released by [sqlite3_free()]. {F17403}  Both routines return a
78830 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
78831 ** memory to hold the resulting string.
78832 **
78833 ** {F17404} In sqlite3_snprintf() routine is similar to "snprintf()" from
78834 ** the standard C library.  The result is written into the
78835 ** buffer supplied as the second parameter whose size is given by
78836 ** the first parameter. {END} Note that the order of the
78837 ** first two parameters is reversed from snprintf().  This is an
78838 ** historical accident that cannot be fixed without breaking
78839 ** backwards compatibility.  {F17405} Note also that sqlite3_snprintf()
78840 ** returns a pointer to its buffer instead of the number of
78841 ** characters actually written into the buffer. {END} We admit that
78842 ** the number of characters written would be a more useful return
78843 ** value but we cannot change the implementation of sqlite3_snprintf()
78844 ** now without breaking compatibility.
78845 **
78846 ** {F17406} As long as the buffer size is greater than zero, sqlite3_snprintf()
78847 ** guarantees that the buffer is always zero-terminated. {F17407} The first
78848 ** parameter "n" is the total size of the buffer, including space for
78849 ** the zero terminator.  {END} So the longest string that can be completely
78850 ** written will be n-1 characters.
78851 **
78852 ** These routines all implement some additional formatting
78853 ** options that are useful for constructing SQL statements.
78854 ** All of the usual printf formatting options apply.  In addition, there
78855 ** is are "%q", "%Q", and "%z" options.
78856 **
78857 ** {F17410} The %q option works like %s in that it substitutes a null-terminated
78858 ** string from the argument list.  But %q also doubles every '\'' character.
78859 ** %q is designed for use inside a string literal. {END} By doubling each '\''
78860 ** character it escapes that character and allows it to be inserted into
78861 ** the string.
78862 **
78863 ** For example, so some string variable contains text as follows:
78864 **
78865 ** <blockquote><pre>
78866 **  char *zText = "It's a happy day!";
78867 ** </pre></blockquote>
78868 **
78869 ** One can use this text in an SQL statement as follows:
78870 **
78871 ** <blockquote><pre>
78872 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
78873 **  sqlite3_exec(db, zSQL, 0, 0, 0);
78874 **  sqlite3_free(zSQL);
78875 ** </pre></blockquote>
78876 **
78877 ** Because the %q format string is used, the '\'' character in zText
78878 ** is escaped and the SQL generated is as follows:
78879 **
78880 ** <blockquote><pre>
78881 **  INSERT INTO table1 VALUES('It''s a happy day!')
78882 ** </pre></blockquote>
78883 **
78884 ** This is correct.  Had we used %s instead of %q, the generated SQL
78885 ** would have looked like this:
78886 **
78887 ** <blockquote><pre>
78888 **  INSERT INTO table1 VALUES('It's a happy day!');
78889 ** </pre></blockquote>
78890 **
78891 ** This second example is an SQL syntax error.  As a general rule you
78892 ** should always use %q instead of %s when inserting text into a string 
78893 ** literal.
78894 **
78895 ** {F17411} The %Q option works like %q except it also adds single quotes around
78896 ** the outside of the total string.  Or if the parameter in the argument
78897 ** list is a NULL pointer, %Q substitutes the text "NULL" (without single
78898 ** quotes) in place of the %Q option. {END}  So, for example, one could say:
78899 **
78900 ** <blockquote><pre>
78901 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
78902 **  sqlite3_exec(db, zSQL, 0, 0, 0);
78903 **  sqlite3_free(zSQL);
78904 ** </pre></blockquote>
78905 **
78906 ** The code above will render a correct SQL statement in the zSQL
78907 ** variable even if the zText variable is a NULL pointer.
78908 **
78909 ** {F17412} The "%z" formatting option works exactly like "%s" with the
78910 ** addition that after the string has been read and copied into
78911 ** the result, [sqlite3_free()] is called on the input string. {END}
78912 */
78913 char *sqlite3_mprintf(const char*,...);
78914 char *sqlite3_vmprintf(const char*, va_list);
78915 char *sqlite3_snprintf(int,char*,const char*, ...);
78916
78917 /*
78918 ** CAPI3REF: Memory Allocation Subsystem {F17300}
78919 **
78920 ** {F17301} The SQLite core  uses these three routines for all of its own
78921 ** internal memory allocation needs. {END}  "Core" in the previous sentence
78922 ** does not include operating-system specific VFS implementation.  The
78923 ** windows VFS uses native malloc and free for some operations.
78924 **
78925 ** {F17302} The sqlite3_malloc() routine returns a pointer to a block
78926 ** of memory at least N bytes in length, where N is the parameter.
78927 ** {F17303} If sqlite3_malloc() is unable to obtain sufficient free
78928 ** memory, it returns a NULL pointer.  {F17304} If the parameter N to
78929 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
78930 ** a NULL pointer.
78931 **
78932 ** {F17305} Calling sqlite3_free() with a pointer previously returned
78933 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
78934 ** that it might be reused.  {F17306} The sqlite3_free() routine is
78935 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
78936 ** to sqlite3_free() is harmless.  {U17307} After being freed, memory
78937 ** should neither be read nor written.  Even reading previously freed
78938 ** memory might result in a segmentation fault or other severe error.
78939 ** {U17309} Memory corruption, a segmentation fault, or other severe error
78940 ** might result if sqlite3_free() is called with a non-NULL pointer that
78941 ** was not obtained from sqlite3_malloc() or sqlite3_free().
78942 **
78943 ** {F17310} The sqlite3_realloc() interface attempts to resize a
78944 ** prior memory allocation to be at least N bytes, where N is the
78945 ** second parameter.  The memory allocation to be resized is the first
78946 ** parameter.  {F17311} If the first parameter to sqlite3_realloc()
78947 ** is a NULL pointer then its behavior is identical to calling
78948 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
78949 ** {F17312} If the second parameter to sqlite3_realloc() is zero or
78950 ** negative then the behavior is exactly the same as calling
78951 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
78952 ** {F17313} Sqlite3_realloc() returns a pointer to a memory allocation
78953 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
78954 ** {F17314} If M is the size of the prior allocation, then min(N,M) bytes
78955 ** of the prior allocation are copied into the beginning of buffer returned
78956 ** by sqlite3_realloc() and the prior allocation is freed.
78957 ** {F17315} If sqlite3_realloc() returns NULL, then the prior allocation
78958 ** is not freed.
78959 **
78960 ** {F17316} The memory returned by sqlite3_malloc() and sqlite3_realloc()
78961 ** is always aligned to at least an 8 byte boundary. {END}
78962 **
78963 ** {F17381} The default implementation
78964 ** of the memory allocation subsystem uses the malloc(), realloc()
78965 ** and free() provided by the standard C library. {F17382} However, if 
78966 ** SQLite is compiled with the following C preprocessor macro
78967 **
78968 ** <blockquote> SQLITE_MEMORY_SIZE=<i>NNN</i> </blockquote>
78969 **
78970 ** where <i>NNN</i> is an integer, then SQLite create a static
78971 ** array of at least <i>NNN</i> bytes in size and use that array
78972 ** for all of its dynamic memory allocation needs. {END}  Additional
78973 ** memory allocator options may be added in future releases.
78974 **
78975 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
78976 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
78977 ** implementation of these routines to be omitted.  That capability
78978 ** is no longer provided.  Only built-in memory allocators can be
78979 ** used.
78980 **
78981 ** The windows OS interface layer calls
78982 ** the system malloc() and free() directly when converting
78983 ** filenames between the UTF-8 encoding used by SQLite
78984 ** and whatever filename encoding is used by the particular windows
78985 ** installation.  Memory allocation errors are detected, but
78986 ** they are reported back as [SQLITE_CANTOPEN] or
78987 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
78988 */
78989 void *sqlite3_malloc(int);
78990 void *sqlite3_realloc(void*, int);
78991 void sqlite3_free(void*);
78992
78993 /*
78994 ** CAPI3REF: Memory Allocator Statistics {F17370}
78995 **
78996 ** In addition to the basic three allocation routines 
78997 ** [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()],
78998 ** the memory allocation subsystem included with the SQLite
78999 ** sources provides the interfaces shown here.
79000 **
79001 ** {F17371} The sqlite3_memory_used() routine returns the
79002 ** number of bytes of memory currently outstanding (malloced but not freed).
79003 ** {F17372} The value returned by sqlite3_memory_used() includes
79004 ** any overhead added by SQLite, but not overhead added by the
79005 ** library malloc() that backs the sqlite3_malloc() implementation.
79006 ** {F17373} The sqlite3_memory_highwater() routines returns the
79007 ** maximum number of bytes that have been outstanding at any time
79008 ** since the highwater mark was last reset.
79009 ** {F17374} The byte count returned by sqlite3_memory_highwater()
79010 ** uses the same byte counting rules as sqlite3_memory_used(). {END}
79011 ** In other words, overhead added internally by SQLite is counted,
79012 ** but overhead from the underlying system malloc is not.
79013 ** {F17375} If the parameter to sqlite3_memory_highwater() is true,
79014 ** then the highwater mark is reset to the current value of
79015 ** sqlite3_memory_used() and the prior highwater mark (before the
79016 ** reset) is returned.  {F17376}  If the parameter to 
79017 ** sqlite3_memory_highwater() is zero, then the highwater mark is
79018 ** unchanged.
79019 */
79020 sqlite3_int64 sqlite3_memory_used(void);
79021 sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
79022
79023 /*
79024 ** CAPI3REF: Compile-Time Authorization Callbacks {F12500}
79025 **
79026 ** {F12501} This routine registers a authorizer callback with a particular
79027 ** database connection, supplied in the first argument. {F12502}
79028 ** The authorizer callback is invoked as SQL statements are being compiled
79029 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
79030 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  {F12503} At various
79031 ** points during the compilation process, as logic is being created
79032 ** to perform various actions, the authorizer callback is invoked to
79033 ** see if those actions are allowed.  The authorizer callback should
79034 ** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the
79035 ** specific action but allow the SQL statement to continue to be
79036 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
79037 ** rejected with an error.  {F12504} If the authorizer callback returns
79038 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
79039 ** then [sqlite3_prepare_v2()] or equivalent call that triggered
79040 ** the authorizer shall
79041 ** fail with an SQLITE_ERROR error code and an appropriate error message. {END}
79042 **
79043 ** When the callback returns [SQLITE_OK], that means the operation
79044 ** requested is ok.  {F12505} When the callback returns [SQLITE_DENY], the
79045 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
79046 ** authorizer shall fail
79047 ** with an SQLITE_ERROR error code and an error message explaining that
79048 ** access is denied. {F12506} If the authorizer code (the 2nd parameter
79049 ** to the authorizer callback is anything other than [SQLITE_READ], then
79050 ** a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. 
79051 ** If the authorizer code is [SQLITE_READ] and the callback returns
79052 ** [SQLITE_IGNORE] then the prepared statement is constructed to
79053 ** insert a NULL value in place of the table column that would have
79054 ** been read if [SQLITE_OK] had been returned. {END}
79055 **
79056 ** {F12510} The first parameter to the authorizer callback is a copy of
79057 ** the third parameter to the sqlite3_set_authorizer() interface.
79058 ** {F12511} The second parameter to the callback is an integer 
79059 ** [SQLITE_COPY | action code] that specifies the particular action
79060 ** to be authorized. {END} The available action codes are
79061 ** [SQLITE_COPY | documented separately].  {F12512} The third through sixth
79062 ** parameters to the callback are zero-terminated strings that contain 
79063 ** additional details about the action to be authorized. {END}
79064 **
79065 ** An authorizer is used when preparing SQL statements from an untrusted
79066 ** source, to ensure that the SQL statements do not try to access data
79067 ** that they are not allowed to see, or that they do not try to
79068 ** execute malicious statements that damage the database.  For
79069 ** example, an application may allow a user to enter arbitrary
79070 ** SQL queries for evaluation by a database.  But the application does
79071 ** not want the user to be able to make arbitrary changes to the
79072 ** database.  An authorizer could then be put in place while the
79073 ** user-entered SQL is being prepared that disallows everything
79074 ** except SELECT statements.  
79075 **
79076 ** {F12520} Only a single authorizer can be in place on a database connection
79077 ** at a time.  Each call to sqlite3_set_authorizer overrides the
79078 ** previous call. {F12521}  A NULL authorizer means that no authorization
79079 ** callback is invoked.  {F12522} The default authorizer is NULL. {END}
79080 **
79081 ** Note that the authorizer callback is invoked only during 
79082 ** [sqlite3_prepare()] or its variants.  {F12523} Authorization is not
79083 ** performed during statement evaluation in [sqlite3_step()]. {END}
79084 */
79085 int sqlite3_set_authorizer(
79086   sqlite3*,
79087   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
79088   void *pUserData
79089 );
79090
79091 /*
79092 ** CAPI3REF: Authorizer Return Codes {F12590}
79093 **
79094 ** The [sqlite3_set_authorizer | authorizer callback function] must
79095 ** return either [SQLITE_OK] or one of these two constants in order
79096 ** to signal SQLite whether or not the action is permitted.  See the
79097 ** [sqlite3_set_authorizer | authorizer documentation] for additional
79098 ** information.
79099 */
79100 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
79101 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
79102
79103 /*
79104 ** CAPI3REF: Authorizer Action Codes {F12550}
79105 **
79106 ** The [sqlite3_set_authorizer()] interface registers a callback function
79107 ** that is invoked to authorizer certain SQL statement actions.  {F12551} The
79108 ** second parameter to the callback is an integer code that specifies
79109 ** what action is being authorized.  These are the integer action codes that
79110 ** the authorizer callback may be passed. {END}
79111 **
79112 ** These action code values signify what kind of operation is to be 
79113 ** authorized.  {F12552} The 3rd and 4th parameters to the authorization
79114 ** callback function will be parameters or NULL depending on which of these
79115 ** codes is used as the second parameter. {F12553} The 5th parameter to the
79116 ** authorizer callback is the name of the database ("main", "temp", 
79117 ** etc.) if applicable. {F12554} The 6th parameter to the authorizer callback
79118 ** is the name of the inner-most trigger or view that is responsible for
79119 ** the access attempt or NULL if this access attempt is directly from 
79120 ** top-level SQL code.
79121 */
79122 /******************************************* 3rd ************ 4th ***********/
79123 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
79124 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
79125 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
79126 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
79127 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
79128 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
79129 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
79130 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
79131 #define SQLITE_DELETE                9   /* Table Name      NULL            */
79132 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
79133 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
79134 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
79135 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
79136 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
79137 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
79138 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
79139 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
79140 #define SQLITE_INSERT               18   /* Table Name      NULL            */
79141 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
79142 #define SQLITE_READ                 20   /* Table Name      Column Name     */
79143 #define SQLITE_SELECT               21   /* NULL            NULL            */
79144 #define SQLITE_TRANSACTION          22   /* NULL            NULL            */
79145 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
79146 #define SQLITE_ATTACH               24   /* Filename        NULL            */
79147 #define SQLITE_DETACH               25   /* Database Name   NULL            */
79148 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
79149 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
79150 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
79151 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
79152 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
79153 #define SQLITE_FUNCTION             31   /* Function Name   NULL            */
79154 #define SQLITE_COPY                  0   /* No longer used */
79155
79156 /*
79157 ** CAPI3REF: Tracing And Profiling Functions {F12280}
79158 **
79159 ** These routines register callback functions that can be used for
79160 ** tracing and profiling the execution of SQL statements.
79161 **
79162 ** {F12281} The callback function registered by sqlite3_trace() is invoked
79163 ** at the first [sqlite3_step()] for the evaluation of an SQL statement.
79164 ** {F12282} Only a single trace callback can be registered at a time.
79165 ** Each call to sqlite3_trace() overrides the previous.  {F12283} A
79166 ** NULL callback for sqlite3_trace() disables tracing.  {F12284} The
79167 ** first argument to the trace callback is a copy of the pointer which
79168 ** was the 3rd argument to sqlite3_trace.  {F12285} The second argument
79169 ** to the trace callback is a zero-terminated UTF8 string containing
79170 ** the original text of the SQL statement as it was passed into
79171 ** [sqlite3_prepare_v2()] or the equivalent. {END}  Note that the
79172 ** host parameter are not expanded in the SQL statement text.
79173 **
79174 ** {F12287} The callback function registered by sqlite3_profile() is invoked
79175 ** as each SQL statement finishes.  {F12288} The first parameter to the
79176 ** profile callback is a copy of the 3rd parameter to sqlite3_profile().
79177 ** {F12289} The second parameter to the profile callback is a
79178 ** zero-terminated UTF-8 string that contains the complete text of
79179 ** the SQL statement as it was processed by [sqlite3_prepare_v2()] or
79180 ** the equivalent.  {F12290} The third parameter to the profile 
79181 ** callback is an estimate of the number of nanoseconds of
79182 ** wall-clock time required to run the SQL statement from start
79183 ** to finish. {END}  
79184 **
79185 ** The sqlite3_profile() API is currently considered experimental and
79186 ** is subject to change.
79187 */
79188 void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
79189 void *sqlite3_profile(sqlite3*,
79190    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
79191
79192 /*
79193 ** CAPI3REF: Query Progress Callbacks {F12910}
79194 **
79195 ** {F12911} This routine configures a callback function - the
79196 ** progress callback - that is invoked periodically during long
79197 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
79198 ** [sqlite3_get_table()]. {END}  An example use for this 
79199 ** interface is to keep a GUI updated during a large query.
79200 **
79201 ** {F12912} The progress callback is invoked once for every N virtual
79202 ** machine opcodes, where N is the second argument to this function.
79203 ** {F12913} The progress callback itself is identified by the third
79204 ** argument to this function. {F12914} The fourth argument to this
79205 ** function is a void pointer passed to the progress callback
79206 ** function each time it is invoked. {END}
79207 **
79208 ** {F12915} If a call to [sqlite3_exec()], [sqlite3_step()], or
79209 ** [sqlite3_get_table()] results in fewer than N opcodes being executed,
79210 ** then the progress callback is never invoked. {END}
79211 ** 
79212 ** {F12916} Only a single progress callback function may be registered for each
79213 ** open database connection.  Every call to sqlite3_progress_handler()
79214 ** overwrites the results of the previous call. {F12917}
79215 ** To remove the progress callback altogether, pass NULL as the third
79216 ** argument to this function. {END}
79217 **
79218 ** {F12918} If the progress callback returns a result other than 0, then
79219 ** the current query is immediately terminated and any database changes
79220 ** rolled back. {F12919}
79221 ** The containing [sqlite3_exec()], [sqlite3_step()], or
79222 ** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. {END}  This feature
79223 ** can be used, for example, to implement the "Cancel" button on a
79224 ** progress dialog box in a GUI.
79225 */
79226 void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
79227
79228 /*
79229 ** CAPI3REF: Opening A New Database Connection {F12700}
79230 **
79231 ** {F12701} These routines open an SQLite database file whose name
79232 ** is given by the filename argument.
79233 ** {F12702} The filename argument is interpreted as UTF-8
79234 ** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16
79235 ** in the native byte order for [sqlite3_open16()].
79236 ** {F12703} An [sqlite3*] handle is returned in *ppDb, even
79237 ** if an error occurs.  {F12723} (Exception: if SQLite is unable
79238 ** to allocate memory to hold the [sqlite3] object, a NULL will
79239 ** be written into *ppDb instead of a pointer to the [sqlite3] object.)
79240 ** {F12704} If the database is opened (and/or created)
79241 ** successfully, then [SQLITE_OK] is returned.  {F12705} Otherwise an
79242 ** error code is returned.  {F12706} The
79243 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()]  routines can be used to obtain
79244 ** an English language description of the error.
79245 **
79246 ** {F12707} The default encoding for the database will be UTF-8 if
79247 ** [sqlite3_open()] or [sqlite3_open_v2()] is called and
79248 ** UTF-16 in the native byte order if [sqlite3_open16()] is used.
79249 **
79250 ** {F12708} Whether or not an error occurs when it is opened, resources
79251 ** associated with the [sqlite3*] handle should be released by passing it
79252 ** to [sqlite3_close()] when it is no longer required.
79253 **
79254 ** {F12709} The [sqlite3_open_v2()] interface works like [sqlite3_open()] 
79255 ** except that it acccepts two additional parameters for additional control
79256 ** over the new database connection.  {F12710} The flags parameter can be
79257 ** one of:
79258 **
79259 ** <ol>
79260 ** <li>  [SQLITE_OPEN_READONLY]
79261 ** <li>  [SQLITE_OPEN_READWRITE]
79262 ** <li>  [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
79263 ** </ol>
79264 **
79265 ** {F12711} The first value opens the database read-only. 
79266 ** {F12712} If the database does not previously exist, an error is returned.
79267 ** {F12713} The second option opens
79268 ** the database for reading and writing if possible, or reading only if
79269 ** if the file is write protected.  {F12714} In either case the database
79270 ** must already exist or an error is returned.  {F12715} The third option
79271 ** opens the database for reading and writing and creates it if it does
79272 ** not already exist. {F12716}
79273 ** The third options is behavior that is always used for [sqlite3_open()]
79274 ** and [sqlite3_open16()].
79275 **
79276 ** {F12717} If the filename is ":memory:", then an private
79277 ** in-memory database is created for the connection. {F12718} This in-memory
79278 ** database will vanish when the database connection is closed. {END}  Future
79279 ** version of SQLite might make use of additional special filenames
79280 ** that begin with the ":" character.  It is recommended that 
79281 ** when a database filename really does begin with
79282 ** ":" that you prefix the filename with a pathname like "./" to
79283 ** avoid ambiguity.
79284 **
79285 ** {F12719} If the filename is an empty string, then a private temporary
79286 ** on-disk database will be created.  {F12720} This private database will be
79287 ** automatically deleted as soon as the database connection is closed.
79288 **
79289 ** {F12721} The fourth parameter to sqlite3_open_v2() is the name of the
79290 ** [sqlite3_vfs] object that defines the operating system 
79291 ** interface that the new database connection should use.  {F12722} If the
79292 ** fourth parameter is a NULL pointer then the default [sqlite3_vfs]
79293 ** object is used. {END}
79294 **
79295 ** <b>Note to windows users:</b>  The encoding used for the filename argument
79296 ** of [sqlite3_open()] and [sqlite3_open_v2()] must be UTF-8, not whatever
79297 ** codepage is currently defined.  Filenames containing international
79298 ** characters must be converted to UTF-8 prior to passing them into
79299 ** [sqlite3_open()] or [sqlite3_open_v2()].
79300 */
79301 int sqlite3_open(
79302   const char *filename,   /* Database filename (UTF-8) */
79303   sqlite3 **ppDb          /* OUT: SQLite db handle */
79304 );
79305 int sqlite3_open16(
79306   const void *filename,   /* Database filename (UTF-16) */
79307   sqlite3 **ppDb          /* OUT: SQLite db handle */
79308 );
79309 int sqlite3_open_v2(
79310   const char *filename,   /* Database filename (UTF-8) */
79311   sqlite3 **ppDb,         /* OUT: SQLite db handle */
79312   int flags,              /* Flags */
79313   const char *zVfs        /* Name of VFS module to use */
79314 );
79315
79316 /*
79317 ** CAPI3REF: Error Codes And Messages {F12800}
79318 **
79319 ** {F12801} The sqlite3_errcode() interface returns the numeric
79320 ** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code]
79321 ** for the most recent failed sqlite3_* API call associated
79322 ** with [sqlite3] handle 'db'. {U12802} If a prior API call failed but the
79323 ** most recent API call succeeded, the return value from sqlite3_errcode()
79324 ** is undefined. {END}
79325 **
79326 ** {F12803} The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
79327 ** text that describes the error, as either UTF8 or UTF16 respectively.
79328 ** {F12804} Memory to hold the error message string is managed internally.
79329 ** {U12805} The 
79330 ** string may be overwritten or deallocated by subsequent calls to SQLite
79331 ** interface functions. {END}
79332 **
79333 ** {F12806} Calls to many sqlite3_* functions set the error code and
79334 ** string returned by [sqlite3_errcode()], [sqlite3_errmsg()], and
79335 ** [sqlite3_errmsg16()] overwriting the previous values.  {F12807}
79336 ** Except, calls to [sqlite3_errcode()],
79337 ** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the
79338 ** results of future invocations.  {F12808} Calls to API routines that
79339 ** do not return an error code (example: [sqlite3_data_count()]) do not
79340 ** change the error code returned by this routine.  {F12809} Interfaces that
79341 ** are not associated with a specific database connection (examples:
79342 ** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change
79343 ** the return code. {END}
79344 **
79345 ** {F12810} Assuming no other intervening sqlite3_* API calls are made,
79346 ** the error code returned by this function is associated with the same
79347 ** error as the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()].
79348 */
79349 int sqlite3_errcode(sqlite3 *db);
79350 const char *sqlite3_errmsg(sqlite3*);
79351 const void *sqlite3_errmsg16(sqlite3*);
79352
79353 /*
79354 ** CAPI3REF: SQL Statement Object {F13000}
79355 **
79356 ** An instance of this object represent single SQL statements.  This
79357 ** object is variously known as a "prepared statement" or a 
79358 ** "compiled SQL statement" or simply as a "statement".
79359 ** 
79360 ** The life of a statement object goes something like this:
79361 **
79362 ** <ol>
79363 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
79364 **      function.
79365 ** <li> Bind values to host parameters using
79366 **      [sqlite3_bind_blob | sqlite3_bind_* interfaces].
79367 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
79368 ** <li> Reset the statement using [sqlite3_reset()] then go back
79369 **      to step 2.  Do this zero or more times.
79370 ** <li> Destroy the object using [sqlite3_finalize()].
79371 ** </ol>
79372 **
79373 ** Refer to documentation on individual methods above for additional
79374 ** information.
79375 */
79376 typedef struct sqlite3_stmt sqlite3_stmt;
79377
79378 /*
79379 ** CAPI3REF: Compiling An SQL Statement {F13010}
79380 **
79381 ** To execute an SQL query, it must first be compiled into a byte-code
79382 ** program using one of these routines. 
79383 **
79384 ** {F13011} The first argument "db" is an [sqlite3 | SQLite database handle] 
79385 ** obtained from a prior call to [sqlite3_open()], [sqlite3_open_v2()]
79386 ** or [sqlite3_open16()]. {F13012}
79387 ** The second argument "zSql" is the statement to be compiled, encoded
79388 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
79389 ** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2()
79390 ** use UTF-16. {END}
79391 **
79392 ** {F13013} If the nByte argument is less
79393 ** than zero, then zSql is read up to the first zero terminator.
79394 ** {F13014} If nByte is non-negative, then it is the maximum number of 
79395 ** bytes read from zSql.  When nByte is non-negative, the
79396 ** zSql string ends at either the first '\000' or '\u0000' character or 
79397 ** until the nByte-th byte, whichever comes first. {END}
79398 **
79399 ** {F13015} *pzTail is made to point to the first byte past the end of the
79400 ** first SQL statement in zSql.  These routines only compiles the first
79401 ** statement in zSql, so *pzTail is left pointing to what remains
79402 ** uncompiled. {END}
79403 **
79404 ** {F13016} *ppStmt is left pointing to a compiled 
79405 ** [sqlite3_stmt | SQL statement structure] that can be
79406 ** executed using [sqlite3_step()].  Or if there is an error, *ppStmt may be
79407 ** set to NULL.  {F13017} If the input text contains no SQL (if the input
79408 ** is and empty string or a comment) then *ppStmt is set to NULL.
79409 ** {U13018} The calling procedure is responsible for deleting the
79410 ** compiled SQL statement
79411 ** using [sqlite3_finalize()] after it has finished with it.
79412 **
79413 ** {F13019} On success, [SQLITE_OK] is returned.  Otherwise an 
79414 ** [SQLITE_ERROR | error code] is returned. {END}
79415 **
79416 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
79417 ** recommended for all new programs. The two older interfaces are retained
79418 ** for backwards compatibility, but their use is discouraged.
79419 ** {F13020} In the "v2" interfaces, the prepared statement
79420 ** that is returned (the [sqlite3_stmt] object) contains a copy of the 
79421 ** original SQL text. {END} This causes the [sqlite3_step()] interface to
79422 ** behave a differently in two ways:
79423 **
79424 ** <ol>
79425 ** <li>{F13022}
79426 ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
79427 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
79428 ** statement and try to run it again. {F12023} If the schema has changed in
79429 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
79430 ** return [SQLITE_SCHEMA].  {END} But unlike the legacy behavior, 
79431 ** [SQLITE_SCHEMA] is now a fatal error.  {F12024} Calling
79432 ** [sqlite3_prepare_v2()] again will not make the
79433 ** error go away.  {F12025} Note: use [sqlite3_errmsg()] to find the text
79434 ** of the parsing error that results in an [SQLITE_SCHEMA] return. {END}
79435 ** </li>
79436 **
79437 ** <li>
79438 ** {F13030} When an error occurs, 
79439 ** [sqlite3_step()] will return one of the detailed 
79440 ** [SQLITE_ERROR | result codes] or
79441 ** [SQLITE_IOERR_READ | extended result codes].  {F13031}
79442 ** The legacy behavior was that [sqlite3_step()] would only return a generic
79443 ** [SQLITE_ERROR] result code and you would have to make a second call to
79444 ** [sqlite3_reset()] in order to find the underlying cause of the problem.
79445 ** {F13032}
79446 ** With the "v2" prepare interfaces, the underlying reason for the error is
79447 ** returned immediately. {END}
79448 ** </li>
79449 ** </ol>
79450 */
79451 int sqlite3_prepare(
79452   sqlite3 *db,            /* Database handle */
79453   const char *zSql,       /* SQL statement, UTF-8 encoded */
79454   int nByte,              /* Maximum length of zSql in bytes. */
79455   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
79456   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
79457 );
79458 int sqlite3_prepare_v2(
79459   sqlite3 *db,            /* Database handle */
79460   const char *zSql,       /* SQL statement, UTF-8 encoded */
79461   int nByte,              /* Maximum length of zSql in bytes. */
79462   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
79463   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
79464 );
79465 int sqlite3_prepare16(
79466   sqlite3 *db,            /* Database handle */
79467   const void *zSql,       /* SQL statement, UTF-16 encoded */
79468   int nByte,              /* Maximum length of zSql in bytes. */
79469   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
79470   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
79471 );
79472 int sqlite3_prepare16_v2(
79473   sqlite3 *db,            /* Database handle */
79474   const void *zSql,       /* SQL statement, UTF-16 encoded */
79475   int nByte,              /* Maximum length of zSql in bytes. */
79476   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
79477   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
79478 );
79479
79480 /*
79481 ** CAPIREF: Retrieving Statement SQL {F13100}
79482 **
79483 ** {F13101} If the compiled SQL statement passed as an argument was
79484 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()],
79485 ** then this function returns a pointer to a zero-terminated string
79486 ** containing a copy of the original SQL statement. {F13102} The
79487 ** pointer is valid until the statement
79488 ** is deleted using sqlite3_finalize().
79489 ** {F13103} The string returned by sqlite3_sql() is always UTF8 even
79490 ** if a UTF16 string was originally entered using [sqlite3_prepare16_v2()]
79491 ** or the equivalent.
79492 **
79493 ** {F13104} If the statement was compiled using either of the legacy
79494 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this
79495 ** function returns NULL.
79496 */
79497 const char *sqlite3_sql(sqlite3_stmt *pStmt);
79498
79499 /*
79500 ** CAPI3REF:  Dynamically Typed Value Object  {F15000}
79501 **
79502 ** {F15001} SQLite uses the sqlite3_value object to represent all values
79503 ** that are or can be stored in a database table. {END}
79504 ** SQLite uses dynamic typing for the values it stores.  
79505 ** {F15002} Values stored in sqlite3_value objects can be
79506 ** be integers, floating point values, strings, BLOBs, or NULL.
79507 */
79508 typedef struct Mem sqlite3_value;
79509
79510 /*
79511 ** CAPI3REF:  SQL Function Context Object {F16001}
79512 **
79513 ** The context in which an SQL function executes is stored in an
79514 ** sqlite3_context object.  {F16002} A pointer to an sqlite3_context
79515 ** object is always first parameter to application-defined SQL functions.
79516 */
79517 typedef struct sqlite3_context sqlite3_context;
79518
79519 /*
79520 ** CAPI3REF:  Binding Values To Prepared Statements {F13500}
79521 **
79522 ** {F13501} In the SQL strings input to [sqlite3_prepare_v2()] and its
79523 ** variants, literals may be replace by a parameter in one
79524 ** of these forms:
79525 **
79526 ** <ul>
79527 ** <li>  ?
79528 ** <li>  ?NNN
79529 ** <li>  :AAA
79530 ** <li>  @AAA
79531 ** <li>  $VVV
79532 ** </ul>
79533 **
79534 ** In the parameter forms shown above NNN is an integer literal,
79535 ** AAA is an alphanumeric identifier and VVV is a variable name according
79536 ** to the syntax rules of the TCL programming language. {END}
79537 ** The values of these parameters (also called "host parameter names")
79538 ** can be set using the sqlite3_bind_*() routines defined here.
79539 **
79540 ** {F13502} The first argument to the sqlite3_bind_*() routines always
79541 ** is a pointer to the [sqlite3_stmt] object returned from
79542 ** [sqlite3_prepare_v2()] or its variants.  {F13503} The second
79543 ** argument is the index of the parameter to be set.  {F13504} The
79544 ** first parameter has an index of 1.  {F13505} When the same named
79545 ** parameter is used more than once, second and subsequent
79546 ** occurrences have the same index as the first occurrence. 
79547 ** {F13506} The index for named parameters can be looked up using the
79548 ** [sqlite3_bind_parameter_name()] API if desired.  {F13507} The index
79549 ** for "?NNN" parameters is the value of NNN.
79550 ** {F13508} The NNN value must be between 1 and the compile-time
79551 ** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). {END}
79552 ** See <a href="limits.html">limits.html</a> for additional information.
79553 **
79554 ** {F13509} The third argument is the value to bind to the parameter. {END}
79555 **
79556 ** {F13510} In those
79557 ** routines that have a fourth argument, its value is the number of bytes
79558 ** in the parameter.  To be clear: the value is the number of bytes in the
79559 ** string, not the number of characters. {F13511}  The number
79560 ** of bytes does not include the zero-terminator at the end of strings.
79561 ** {F13512}
79562 ** If the fourth parameter is negative, the length of the string is
79563 ** number of bytes up to the first zero terminator. {END}
79564 **
79565 ** {F13513}
79566 ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
79567 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
79568 ** text after SQLite has finished with it. {F13514} If the fifth argument is
79569 ** the special value [SQLITE_STATIC], then the library assumes that the
79570 ** information is in static, unmanaged space and does not need to be freed.
79571 ** {F13515} If the fifth argument has the value [SQLITE_TRANSIENT], then
79572 ** SQLite makes its own private copy of the data immediately, before
79573 ** the sqlite3_bind_*() routine returns. {END}
79574 **
79575 ** {F13520} The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
79576 ** is filled with zeros.  {F13521} A zeroblob uses a fixed amount of memory
79577 ** (just an integer to hold it size) while it is being processed. {END}
79578 ** Zeroblobs are intended to serve as place-holders for BLOBs whose
79579 ** content is later written using 
79580 ** [sqlite3_blob_open | increment BLOB I/O] routines. {F13522} A negative
79581 ** value for the zeroblob results in a zero-length BLOB. {END}
79582 **
79583 ** {F13530} The sqlite3_bind_*() routines must be called after
79584 ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and
79585 ** before [sqlite3_step()]. {F13531}
79586 ** Bindings are not cleared by the [sqlite3_reset()] routine.
79587 ** {F13532} Unbound parameters are interpreted as NULL. {END}
79588 **
79589 ** {F13540} These routines return [SQLITE_OK] on success or an error code if
79590 ** anything goes wrong.  {F13541} [SQLITE_RANGE] is returned if the parameter
79591 ** index is out of range.  {F13542} [SQLITE_NOMEM] is returned if malloc fails.
79592 ** {F13543} [SQLITE_MISUSE] is returned if these routines are called on a
79593 ** virtual machine that is the wrong state or which has already been finalized.
79594 */
79595 int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
79596 int sqlite3_bind_double(sqlite3_stmt*, int, double);
79597 int sqlite3_bind_int(sqlite3_stmt*, int, int);
79598 int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
79599 int sqlite3_bind_null(sqlite3_stmt*, int);
79600 int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
79601 int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
79602 int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
79603 int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
79604
79605 /*
79606 ** CAPI3REF: Number Of Host Parameters {F13600}
79607 **
79608 ** {F13601} Return the largest host parameter index in the precompiled
79609 ** statement given as the argument. {F13602} When the host parameters
79610 ** are of the forms like ":AAA", "$VVV", "@AAA", or "?",
79611 ** then they are assigned sequential increasing numbers beginning
79612 ** with one, so the value returned is the number of parameters.
79613 ** {F13603} However
79614 ** if the same host parameter name is used multiple times, each occurrance
79615 ** is given the same number, so the value returned in that case is the number
79616 ** of unique host parameter names. {F13604} If host parameters of the
79617 ** form "?NNN" are used (where NNN is an integer) then there might be
79618 ** gaps in the numbering and the value returned by this interface is
79619 ** the index of the host parameter with the largest index value. {END}
79620 **
79621 ** {U13605} The prepared statement must not be [sqlite3_finalize | finalized]
79622 ** prior to this routine returning.  Otherwise the results are undefined
79623 ** and probably undesirable.
79624 */
79625 int sqlite3_bind_parameter_count(sqlite3_stmt*);
79626
79627 /*
79628 ** CAPI3REF: Name Of A Host Parameter {F13620}
79629 **
79630 ** {F13621} This routine returns a pointer to the name of the n-th
79631 ** parameter in a [sqlite3_stmt | prepared statement]. {F13622}
79632 ** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name
79633 ** which is the string ":AAA" or "@AAA" or "$VVV". 
79634 ** In other words, the initial ":" or "$" or "@"
79635 ** is included as part of the name.  {F13626}
79636 ** Parameters of the form "?" or "?NNN" have no name.
79637 **
79638 ** {F13623} The first host parameter has an index of 1, not 0.
79639 **
79640 ** {F13624} If the value n is out of range or if the n-th parameter is
79641 ** nameless, then NULL is returned.  {F13625} The returned string is
79642 ** always in the UTF-8 encoding even if the named parameter was
79643 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
79644 ** [sqlite3_prepare16_v2()].
79645 */
79646 const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
79647
79648 /*
79649 ** CAPI3REF: Index Of A Parameter With A Given Name {F13640}
79650 **
79651 ** {F13641} This routine returns the index of a host parameter with the
79652 ** given name.  {F13642} The name must match exactly.  {F13643}
79653 ** If no parameter with the given name is found, return 0.
79654 ** {F13644} Parameter names must be UTF8.
79655 */
79656 int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
79657
79658 /*
79659 ** CAPI3REF: Reset All Bindings On A Prepared Statement {F13660}
79660 **
79661 ** {F13661} Contrary to the intuition of many, [sqlite3_reset()] does not
79662 ** reset the [sqlite3_bind_blob | bindings] on a 
79663 ** [sqlite3_stmt | prepared statement]. {F13662} Use this routine to
79664 ** reset all host parameters to NULL.
79665 */
79666 int sqlite3_clear_bindings(sqlite3_stmt*);
79667
79668 /*
79669 ** CAPI3REF: Number Of Columns In A Result Set {F13710}
79670 **
79671 ** {F13711} Return the number of columns in the result set returned by the 
79672 ** [sqlite3_stmt | compiled SQL statement]. {F13712} This routine returns 0
79673 ** if pStmt is an SQL statement that does not return data (for 
79674 ** example an UPDATE).
79675 */
79676 int sqlite3_column_count(sqlite3_stmt *pStmt);
79677
79678 /*
79679 ** CAPI3REF: Column Names In A Result Set {F13720}
79680 **
79681 ** {F13721} These routines return the name assigned to a particular column
79682 ** in the result set of a SELECT statement.  {F13722} The sqlite3_column_name()
79683 ** interface returns a pointer to a zero-terminated UTF8 string
79684 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
79685 ** UTF16 string. {F13723}  The first parameter is the
79686 ** [sqlite3_stmt | prepared statement] that implements the SELECT statement.
79687 ** The second parameter is the column number.  The left-most column is
79688 ** number 0.
79689 **
79690 ** {F13724} The returned string pointer is valid until either the 
79691 ** [sqlite3_stmt | prepared statement] is destroyed by [sqlite3_finalize()]
79692 ** or until the next call sqlite3_column_name() or sqlite3_column_name16()
79693 ** on the same column.
79694 **
79695 ** {F13725} If sqlite3_malloc() fails during the processing of either routine
79696 ** (for example during a conversion from UTF-8 to UTF-16) then a
79697 ** NULL pointer is returned.
79698 */
79699 const char *sqlite3_column_name(sqlite3_stmt*, int N);
79700 const void *sqlite3_column_name16(sqlite3_stmt*, int N);
79701
79702 /*
79703 ** CAPI3REF: Source Of Data In A Query Result {F13740}
79704 **
79705 ** {F13741} These routines provide a means to determine what column of what
79706 ** table in which database a result of a SELECT statement comes from.
79707 ** {F13742} The name of the database or table or column can be returned as
79708 ** either a UTF8 or UTF16 string.  {F13743} The _database_ routines return
79709 ** the database name, the _table_ routines return the table name, and
79710 ** the origin_ routines return the column name. {F13744}
79711 ** The returned string is valid until
79712 ** the [sqlite3_stmt | prepared statement] is destroyed using
79713 ** [sqlite3_finalize()] or until the same information is requested
79714 ** again in a different encoding.
79715 **
79716 ** {F13745} The names returned are the original un-aliased names of the
79717 ** database, table, and column.
79718 **
79719 ** {F13746} The first argument to the following calls is a 
79720 ** [sqlite3_stmt | compiled SQL statement].
79721 ** {F13747} These functions return information about the Nth column returned by 
79722 ** the statement, where N is the second function argument.
79723 **
79724 ** {F13748} If the Nth column returned by the statement is an expression
79725 ** or subquery and is not a column value, then all of these functions
79726 ** return NULL.  {F13749} Otherwise, they return the 
79727 ** name of the attached database, table and column that query result
79728 ** column was extracted from.
79729 **
79730 ** {F13750} As with all other SQLite APIs, those postfixed with "16" return
79731 ** UTF-16 encoded strings, the other functions return UTF-8. {END}
79732 **
79733 ** These APIs are only available if the library was compiled with the 
79734 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
79735 **
79736 ** {U13751}
79737 ** If two or more threads call one or more of these routines against the same
79738 ** prepared statement and column at the same time then the results are
79739 ** undefined.
79740 */
79741 const char *sqlite3_column_database_name(sqlite3_stmt*,int);
79742 const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
79743 const char *sqlite3_column_table_name(sqlite3_stmt*,int);
79744 const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
79745 const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
79746 const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
79747
79748 /*
79749 ** CAPI3REF: Declared Datatype Of A Query Result {F13760}
79750 **
79751 ** The first parameter is a [sqlite3_stmt | compiled SQL statement]. 
79752 ** {F13761} If this statement is a SELECT statement and the Nth column of the 
79753 ** returned result set of that SELECT is a table column (not an
79754 ** expression or subquery) then the declared type of the table
79755 ** column is returned.  {F13762} If the Nth column of the result set is an
79756 ** expression or subquery, then a NULL pointer is returned.
79757 ** {F13763} The returned string is always UTF-8 encoded.  {END} 
79758 ** For example, in the database schema:
79759 **
79760 ** CREATE TABLE t1(c1 VARIANT);
79761 **
79762 ** And the following statement compiled:
79763 **
79764 ** SELECT c1 + 1, c1 FROM t1;
79765 **
79766 ** Then this routine would return the string "VARIANT" for the second
79767 ** result column (i==1), and a NULL pointer for the first result column
79768 ** (i==0).
79769 **
79770 ** SQLite uses dynamic run-time typing.  So just because a column
79771 ** is declared to contain a particular type does not mean that the
79772 ** data stored in that column is of the declared type.  SQLite is
79773 ** strongly typed, but the typing is dynamic not static.  Type
79774 ** is associated with individual values, not with the containers
79775 ** used to hold those values.
79776 */
79777 const char *sqlite3_column_decltype(sqlite3_stmt *, int i);
79778 const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
79779
79780 /* 
79781 ** CAPI3REF:  Evaluate An SQL Statement {F13200}
79782 **
79783 ** After an [sqlite3_stmt | SQL statement] has been prepared with a call
79784 ** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of
79785 ** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()],
79786 ** then this function must be called one or more times to evaluate the 
79787 ** statement.
79788 **
79789 ** The details of the behavior of this sqlite3_step() interface depend
79790 ** on whether the statement was prepared using the newer "v2" interface
79791 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
79792 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
79793 ** new "v2" interface is recommended for new applications but the legacy
79794 ** interface will continue to be supported.
79795 **
79796 ** In the lagacy interface, the return value will be either [SQLITE_BUSY], 
79797 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
79798 ** With the "v2" interface, any of the other [SQLITE_OK | result code]
79799 ** or [SQLITE_IOERR_READ | extended result code] might be returned as
79800 ** well.
79801 **
79802 ** [SQLITE_BUSY] means that the database engine was unable to acquire the
79803 ** database locks it needs to do its job.  If the statement is a COMMIT
79804 ** or occurs outside of an explicit transaction, then you can retry the
79805 ** statement.  If the statement is not a COMMIT and occurs within a
79806 ** explicit transaction then you should rollback the transaction before
79807 ** continuing.
79808 **
79809 ** [SQLITE_DONE] means that the statement has finished executing
79810 ** successfully.  sqlite3_step() should not be called again on this virtual
79811 ** machine without first calling [sqlite3_reset()] to reset the virtual
79812 ** machine back to its initial state.
79813 **
79814 ** If the SQL statement being executed returns any data, then 
79815 ** [SQLITE_ROW] is returned each time a new row of data is ready
79816 ** for processing by the caller. The values may be accessed using
79817 ** the [sqlite3_column_int | column access functions].
79818 ** sqlite3_step() is called again to retrieve the next row of data.
79819 ** 
79820 ** [SQLITE_ERROR] means that a run-time error (such as a constraint
79821 ** violation) has occurred.  sqlite3_step() should not be called again on
79822 ** the VM. More information may be found by calling [sqlite3_errmsg()].
79823 ** With the legacy interface, a more specific error code (example:
79824 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
79825 ** can be obtained by calling [sqlite3_reset()] on the
79826 ** [sqlite3_stmt | prepared statement].  In the "v2" interface,
79827 ** the more specific error code is returned directly by sqlite3_step().
79828 **
79829 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
79830 ** Perhaps it was called on a [sqlite3_stmt | prepared statement] that has
79831 ** already been [sqlite3_finalize | finalized] or on one that had 
79832 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
79833 ** be the case that the same database connection is being used by two or
79834 ** more threads at the same moment in time.
79835 **
79836 ** <b>Goofy Interface Alert:</b>
79837 ** In the legacy interface, 
79838 ** the sqlite3_step() API always returns a generic error code,
79839 ** [SQLITE_ERROR], following any error other than [SQLITE_BUSY]
79840 ** and [SQLITE_MISUSE].  You must call [sqlite3_reset()] or
79841 ** [sqlite3_finalize()] in order to find one of the specific
79842 ** [SQLITE_ERROR | result codes] that better describes the error.
79843 ** We admit that this is a goofy design.  The problem has been fixed
79844 ** with the "v2" interface.  If you prepare all of your SQL statements
79845 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
79846 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the 
79847 ** more specific [SQLITE_ERROR | result codes] are returned directly
79848 ** by sqlite3_step().  The use of the "v2" interface is recommended.
79849 */
79850 int sqlite3_step(sqlite3_stmt*);
79851
79852 /*
79853 ** CAPI3REF: Number of columns in a result set {F13770}
79854 **
79855 ** Return the number of values in the current row of the result set.
79856 **
79857 ** {F13771} After a call to [sqlite3_step()] that returns [SQLITE_ROW],
79858 ** this routine
79859 ** will return the same value as the [sqlite3_column_count()] function.
79860 ** {F13772}
79861 ** After [sqlite3_step()] has returned an [SQLITE_DONE], [SQLITE_BUSY], or
79862 ** a [SQLITE_ERROR | error code], or before [sqlite3_step()] has been 
79863 ** called on the [sqlite3_stmt | prepared statement] for the first time,
79864 ** this routine returns zero.
79865 */
79866 int sqlite3_data_count(sqlite3_stmt *pStmt);
79867
79868 /*
79869 ** CAPI3REF: Fundamental Datatypes {F10265}
79870 **
79871 ** {F10266}Every value in SQLite has one of five fundamental datatypes:
79872 **
79873 ** <ul>
79874 ** <li> 64-bit signed integer
79875 ** <li> 64-bit IEEE floating point number
79876 ** <li> string
79877 ** <li> BLOB
79878 ** <li> NULL
79879 ** </ul> {END}
79880 **
79881 ** These constants are codes for each of those types.
79882 **
79883 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
79884 ** for a completely different meaning.  Software that links against both
79885 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not
79886 ** SQLITE_TEXT.
79887 */
79888 #define SQLITE_INTEGER  1
79889 #define SQLITE_FLOAT    2
79890 #define SQLITE_BLOB     4
79891 #define SQLITE_NULL     5
79892 #ifdef SQLITE_TEXT
79893 # undef SQLITE_TEXT
79894 #else
79895 # define SQLITE_TEXT     3
79896 #endif
79897 #define SQLITE3_TEXT     3
79898
79899 /*
79900 ** CAPI3REF: Results Values From A Query {F13800}
79901 **
79902 ** These routines return information about
79903 ** a single column of the current result row of a query.  In every
79904 ** case the first argument is a pointer to the 
79905 ** [sqlite3_stmt | SQL statement] that is being
79906 ** evaluated (the [sqlite3_stmt*] that was returned from 
79907 ** [sqlite3_prepare_v2()] or one of its variants) and
79908 ** the second argument is the index of the column for which information 
79909 ** should be returned.  The left-most column of the result set
79910 ** has an index of 0.
79911 **
79912 ** If the SQL statement is not currently point to a valid row, or if the
79913 ** the column index is out of range, the result is undefined. 
79914 ** These routines may only be called when the most recent call to
79915 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
79916 ** [sqlite3_reset()] nor [sqlite3_finalize()] has been call subsequently.
79917 ** If any of these routines are called after [sqlite3_reset()] or
79918 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
79919 ** something other than [SQLITE_ROW], the results are undefined.
79920 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
79921 ** are called from a different thread while any of these routines
79922 ** are pending, then the results are undefined.  
79923 **
79924 ** The sqlite3_column_type() routine returns 
79925 ** [SQLITE_INTEGER | datatype code] for the initial data type
79926 ** of the result column.  The returned value is one of [SQLITE_INTEGER],
79927 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
79928 ** returned by sqlite3_column_type() is only meaningful if no type
79929 ** conversions have occurred as described below.  After a type conversion,
79930 ** the value returned by sqlite3_column_type() is undefined.  Future
79931 ** versions of SQLite may change the behavior of sqlite3_column_type()
79932 ** following a type conversion.
79933 **
79934 ** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() 
79935 ** routine returns the number of bytes in that BLOB or string.
79936 ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
79937 ** the string to UTF-8 and then returns the number of bytes.
79938 ** If the result is a numeric value then sqlite3_column_bytes() uses
79939 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
79940 ** the number of bytes in that string.
79941 ** The value returned does not include the zero terminator at the end
79942 ** of the string.  For clarity: the value returned is the number of
79943 ** bytes in the string, not the number of characters.
79944 **
79945 ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
79946 ** even zero-length strings, are always zero terminated.  The return
79947 ** value from sqlite3_column_blob() for a zero-length blob is an arbitrary
79948 ** pointer, possibly even a NULL pointer.
79949 **
79950 ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
79951 ** but leaves the result in UTF-16 instead of UTF-8.  
79952 ** The zero terminator is not included in this count.
79953 **
79954 ** These routines attempt to convert the value where appropriate.  For
79955 ** example, if the internal representation is FLOAT and a text result
79956 ** is requested, [sqlite3_snprintf()] is used internally to do the conversion
79957 ** automatically.  The following table details the conversions that
79958 ** are applied:
79959 **
79960 ** <blockquote>
79961 ** <table border="1">
79962 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
79963 **
79964 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
79965 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
79966 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
79967 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
79968 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
79969 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
79970 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as for INTEGER->TEXT
79971 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
79972 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
79973 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
79974 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
79975 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
79976 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
79977 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
79978 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
79979 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
79980 ** </table>
79981 ** </blockquote>
79982 **
79983 ** The table above makes reference to standard C library functions atoi()
79984 ** and atof().  SQLite does not really use these functions.  It has its
79985 ** on equavalent internal routines.  The atoi() and atof() names are
79986 ** used in the table for brevity and because they are familiar to most
79987 ** C programmers.
79988 **
79989 ** Note that when type conversions occur, pointers returned by prior
79990 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
79991 ** sqlite3_column_text16() may be invalidated. 
79992 ** Type conversions and pointer invalidations might occur
79993 ** in the following cases:
79994 **
79995 ** <ul>
79996 ** <li><p>  The initial content is a BLOB and sqlite3_column_text() 
79997 **          or sqlite3_column_text16() is called.  A zero-terminator might
79998 **          need to be added to the string.</p></li>
79999 **
80000 ** <li><p>  The initial content is UTF-8 text and sqlite3_column_bytes16() or
80001 **          sqlite3_column_text16() is called.  The content must be converted
80002 **          to UTF-16.</p></li>
80003 **
80004 ** <li><p>  The initial content is UTF-16 text and sqlite3_column_bytes() or
80005 **          sqlite3_column_text() is called.  The content must be converted
80006 **          to UTF-8.</p></li>
80007 ** </ul>
80008 **
80009 ** Conversions between UTF-16be and UTF-16le are always done in place and do
80010 ** not invalidate a prior pointer, though of course the content of the buffer
80011 ** that the prior pointer points to will have been modified.  Other kinds
80012 ** of conversion are done in place when it is possible, but sometime it is
80013 ** not possible and in those cases prior pointers are invalidated.  
80014 **
80015 ** The safest and easiest to remember policy is to invoke these routines
80016 ** in one of the following ways:
80017 **
80018 **  <ul>
80019 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
80020 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
80021 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
80022 **  </ul>
80023 **
80024 ** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(),
80025 ** or sqlite3_column_text16() first to force the result into the desired
80026 ** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to
80027 ** find the size of the result.  Do not mix call to sqlite3_column_text() or
80028 ** sqlite3_column_blob() with calls to sqlite3_column_bytes16().  And do not
80029 ** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes().
80030 **
80031 ** The pointers returned are valid until a type conversion occurs as
80032 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
80033 ** [sqlite3_finalize()] is called.  The memory space used to hold strings
80034 ** and blobs is freed automatically.  Do <b>not</b> pass the pointers returned
80035 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into 
80036 ** [sqlite3_free()].
80037 **
80038 ** If a memory allocation error occurs during the evaluation of any
80039 ** of these routines, a default value is returned.  The default value
80040 ** is either the integer 0, the floating point number 0.0, or a NULL
80041 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
80042 ** [SQLITE_NOMEM].
80043 */
80044 const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
80045 int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
80046 int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
80047 double sqlite3_column_double(sqlite3_stmt*, int iCol);
80048 int sqlite3_column_int(sqlite3_stmt*, int iCol);
80049 sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
80050 const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
80051 const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
80052 int sqlite3_column_type(sqlite3_stmt*, int iCol);
80053 sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
80054
80055 /*
80056 ** CAPI3REF: Destroy A Prepared Statement Object {F13300}
80057 **
80058 ** The sqlite3_finalize() function is called to delete a 
80059 ** [sqlite3_stmt | compiled SQL statement]. If the statement was
80060 ** executed successfully, or not executed at all, then SQLITE_OK is returned.
80061 ** If execution of the statement failed then an 
80062 ** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code]
80063 ** is returned. 
80064 **
80065 ** This routine can be called at any point during the execution of the
80066 ** [sqlite3_stmt | virtual machine].  If the virtual machine has not 
80067 ** completed execution when this routine is called, that is like
80068 ** encountering an error or an interrupt.  (See [sqlite3_interrupt()].) 
80069 ** Incomplete updates may be rolled back and transactions cancelled,  
80070 ** depending on the circumstances, and the 
80071 ** [SQLITE_ERROR | result code] returned will be [SQLITE_ABORT].
80072 */
80073 int sqlite3_finalize(sqlite3_stmt *pStmt);
80074
80075 /*
80076 ** CAPI3REF: Reset A Prepared Statement Object {F13330}
80077 **
80078 ** The sqlite3_reset() function is called to reset a 
80079 ** [sqlite3_stmt | compiled SQL statement] object.
80080 ** back to its initial state, ready to be re-executed.
80081 ** Any SQL statement variables that had values bound to them using
80082 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
80083 ** Use [sqlite3_clear_bindings()] to reset the bindings.
80084 */
80085 int sqlite3_reset(sqlite3_stmt *pStmt);
80086
80087 /*
80088 ** CAPI3REF: Create Or Redefine SQL Functions {F16100}
80089 **
80090 ** The following two functions are used to add SQL functions or aggregates
80091 ** or to redefine the behavior of existing SQL functions or aggregates.  The
80092 ** difference only between the two is that the second parameter, the
80093 ** name of the (scalar) function or aggregate, is encoded in UTF-8 for
80094 ** sqlite3_create_function() and UTF-16 for sqlite3_create_function16().
80095 **
80096 ** The first argument is the [sqlite3 | database handle] that holds the
80097 ** SQL function or aggregate is to be added or redefined. If a single
80098 ** program uses more than one database handle internally, then SQL
80099 ** functions or aggregates must be added individually to each database
80100 ** handle with which they will be used.
80101 **
80102 ** The second parameter is the name of the SQL function to be created
80103 ** or redefined.
80104 ** The length of the name is limited to 255 bytes, exclusive of the 
80105 ** zero-terminator.  Note that the name length limit is in bytes, not
80106 ** characters.  Any attempt to create a function with a longer name
80107 ** will result in an SQLITE_ERROR error.
80108 **
80109 ** The third parameter is the number of arguments that the SQL function or
80110 ** aggregate takes. If this parameter is negative, then the SQL function or
80111 ** aggregate may take any number of arguments.
80112 **
80113 ** The fourth parameter, eTextRep, specifies what 
80114 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
80115 ** its parameters.  Any SQL function implementation should be able to work
80116 ** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
80117 ** more efficient with one encoding than another.  It is allowed to
80118 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
80119 ** times with the same function but with different values of eTextRep.
80120 ** When multiple implementations of the same function are available, SQLite
80121 ** will pick the one that involves the least amount of data conversion.
80122 ** If there is only a single implementation which does not care what
80123 ** text encoding is used, then the fourth argument should be
80124 ** [SQLITE_ANY].
80125 **
80126 ** The fifth parameter is an arbitrary pointer.  The implementation
80127 ** of the function can gain access to this pointer using
80128 ** [sqlite3_user_data()].
80129 **
80130 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
80131 ** pointers to C-language functions that implement the SQL
80132 ** function or aggregate. A scalar SQL function requires an implementation of
80133 ** the xFunc callback only, NULL pointers should be passed as the xStep
80134 ** and xFinal parameters. An aggregate SQL function requires an implementation
80135 ** of xStep and xFinal and NULL should be passed for xFunc. To delete an
80136 ** existing SQL function or aggregate, pass NULL for all three function
80137 ** callback.
80138 **
80139 ** It is permitted to register multiple implementations of the same
80140 ** functions with the same name but with either differing numbers of
80141 ** arguments or differing perferred text encodings.  SQLite will use
80142 ** the implementation most closely matches the way in which the
80143 ** SQL function is used.
80144 */
80145 int sqlite3_create_function(
80146   sqlite3 *,
80147   const char *zFunctionName,
80148   int nArg,
80149   int eTextRep,
80150   void*,
80151   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
80152   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
80153   void (*xFinal)(sqlite3_context*)
80154 );
80155 int sqlite3_create_function16(
80156   sqlite3*,
80157   const void *zFunctionName,
80158   int nArg,
80159   int eTextRep,
80160   void*,
80161   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
80162   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
80163   void (*xFinal)(sqlite3_context*)
80164 );
80165
80166 /*
80167 ** CAPI3REF: Text Encodings {F10267}
80168 **
80169 ** These constant define integer codes that represent the various
80170 ** text encodings supported by SQLite.
80171 */
80172 #define SQLITE_UTF8           1
80173 #define SQLITE_UTF16LE        2
80174 #define SQLITE_UTF16BE        3
80175 #define SQLITE_UTF16          4    /* Use native byte order */
80176 #define SQLITE_ANY            5    /* sqlite3_create_function only */
80177 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
80178
80179 /*
80180 ** CAPI3REF: Obsolete Functions
80181 **
80182 ** These functions are all now obsolete.  In order to maintain
80183 ** backwards compatibility with older code, we continue to support
80184 ** these functions.  However, new development projects should avoid
80185 ** the use of these functions.  To help encourage people to avoid
80186 ** using these functions, we are not going to tell you want they do.
80187 */
80188 int sqlite3_aggregate_count(sqlite3_context*);
80189 int sqlite3_expired(sqlite3_stmt*);
80190 int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
80191 int sqlite3_global_recover(void);
80192 void sqlite3_thread_cleanup(void);
80193 int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
80194
80195 /*
80196 ** CAPI3REF: Obtaining SQL Function Parameter Values {F15100}
80197 **
80198 ** The C-language implementation of SQL functions and aggregates uses
80199 ** this set of interface routines to access the parameter values on
80200 ** the function or aggregate.
80201 **
80202 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
80203 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
80204 ** define callbacks that implement the SQL functions and aggregates.
80205 ** The 4th parameter to these callbacks is an array of pointers to
80206 ** [sqlite3_value] objects.  There is one [sqlite3_value] object for
80207 ** each parameter to the SQL function.  These routines are used to
80208 ** extract values from the [sqlite3_value] objects.
80209 **
80210 ** These routines work just like the corresponding 
80211 ** [sqlite3_column_blob | sqlite3_column_* routines] except that 
80212 ** these routines take a single [sqlite3_value*] pointer instead
80213 ** of an [sqlite3_stmt*] pointer and an integer column number.
80214 **
80215 ** The sqlite3_value_text16() interface extracts a UTF16 string
80216 ** in the native byte-order of the host machine.  The
80217 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
80218 ** extract UTF16 strings as big-endian and little-endian respectively.
80219 **
80220 ** The sqlite3_value_numeric_type() interface attempts to apply
80221 ** numeric affinity to the value.  This means that an attempt is
80222 ** made to convert the value to an integer or floating point.  If
80223 ** such a conversion is possible without loss of information (in other
80224 ** words if the value is a string that looks like a number)
80225 ** then the conversion is done.  Otherwise no conversion occurs.  The 
80226 ** [SQLITE_INTEGER | datatype] after conversion is returned.
80227 **
80228 ** Please pay particular attention to the fact that the pointer that
80229 ** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or
80230 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
80231 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
80232 ** or [sqlite3_value_text16()].  
80233 **
80234 ** These routines must be called from the same thread as
80235 ** the SQL function that supplied the sqlite3_value* parameters.
80236 ** Or, if the sqlite3_value* argument comes from the [sqlite3_column_value()]
80237 ** interface, then these routines should be called from the same thread
80238 ** that ran [sqlite3_column_value()].
80239 **
80240 */
80241 const void *sqlite3_value_blob(sqlite3_value*);
80242 int sqlite3_value_bytes(sqlite3_value*);
80243 int sqlite3_value_bytes16(sqlite3_value*);
80244 double sqlite3_value_double(sqlite3_value*);
80245 int sqlite3_value_int(sqlite3_value*);
80246 sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
80247 const unsigned char *sqlite3_value_text(sqlite3_value*);
80248 const void *sqlite3_value_text16(sqlite3_value*);
80249 const void *sqlite3_value_text16le(sqlite3_value*);
80250 const void *sqlite3_value_text16be(sqlite3_value*);
80251 int sqlite3_value_type(sqlite3_value*);
80252 int sqlite3_value_numeric_type(sqlite3_value*);
80253
80254 /*
80255 ** CAPI3REF: Obtain Aggregate Function Context {F16210}
80256 **
80257 ** The implementation of aggregate SQL functions use this routine to allocate
80258 ** a structure for storing their state.  
80259 ** {F16211} The first time the sqlite3_aggregate_context() routine is
80260 ** is called for a particular aggregate, SQLite allocates nBytes of memory
80261 ** zeros that memory, and returns a pointer to it.
80262 ** {F16212} On second and subsequent calls to sqlite3_aggregate_context()
80263 ** for the same aggregate function index, the same buffer is returned. {END}
80264 ** The implementation
80265 ** of the aggregate can use the returned buffer to accumulate data.
80266 **
80267 ** {F16213} SQLite automatically frees the allocated buffer when the aggregate
80268 ** query concludes. {END}
80269 **
80270 ** The first parameter should be a copy of the 
80271 ** [sqlite3_context | SQL function context] that is the first
80272 ** parameter to the callback routine that implements the aggregate
80273 ** function.
80274 **
80275 ** This routine must be called from the same thread in which
80276 ** the aggregate SQL function is running.
80277 */
80278 void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
80279
80280 /*
80281 ** CAPI3REF: User Data For Functions {F16240}
80282 **
80283 ** {F16241} The sqlite3_user_data() interface returns a copy of
80284 ** the pointer that was the pUserData parameter (the 5th parameter)
80285 ** of the the [sqlite3_create_function()]
80286 ** and [sqlite3_create_function16()] routines that originally
80287 ** registered the application defined function. {END}
80288 **
80289 ** {U16243} This routine must be called from the same thread in which
80290 ** the application-defined function is running.
80291 */
80292 void *sqlite3_user_data(sqlite3_context*);
80293
80294 /*
80295 ** CAPI3REF: Function Auxiliary Data {F16270}
80296 **
80297 ** The following two functions may be used by scalar SQL functions to
80298 ** associate meta-data with argument values. If the same value is passed to
80299 ** multiple invocations of the same SQL function during query execution, under
80300 ** some circumstances the associated meta-data may be preserved. This may
80301 ** be used, for example, to add a regular-expression matching scalar
80302 ** function. The compiled version of the regular expression is stored as
80303 ** meta-data associated with the SQL value passed as the regular expression
80304 ** pattern.  The compiled regular expression can be reused on multiple
80305 ** invocations of the same function so that the original pattern string
80306 ** does not need to be recompiled on each invocation.
80307 **
80308 ** {F16271}
80309 ** The sqlite3_get_auxdata() interface returns a pointer to the meta-data
80310 ** associated by the sqlite3_set_auxdata() function with the Nth argument
80311 ** value to the application-defined function.
80312 ** {F16272} If no meta-data has been ever been set for the Nth
80313 ** argument of the function, or if the cooresponding function parameter
80314 ** has changed since the meta-data was set, then sqlite3_get_auxdata()
80315 ** returns a NULL pointer.
80316 **
80317 ** {F16275} The sqlite3_set_auxdata() interface saves the meta-data
80318 ** pointed to by its 3rd parameter as the meta-data for the N-th
80319 ** argument of the application-defined function. {END} Subsequent
80320 ** calls to sqlite3_get_auxdata() might return this data, if it has
80321 ** not been destroyed. 
80322 ** {F16277} If it is not NULL, SQLite will invoke the destructor 
80323 ** function given by the 4th parameter to sqlite3_set_auxdata() on
80324 ** the meta-data when the corresponding function parameter changes
80325 ** or when the SQL statement completes, whichever comes first. {END}
80326 **
80327 ** In practice, meta-data is preserved between function calls for
80328 ** expressions that are constant at compile time. This includes literal
80329 ** values and SQL variables.
80330 **
80331 ** These routines must be called from the same thread in which
80332 ** the SQL function is running.
80333 */
80334 void *sqlite3_get_auxdata(sqlite3_context*, int N);
80335 void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
80336
80337
80338 /*
80339 ** CAPI3REF: Constants Defining Special Destructor Behavior {F10280}
80340 **
80341 ** These are special value for the destructor that is passed in as the
80342 ** final argument to routines like [sqlite3_result_blob()].  If the destructor
80343 ** argument is SQLITE_STATIC, it means that the content pointer is constant
80344 ** and will never change.  It does not need to be destroyed.  The 
80345 ** SQLITE_TRANSIENT value means that the content will likely change in
80346 ** the near future and that SQLite should make its own private copy of
80347 ** the content before returning.
80348 **
80349 ** The typedef is necessary to work around problems in certain
80350 ** C++ compilers.  See ticket #2191.
80351 */
80352 typedef void (*sqlite3_destructor_type)(void*);
80353 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
80354 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
80355
80356 /*
80357 ** CAPI3REF: Setting The Result Of An SQL Function {F16400}
80358 **
80359 ** These routines are used by the xFunc or xFinal callbacks that
80360 ** implement SQL functions and aggregates.  See
80361 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
80362 ** for additional information.
80363 **
80364 ** These functions work very much like the 
80365 ** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used
80366 ** to bind values to host parameters in prepared statements.
80367 ** Refer to the
80368 ** [sqlite3_bind_blob | sqlite3_bind_* documentation] for
80369 ** additional information.
80370 **
80371 ** {F16402} The sqlite3_result_blob() interface sets the result from
80372 ** an application defined function to be the BLOB whose content is pointed
80373 ** to by the second parameter and which is N bytes long where N is the
80374 ** third parameter. 
80375 ** {F16403} The sqlite3_result_zeroblob() inerfaces set the result of
80376 ** the application defined function to be a BLOB containing all zero
80377 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
80378 **
80379 ** {F16407} The sqlite3_result_double() interface sets the result from
80380 ** an application defined function to be a floating point value specified
80381 ** by its 2nd argument.
80382 **
80383 ** {F16409} The sqlite3_result_error() and sqlite3_result_error16() functions
80384 ** cause the implemented SQL function to throw an exception.
80385 ** {F16411} SQLite uses the string pointed to by the
80386 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
80387 ** as the text of an error message. {F16412} SQLite interprets the error
80388 ** message string from sqlite3_result_error() as UTF8.  {F16413} SQLite
80389 ** interprets the string from sqlite3_result_error16() as UTF16 in native
80390 ** byte order.  {F16414} If the third parameter to sqlite3_result_error()
80391 ** or sqlite3_result_error16() is negative then SQLite takes as the error
80392 ** message all text up through the first zero character.
80393 ** {F16415} If the third parameter to sqlite3_result_error() or
80394 ** sqlite3_result_error16() is non-negative then SQLite takes that many
80395 ** bytes (not characters) from the 2nd parameter as the error message.
80396 ** {F16417} The sqlite3_result_error() and sqlite3_result_error16()
80397 ** routines make a copy private copy of the error message text before
80398 ** they return.  {END} Hence, the calling function can deallocate or
80399 ** modify the text after they return without harm.
80400 **
80401 ** {F16421} The sqlite3_result_toobig() interface causes SQLite
80402 ** to throw an error indicating that a string or BLOB is to long
80403 ** to represent.  {F16422} The sqlite3_result_nomem() interface
80404 ** causes SQLite to throw an exception indicating that the a
80405 ** memory allocation failed.
80406 **
80407 ** {F16431} The sqlite3_result_int() interface sets the return value
80408 ** of the application-defined function to be the 32-bit signed integer
80409 ** value given in the 2nd argument.
80410 ** {F16432} The sqlite3_result_int64() interface sets the return value
80411 ** of the application-defined function to be the 64-bit signed integer
80412 ** value given in the 2nd argument.
80413 **
80414 ** {F16437} The sqlite3_result_null() interface sets the return value
80415 ** of the application-defined function to be NULL.
80416 **
80417 ** {F16441} The sqlite3_result_text(), sqlite3_result_text16(), 
80418 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
80419 ** set the return value of the application-defined function to be
80420 ** a text string which is represented as UTF-8, UTF-16 native byte order,
80421 ** UTF-16 little endian, or UTF-16 big endian, respectively.
80422 ** {F16442} SQLite takes the text result from the application from
80423 ** the 2nd parameter of the sqlite3_result_text* interfaces.
80424 ** {F16444} If the 3rd parameter to the sqlite3_result_text* interfaces
80425 ** is negative, then SQLite takes result text from the 2nd parameter 
80426 ** through the first zero character.
80427 ** {F16447} If the 3rd parameter to the sqlite3_result_text* interfaces
80428 ** is non-negative, then as many bytes (not characters) of the text
80429 ** pointed to by the 2nd parameter are taken as the application-defined
80430 ** function result.
80431 ** {F16451} If the 4th parameter to the sqlite3_result_text* interfaces
80432 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
80433 ** function as the destructor on the text or blob result when it has
80434 ** finished using that result.
80435 ** {F16453} If the 4th parameter to the sqlite3_result_text* interfaces
80436 ** or sqlite3_result_blob is the special constant SQLITE_STATIC, then
80437 ** SQLite assumes that the text or blob result is constant space and
80438 ** does not copy the space or call a destructor when it has
80439 ** finished using that result.
80440 ** {F16454} If the 4th parameter to the sqlite3_result_text* interfaces
80441 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
80442 ** then SQLite makes a copy of the result into space obtained from
80443 ** from [sqlite3_malloc()] before it returns.
80444 **
80445 ** {F16461} The sqlite3_result_value() interface sets the result of
80446 ** the application-defined function to be a copy the [sqlite3_value]
80447 ** object specified by the 2nd parameter.  {F16463} The
80448 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
80449 ** so that [sqlite3_value] specified in the parameter may change or
80450 ** be deallocated after sqlite3_result_value() returns without harm.
80451 **
80452 ** {U16491} These routines are called from within the different thread 
80453 ** than the one containing the application-defined function that recieved
80454 ** the [sqlite3_context] pointer, the results are undefined.
80455 */
80456 void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
80457 void sqlite3_result_double(sqlite3_context*, double);
80458 void sqlite3_result_error(sqlite3_context*, const char*, int);
80459 void sqlite3_result_error16(sqlite3_context*, const void*, int);
80460 void sqlite3_result_error_toobig(sqlite3_context*);
80461 void sqlite3_result_error_nomem(sqlite3_context*);
80462 void sqlite3_result_int(sqlite3_context*, int);
80463 void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
80464 void sqlite3_result_null(sqlite3_context*);
80465 void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
80466 void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
80467 void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
80468 void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
80469 void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
80470 void sqlite3_result_zeroblob(sqlite3_context*, int n);
80471
80472 /*
80473 ** CAPI3REF: Define New Collating Sequences {F16600}
80474 **
80475 ** {F16601}
80476 ** These functions are used to add new collation sequences to the
80477 ** [sqlite3*] handle specified as the first argument. 
80478 **
80479 ** {F16602}
80480 ** The name of the new collation sequence is specified as a UTF-8 string
80481 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
80482 ** and a UTF-16 string for sqlite3_create_collation16(). {F16603} In all cases
80483 ** the name is passed as the second function argument.
80484 **
80485 ** {F16604}
80486 ** The third argument may be one of the constants [SQLITE_UTF8],
80487 ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
80488 ** routine expects to be passed pointers to strings encoded using UTF-8,
80489 ** UTF-16 little-endian or UTF-16 big-endian respectively. {F16605} The
80490 ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that
80491 ** the routine expects pointers to 16-bit word aligned strings
80492 ** of UTF16 in the native byte order of the host computer.
80493 **
80494 ** {F16607}
80495 ** A pointer to the user supplied routine must be passed as the fifth
80496 ** argument. {F16609} If it is NULL, this is the same as deleting the collation
80497 ** sequence (so that SQLite cannot call it anymore).
80498 ** {F16611} Each time the application
80499 ** supplied function is invoked, it is passed a copy of the void* passed as
80500 ** the fourth argument to sqlite3_create_collation() or
80501 ** sqlite3_create_collation16() as its first parameter.
80502 **
80503 ** {F16612}
80504 ** The remaining arguments to the application-supplied routine are two strings,
80505 ** each represented by a [length, data] pair and encoded in the encoding
80506 ** that was passed as the third argument when the collation sequence was
80507 ** registered. {END} The application defined collation routine should
80508 ** return negative, zero or positive if
80509 ** the first string is less than, equal to, or greater than the second
80510 ** string. i.e. (STRING1 - STRING2).
80511 **
80512 ** {F16615}
80513 ** The sqlite3_create_collation_v2() works like sqlite3_create_collation()
80514 ** excapt that it takes an extra argument which is a destructor for
80515 ** the collation.  {F16617} The destructor is called when the collation is
80516 ** destroyed and is passed a copy of the fourth parameter void* pointer
80517 ** of the sqlite3_create_collation_v2().
80518 ** {F16618}  Collations are destroyed when
80519 ** they are overridden by later calls to the collation creation functions
80520 ** or when the [sqlite3*] database handle is closed using [sqlite3_close()].
80521 */
80522 int sqlite3_create_collation(
80523   sqlite3*, 
80524   const char *zName, 
80525   int eTextRep, 
80526   void*,
80527   int(*xCompare)(void*,int,const void*,int,const void*)
80528 );
80529 int sqlite3_create_collation_v2(
80530   sqlite3*, 
80531   const char *zName, 
80532   int eTextRep, 
80533   void*,
80534   int(*xCompare)(void*,int,const void*,int,const void*),
80535   void(*xDestroy)(void*)
80536 );
80537 int sqlite3_create_collation16(
80538   sqlite3*, 
80539   const char *zName, 
80540   int eTextRep, 
80541   void*,
80542   int(*xCompare)(void*,int,const void*,int,const void*)
80543 );
80544
80545 /*
80546 ** CAPI3REF: Collation Needed Callbacks {F16700}
80547 **
80548 ** {F16701}
80549 ** To avoid having to register all collation sequences before a database
80550 ** can be used, a single callback function may be registered with the
80551 ** database handle to be called whenever an undefined collation sequence is
80552 ** required.
80553 **
80554 ** {F16702}
80555 ** If the function is registered using the sqlite3_collation_needed() API,
80556 ** then it is passed the names of undefined collation sequences as strings
80557 ** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, the names
80558 ** are passed as UTF-16 in machine native byte order. {F16704} A call to either
80559 ** function replaces any existing callback.
80560 **
80561 ** {F16705} When the callback is invoked, the first argument passed is a copy
80562 ** of the second argument to sqlite3_collation_needed() or
80563 ** sqlite3_collation_needed16(). {F16706} The second argument is the database
80564 ** handle.  {F16707} The third argument is one of [SQLITE_UTF8],
80565 ** [SQLITE_UTF16BE], or [SQLITE_UTF16LE], indicating the most
80566 ** desirable form of the collation sequence function required.
80567 ** {F16708} The fourth parameter is the name of the
80568 ** required collation sequence. {END}
80569 **
80570 ** The callback function should register the desired collation using
80571 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
80572 ** [sqlite3_create_collation_v2()].
80573 */
80574 int sqlite3_collation_needed(
80575   sqlite3*, 
80576   void*, 
80577   void(*)(void*,sqlite3*,int eTextRep,const char*)
80578 );
80579 int sqlite3_collation_needed16(
80580   sqlite3*, 
80581   void*,
80582   void(*)(void*,sqlite3*,int eTextRep,const void*)
80583 );
80584
80585 /*
80586 ** Specify the key for an encrypted database.  This routine should be
80587 ** called right after sqlite3_open().
80588 **
80589 ** The code to implement this API is not available in the public release
80590 ** of SQLite.
80591 */
80592 int sqlite3_key(
80593   sqlite3 *db,                   /* Database to be rekeyed */
80594   const void *pKey, int nKey     /* The key */
80595 );
80596
80597 /*
80598 ** Change the key on an open database.  If the current database is not
80599 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
80600 ** database is decrypted.
80601 **
80602 ** The code to implement this API is not available in the public release
80603 ** of SQLite.
80604 */
80605 int sqlite3_rekey(
80606   sqlite3 *db,                   /* Database to be rekeyed */
80607   const void *pKey, int nKey     /* The new key */
80608 );
80609
80610 /*
80611 ** CAPI3REF:  Suspend Execution For A Short Time {F10530}
80612 **
80613 ** {F10531} The sqlite3_sleep() function
80614 ** causes the current thread to suspend execution
80615 ** for at least a number of milliseconds specified in its parameter.
80616 **
80617 ** {F10532} If the operating system does not support sleep requests with 
80618 ** millisecond time resolution, then the time will be rounded up to 
80619 ** the nearest second. {F10533} The number of milliseconds of sleep actually 
80620 ** requested from the operating system is returned.
80621 **
80622 ** {F10534} SQLite implements this interface by calling the xSleep()
80623 ** method of the default [sqlite3_vfs] object. {END}
80624 */
80625 int sqlite3_sleep(int);
80626
80627 /*
80628 ** CAPI3REF:  Name Of The Folder Holding Temporary Files {F10310}
80629 **
80630 ** If this global variable is made to point to a string which is
80631 ** the name of a folder (a.ka. directory), then all temporary files
80632 ** created by SQLite will be placed in that directory.  If this variable
80633 ** is NULL pointer, then SQLite does a search for an appropriate temporary
80634 ** file directory.
80635 **
80636 ** It is not safe to modify this variable once a database connection
80637 ** has been opened.  It is intended that this variable be set once
80638 ** as part of process initialization and before any SQLite interface
80639 ** routines have been call and remain unchanged thereafter.
80640 */
80641 SQLITE_EXTERN char *sqlite3_temp_directory;
80642
80643 /*
80644 ** CAPI3REF:  Test To See If The Database Is In Auto-Commit Mode {F12930}
80645 **
80646 ** {F12931} The sqlite3_get_autocommit() interfaces returns non-zero or
80647 ** zero if the given database connection is or is not in autocommit mode,
80648 ** respectively. {F12932}  Autocommit mode is on
80649 ** by default.  {F12933} Autocommit mode is disabled by a BEGIN statement.
80650 ** {F12934} Autocommit mode is reenabled by a COMMIT or ROLLBACK. {END}
80651 **
80652 ** If certain kinds of errors occur on a statement within a multi-statement
80653 ** transactions (errors including [SQLITE_FULL], [SQLITE_IOERR], 
80654 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
80655 ** transaction might be rolled back automatically.  {F12935} The only way to
80656 ** find out if SQLite automatically rolled back the transaction after
80657 ** an error is to use this function. {END}
80658 **
80659 ** {U12936} If another thread changes the autocommit status of the database
80660 ** connection while this routine is running, then the return value
80661 ** is undefined. {END}
80662 */
80663 int sqlite3_get_autocommit(sqlite3*);
80664
80665 /*
80666 ** CAPI3REF:  Find The Database Handle Of A Prepared Statement {F13120}
80667 **
80668 ** {F13121} The sqlite3_db_handle interface
80669 ** returns the [sqlite3*] database handle to which a
80670 ** [sqlite3_stmt | prepared statement] belongs.
80671 ** {F13122} the database handle returned by sqlite3_db_handle
80672 ** is the same database handle that was
80673 ** the first argument to the [sqlite3_prepare_v2()] or its variants
80674 ** that was used to create the statement in the first place.
80675 */
80676 sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
80677
80678
80679 /*
80680 ** CAPI3REF: Commit And Rollback Notification Callbacks {F12950}
80681 **
80682 ** {F12951} The sqlite3_commit_hook() interface registers a callback
80683 ** function to be invoked whenever a transaction is committed.
80684 ** {F12952} Any callback set by a previous call to sqlite3_commit_hook()
80685 ** for the same database connection is overridden.
80686 ** {F12953} The sqlite3_rollback_hook() interface registers a callback
80687 ** function to be invoked whenever a transaction is committed.
80688 ** {F12954} Any callback set by a previous call to sqlite3_commit_hook()
80689 ** for the same database connection is overridden.
80690 ** {F12956} The pArg argument is passed through
80691 ** to the callback.  {F12957} If the callback on a commit hook function 
80692 ** returns non-zero, then the commit is converted into a rollback.
80693 **
80694 ** {F12958} If another function was previously registered, its
80695 ** pArg value is returned.  Otherwise NULL is returned.
80696 **
80697 ** {F12959} Registering a NULL function disables the callback.
80698 **
80699 ** {F12961} For the purposes of this API, a transaction is said to have been 
80700 ** rolled back if an explicit "ROLLBACK" statement is executed, or
80701 ** an error or constraint causes an implicit rollback to occur.
80702 ** {F12962} The rollback callback is not invoked if a transaction is
80703 ** automatically rolled back because the database connection is closed.
80704 ** {F12964} The rollback callback is not invoked if a transaction is
80705 ** rolled back because a commit callback returned non-zero.
80706 ** <todo> Check on this </todo> {END}
80707 **
80708 ** These are experimental interfaces and are subject to change.
80709 */
80710 void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
80711 void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
80712
80713 /*
80714 ** CAPI3REF: Data Change Notification Callbacks {F12970}
80715 **
80716 ** {F12971} The sqlite3_update_hook() interface
80717 ** registers a callback function with the database connection identified by the 
80718 ** first argument to be invoked whenever a row is updated, inserted or deleted.
80719 ** {F12972} Any callback set by a previous call to this function for the same 
80720 ** database connection is overridden.
80721 **
80722 ** {F12974} The second argument is a pointer to the function to invoke when a 
80723 ** row is updated, inserted or deleted. 
80724 ** {F12976} The first argument to the callback is
80725 ** a copy of the third argument to sqlite3_update_hook().
80726 ** {F12977} The second callback 
80727 ** argument is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
80728 ** depending on the operation that caused the callback to be invoked.
80729 ** {F12978} The third and 
80730 ** fourth arguments to the callback contain pointers to the database and 
80731 ** table name containing the affected row.
80732 ** {F12979} The final callback parameter is 
80733 ** the rowid of the row.
80734 ** {F12981} In the case of an update, this is the rowid after 
80735 ** the update takes place.
80736 **
80737 ** {F12983} The update hook is not invoked when internal system tables are
80738 ** modified (i.e. sqlite_master and sqlite_sequence).
80739 **
80740 ** {F12984} If another function was previously registered, its pArg value
80741 ** is returned.  {F12985} Otherwise NULL is returned.
80742 */
80743 void *sqlite3_update_hook(
80744   sqlite3*, 
80745   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
80746   void*
80747 );
80748
80749 /*
80750 ** CAPI3REF:  Enable Or Disable Shared Pager Cache {F10330}
80751 **
80752 ** {F10331}
80753 ** This routine enables or disables the sharing of the database cache
80754 ** and schema data structures between connections to the same database.
80755 ** {F10332}
80756 ** Sharing is enabled if the argument is true and disabled if the argument
80757 ** is false.
80758 **
80759 ** {F10333} Cache sharing is enabled and disabled
80760 ** for an entire process. {END} This is a change as of SQLite version 3.5.0.
80761 ** In prior versions of SQLite, sharing was
80762 ** enabled or disabled for each thread separately.
80763 **
80764 ** {F10334}
80765 ** The cache sharing mode set by this interface effects all subsequent
80766 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
80767 ** {F10335} Existing database connections continue use the sharing mode
80768 ** that was in effect at the time they were opened. {END}
80769 **
80770 ** Virtual tables cannot be used with a shared cache.  {F10336} When shared
80771 ** cache is enabled, the [sqlite3_create_module()] API used to register
80772 ** virtual tables will always return an error. {END}
80773 **
80774 ** {F10337} This routine returns [SQLITE_OK] if shared cache was
80775 ** enabled or disabled successfully.  {F10338} An [SQLITE_ERROR | error code]
80776 ** is returned otherwise. {END}
80777 **
80778 ** {F10339} Shared cache is disabled by default. {END} But this might change in
80779 ** future releases of SQLite.  Applications that care about shared
80780 ** cache setting should set it explicitly.
80781 */
80782 int sqlite3_enable_shared_cache(int);
80783
80784 /*
80785 ** CAPI3REF:  Attempt To Free Heap Memory {F17340}
80786 **
80787 ** {F17341} The sqlite3_release_memory() interface attempts to
80788 ** free N bytes of heap memory by deallocating non-essential memory
80789 ** allocations held by the database labrary. {END}  Memory used
80790 ** to cache database pages to improve performance is an example of
80791 ** non-essential memory.  {F16342} sqlite3_release_memory() returns
80792 ** the number of bytes actually freed, which might be more or less
80793 ** than the amount requested.
80794 */
80795 int sqlite3_release_memory(int);
80796
80797 /*
80798 ** CAPI3REF:  Impose A Limit On Heap Size {F17350}
80799 **
80800 ** {F16351} The sqlite3_soft_heap_limit() interface
80801 ** places a "soft" limit on the amount of heap memory that may be allocated
80802 ** by SQLite. {F16352} If an internal allocation is requested 
80803 ** that would exceed the soft heap limit, [sqlite3_release_memory()] is
80804 ** invoked one or more times to free up some space before the allocation
80805 ** is made. {END}
80806 **
80807 ** {F16353} The limit is called "soft", because if
80808 ** [sqlite3_release_memory()] cannot
80809 ** free sufficient memory to prevent the limit from being exceeded,
80810 ** the memory is allocated anyway and the current operation proceeds.
80811 **
80812 ** {F16354}
80813 ** A negative or zero value for N means that there is no soft heap limit and
80814 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
80815 ** {F16355} The default value for the soft heap limit is zero.
80816 **
80817 ** SQLite makes a best effort to honor the soft heap limit.  
80818 ** {F16356} But if the soft heap limit cannot honored, execution will
80819 ** continue without error or notification. {END}  This is why the limit is 
80820 ** called a "soft" limit.  It is advisory only.
80821 **
80822 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
80823 ** allocated by a single thread - the same thread in which this routine
80824 ** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
80825 ** applied to all threads. {F16357} The value specified for the soft heap limit
80826 ** is an upper bound on the total memory allocation for all threads. {END}  In
80827 ** version 3.5.0 there is no mechanism for limiting the heap usage for
80828 ** individual threads.
80829 */
80830 void sqlite3_soft_heap_limit(int);
80831
80832 /*
80833 ** CAPI3REF:  Extract Metadata About A Column Of A Table {F12850}
80834 **
80835 ** This routine
80836 ** returns meta-data about a specific column of a specific database
80837 ** table accessible using the connection handle passed as the first function 
80838 ** argument.
80839 **
80840 ** The column is identified by the second, third and fourth parameters to 
80841 ** this function. The second parameter is either the name of the database
80842 ** (i.e. "main", "temp" or an attached database) containing the specified
80843 ** table or NULL. If it is NULL, then all attached databases are searched
80844 ** for the table using the same algorithm as the database engine uses to 
80845 ** resolve unqualified table references.
80846 **
80847 ** The third and fourth parameters to this function are the table and column 
80848 ** name of the desired column, respectively. Neither of these parameters 
80849 ** may be NULL.
80850 **
80851 ** Meta information is returned by writing to the memory locations passed as
80852 ** the 5th and subsequent parameters to this function. Any of these 
80853 ** arguments may be NULL, in which case the corresponding element of meta 
80854 ** information is ommitted.
80855 **
80856 ** <pre>
80857 ** Parameter     Output Type      Description
80858 ** -----------------------------------
80859 **
80860 **   5th         const char*      Data type
80861 **   6th         const char*      Name of the default collation sequence 
80862 **   7th         int              True if the column has a NOT NULL constraint
80863 **   8th         int              True if the column is part of the PRIMARY KEY
80864 **   9th         int              True if the column is AUTOINCREMENT
80865 ** </pre>
80866 **
80867 **
80868 ** The memory pointed to by the character pointers returned for the 
80869 ** declaration type and collation sequence is valid only until the next 
80870 ** call to any sqlite API function.
80871 **
80872 ** If the specified table is actually a view, then an error is returned.
80873 **
80874 ** If the specified column is "rowid", "oid" or "_rowid_" and an 
80875 ** INTEGER PRIMARY KEY column has been explicitly declared, then the output 
80876 ** parameters are set for the explicitly declared column. If there is no
80877 ** explicitly declared IPK column, then the output parameters are set as 
80878 ** follows:
80879 **
80880 ** <pre>
80881 **     data type: "INTEGER"
80882 **     collation sequence: "BINARY"
80883 **     not null: 0
80884 **     primary key: 1
80885 **     auto increment: 0
80886 ** </pre>
80887 **
80888 ** This function may load one or more schemas from database files. If an
80889 ** error occurs during this process, or if the requested table or column
80890 ** cannot be found, an SQLITE error code is returned and an error message
80891 ** left in the database handle (to be retrieved using sqlite3_errmsg()).
80892 **
80893 ** This API is only available if the library was compiled with the
80894 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
80895 */
80896 int sqlite3_table_column_metadata(
80897   sqlite3 *db,                /* Connection handle */
80898   const char *zDbName,        /* Database name or NULL */
80899   const char *zTableName,     /* Table name */
80900   const char *zColumnName,    /* Column name */
80901   char const **pzDataType,    /* OUTPUT: Declared data type */
80902   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
80903   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
80904   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
80905   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
80906 );
80907
80908 /*
80909 ** CAPI3REF: Load An Extension {F12600}
80910 **
80911 ** {F12601} The sqlite3_load_extension() interface
80912 ** attempts to load an SQLite extension library contained in the file
80913 ** zFile. {F12602} The entry point is zProc. {F12603} zProc may be 0
80914 ** in which case the name of the entry point defaults
80915 ** to "sqlite3_extension_init".
80916 **
80917 ** {F12604} The sqlite3_load_extension() interface shall
80918 ** return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
80919 **
80920 ** {F12605}
80921 ** If an error occurs and pzErrMsg is not 0, then the
80922 ** sqlite3_load_extension() interface shall attempt to fill *pzErrMsg with 
80923 ** error message text stored in memory obtained from [sqlite3_malloc()].
80924 ** {END}  The calling function should free this memory
80925 ** by calling [sqlite3_free()].
80926 **
80927 ** {F12606}
80928 ** Extension loading must be enabled using [sqlite3_enable_load_extension()]
80929 ** prior to calling this API or an error will be returned.
80930 */
80931 int sqlite3_load_extension(
80932   sqlite3 *db,          /* Load the extension into this database connection */
80933   const char *zFile,    /* Name of the shared library containing extension */
80934   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
80935   char **pzErrMsg       /* Put error message here if not 0 */
80936 );
80937
80938 /*
80939 ** CAPI3REF:  Enable Or Disable Extension Loading {F12620}
80940 **
80941 ** So as not to open security holes in older applications that are
80942 ** unprepared to deal with extension loading, and as a means of disabling
80943 ** extension loading while evaluating user-entered SQL, the following
80944 ** API is provided to turn the [sqlite3_load_extension()] mechanism on and
80945 ** off.  {F12622} It is off by default. {END} See ticket #1863.
80946 **
80947 ** {F12621} Call the sqlite3_enable_load_extension() routine
80948 ** with onoff==1 to turn extension loading on
80949 ** and call it with onoff==0 to turn it back off again. {END}
80950 */
80951 int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
80952
80953 /*
80954 ** CAPI3REF: Make Arrangements To Automatically Load An Extension {F12640}
80955 **
80956 ** {F12641} This function
80957 ** registers an extension entry point that is automatically invoked
80958 ** whenever a new database connection is opened using
80959 ** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. {END}
80960 **
80961 ** This API can be invoked at program startup in order to register
80962 ** one or more statically linked extensions that will be available
80963 ** to all new database connections.
80964 **
80965 ** {F12642} Duplicate extensions are detected so calling this routine multiple
80966 ** times with the same extension is harmless.
80967 **
80968 ** {F12643} This routine stores a pointer to the extension in an array
80969 ** that is obtained from sqlite_malloc(). {END} If you run a memory leak
80970 ** checker on your program and it reports a leak because of this
80971 ** array, then invoke [sqlite3_reset_auto_extension()] prior
80972 ** to shutdown to free the memory.
80973 **
80974 ** {F12644} Automatic extensions apply across all threads. {END}
80975 **
80976 ** This interface is experimental and is subject to change or
80977 ** removal in future releases of SQLite.
80978 */
80979 int sqlite3_auto_extension(void *xEntryPoint);
80980
80981
80982 /*
80983 ** CAPI3REF: Reset Automatic Extension Loading {F12660}
80984 **
80985 ** {F12661} This function disables all previously registered
80986 ** automatic extensions. {END}  This
80987 ** routine undoes the effect of all prior [sqlite3_automatic_extension()]
80988 ** calls.
80989 **
80990 ** {F12662} This call disabled automatic extensions in all threads. {END}
80991 **
80992 ** This interface is experimental and is subject to change or
80993 ** removal in future releases of SQLite.
80994 */
80995 void sqlite3_reset_auto_extension(void);
80996
80997
80998 /*
80999 ****** EXPERIMENTAL - subject to change without notice **************
81000 **
81001 ** The interface to the virtual-table mechanism is currently considered
81002 ** to be experimental.  The interface might change in incompatible ways.
81003 ** If this is a problem for you, do not use the interface at this time.
81004 **
81005 ** When the virtual-table mechanism stablizes, we will declare the
81006 ** interface fixed, support it indefinitely, and remove this comment.
81007 */
81008
81009 /*
81010 ** Structures used by the virtual table interface
81011 */
81012 typedef struct sqlite3_vtab sqlite3_vtab;
81013 typedef struct sqlite3_index_info sqlite3_index_info;
81014 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
81015 typedef struct sqlite3_module sqlite3_module;
81016
81017 /*
81018 ** A module is a class of virtual tables.  Each module is defined
81019 ** by an instance of the following structure.  This structure consists
81020 ** mostly of methods for the module.
81021 */
81022 struct sqlite3_module {
81023   int iVersion;
81024   int (*xCreate)(sqlite3*, void *pAux,
81025                int argc, const char *const*argv,
81026                sqlite3_vtab **ppVTab, char**);
81027   int (*xConnect)(sqlite3*, void *pAux,
81028                int argc, const char *const*argv,
81029                sqlite3_vtab **ppVTab, char**);
81030   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
81031   int (*xDisconnect)(sqlite3_vtab *pVTab);
81032   int (*xDestroy)(sqlite3_vtab *pVTab);
81033   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
81034   int (*xClose)(sqlite3_vtab_cursor*);
81035   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
81036                 int argc, sqlite3_value **argv);
81037   int (*xNext)(sqlite3_vtab_cursor*);
81038   int (*xEof)(sqlite3_vtab_cursor*);
81039   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
81040   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
81041   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
81042   int (*xBegin)(sqlite3_vtab *pVTab);
81043   int (*xSync)(sqlite3_vtab *pVTab);
81044   int (*xCommit)(sqlite3_vtab *pVTab);
81045   int (*xRollback)(sqlite3_vtab *pVTab);
81046   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
81047                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
81048                        void **ppArg);
81049
81050   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
81051 };
81052
81053 /*
81054 ** The sqlite3_index_info structure and its substructures is used to
81055 ** pass information into and receive the reply from the xBestIndex
81056 ** method of an sqlite3_module.  The fields under **Inputs** are the
81057 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
81058 ** results into the **Outputs** fields.
81059 **
81060 ** The aConstraint[] array records WHERE clause constraints of the
81061 ** form:
81062 **
81063 **         column OP expr
81064 **
81065 ** Where OP is =, &lt;, &lt;=, &gt;, or &gt;=.  
81066 ** The particular operator is stored
81067 ** in aConstraint[].op.  The index of the column is stored in 
81068 ** aConstraint[].iColumn.  aConstraint[].usable is TRUE if the
81069 ** expr on the right-hand side can be evaluated (and thus the constraint
81070 ** is usable) and false if it cannot.
81071 **
81072 ** The optimizer automatically inverts terms of the form "expr OP column"
81073 ** and makes other simplifications to the WHERE clause in an attempt to
81074 ** get as many WHERE clause terms into the form shown above as possible.
81075 ** The aConstraint[] array only reports WHERE clause terms in the correct
81076 ** form that refer to the particular virtual table being queried.
81077 **
81078 ** Information about the ORDER BY clause is stored in aOrderBy[].
81079 ** Each term of aOrderBy records a column of the ORDER BY clause.
81080 **
81081 ** The xBestIndex method must fill aConstraintUsage[] with information
81082 ** about what parameters to pass to xFilter.  If argvIndex>0 then
81083 ** the right-hand side of the corresponding aConstraint[] is evaluated
81084 ** and becomes the argvIndex-th entry in argv.  If aConstraintUsage[].omit
81085 ** is true, then the constraint is assumed to be fully handled by the
81086 ** virtual table and is not checked again by SQLite.
81087 **
81088 ** The idxNum and idxPtr values are recorded and passed into xFilter.
81089 ** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
81090 **
81091 ** The orderByConsumed means that output from xFilter will occur in
81092 ** the correct order to satisfy the ORDER BY clause so that no separate
81093 ** sorting step is required.
81094 **
81095 ** The estimatedCost value is an estimate of the cost of doing the
81096 ** particular lookup.  A full scan of a table with N entries should have
81097 ** a cost of N.  A binary search of a table of N entries should have a
81098 ** cost of approximately log(N).
81099 */
81100 struct sqlite3_index_info {
81101   /* Inputs */
81102   int nConstraint;           /* Number of entries in aConstraint */
81103   struct sqlite3_index_constraint {
81104      int iColumn;              /* Column on left-hand side of constraint */
81105      unsigned char op;         /* Constraint operator */
81106      unsigned char usable;     /* True if this constraint is usable */
81107      int iTermOffset;          /* Used internally - xBestIndex should ignore */
81108   } *aConstraint;            /* Table of WHERE clause constraints */
81109   int nOrderBy;              /* Number of terms in the ORDER BY clause */
81110   struct sqlite3_index_orderby {
81111      int iColumn;              /* Column number */
81112      unsigned char desc;       /* True for DESC.  False for ASC. */
81113   } *aOrderBy;               /* The ORDER BY clause */
81114
81115   /* Outputs */
81116   struct sqlite3_index_constraint_usage {
81117     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
81118     unsigned char omit;      /* Do not code a test for this constraint */
81119   } *aConstraintUsage;
81120   int idxNum;                /* Number used to identify the index */
81121   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
81122   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
81123   int orderByConsumed;       /* True if output is already ordered */
81124   double estimatedCost;      /* Estimated cost of using this index */
81125 };
81126 #define SQLITE_INDEX_CONSTRAINT_EQ    2
81127 #define SQLITE_INDEX_CONSTRAINT_GT    4
81128 #define SQLITE_INDEX_CONSTRAINT_LE    8
81129 #define SQLITE_INDEX_CONSTRAINT_LT    16
81130 #define SQLITE_INDEX_CONSTRAINT_GE    32
81131 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
81132
81133 /*
81134 ** This routine is used to register a new module name with an SQLite
81135 ** connection.  Module names must be registered before creating new
81136 ** virtual tables on the module, or before using preexisting virtual
81137 ** tables of the module.
81138 */
81139 int sqlite3_create_module(
81140   sqlite3 *db,               /* SQLite connection to register module with */
81141   const char *zName,         /* Name of the module */
81142   const sqlite3_module *,    /* Methods for the module */
81143   void *                     /* Client data for xCreate/xConnect */
81144 );
81145
81146 /*
81147 ** This routine is identical to the sqlite3_create_module() method above,
81148 ** except that it allows a destructor function to be specified. It is
81149 ** even more experimental than the rest of the virtual tables API.
81150 */
81151 int sqlite3_create_module_v2(
81152   sqlite3 *db,               /* SQLite connection to register module with */
81153   const char *zName,         /* Name of the module */
81154   const sqlite3_module *,    /* Methods for the module */
81155   void *,                    /* Client data for xCreate/xConnect */
81156   void(*xDestroy)(void*)     /* Module destructor function */
81157 );
81158
81159 /*
81160 ** Every module implementation uses a subclass of the following structure
81161 ** to describe a particular instance of the module.  Each subclass will
81162 ** be tailored to the specific needs of the module implementation.   The
81163 ** purpose of this superclass is to define certain fields that are common
81164 ** to all module implementations.
81165 **
81166 ** Virtual tables methods can set an error message by assigning a
81167 ** string obtained from sqlite3_mprintf() to zErrMsg.  The method should
81168 ** take care that any prior string is freed by a call to sqlite3_free()
81169 ** prior to assigning a new string to zErrMsg.  After the error message
81170 ** is delivered up to the client application, the string will be automatically
81171 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.  Note
81172 ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
81173 ** since virtual tables are commonly implemented in loadable extensions which
81174 ** do not have access to sqlite3MPrintf() or sqlite3Free().
81175 */
81176 struct sqlite3_vtab {
81177   const sqlite3_module *pModule;  /* The module for this virtual table */
81178   int nRef;                       /* Used internally */
81179   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
81180   /* Virtual table implementations will typically add additional fields */
81181 };
81182
81183 /* Every module implementation uses a subclass of the following structure
81184 ** to describe cursors that point into the virtual table and are used
81185 ** to loop through the virtual table.  Cursors are created using the
81186 ** xOpen method of the module.  Each module implementation will define
81187 ** the content of a cursor structure to suit its own needs.
81188 **
81189 ** This superclass exists in order to define fields of the cursor that
81190 ** are common to all implementations.
81191 */
81192 struct sqlite3_vtab_cursor {
81193   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
81194   /* Virtual table implementations will typically add additional fields */
81195 };
81196
81197 /*
81198 ** The xCreate and xConnect methods of a module use the following API
81199 ** to declare the format (the names and datatypes of the columns) of
81200 ** the virtual tables they implement.
81201 */
81202 int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
81203
81204 /*
81205 ** Virtual tables can provide alternative implementations of functions
81206 ** using the xFindFunction method.  But global versions of those functions
81207 ** must exist in order to be overloaded.
81208 **
81209 ** This API makes sure a global version of a function with a particular
81210 ** name and number of parameters exists.  If no such function exists
81211 ** before this API is called, a new function is created.  The implementation
81212 ** of the new function always causes an exception to be thrown.  So
81213 ** the new function is not good for anything by itself.  Its only
81214 ** purpose is to be a place-holder function that can be overloaded
81215 ** by virtual tables.
81216 **
81217 ** This API should be considered part of the virtual table interface,
81218 ** which is experimental and subject to change.
81219 */
81220 int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
81221
81222 /*
81223 ** The interface to the virtual-table mechanism defined above (back up
81224 ** to a comment remarkably similar to this one) is currently considered
81225 ** to be experimental.  The interface might change in incompatible ways.
81226 ** If this is a problem for you, do not use the interface at this time.
81227 **
81228 ** When the virtual-table mechanism stabilizes, we will declare the
81229 ** interface fixed, support it indefinitely, and remove this comment.
81230 **
81231 ****** EXPERIMENTAL - subject to change without notice **************
81232 */
81233
81234 /*
81235 ** CAPI3REF: A Handle To An Open BLOB {F17800}
81236 **
81237 ** An instance of the following opaque structure is used to 
81238 ** represent an blob-handle.  A blob-handle is created by
81239 ** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()].
81240 ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
81241 ** can be used to read or write small subsections of the blob.
81242 ** The [sqlite3_blob_bytes()] interface returns the size of the
81243 ** blob in bytes.
81244 */
81245 typedef struct sqlite3_blob sqlite3_blob;
81246
81247 /*
81248 ** CAPI3REF: Open A BLOB For Incremental I/O {F17810}
81249 **
81250 ** {F17811} This interfaces opens a handle to the blob located
81251 ** in row iRow,, column zColumn, table zTable in database zDb;
81252 ** in other words,  the same blob that would be selected by:
81253 **
81254 ** <pre>
81255 **     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
81256 ** </pre> {END}
81257 **
81258 ** {F17812} If the flags parameter is non-zero, the blob is opened for 
81259 ** read and write access. If it is zero, the blob is opened for read 
81260 ** access. {END}
81261 **
81262 ** {F17813} On success, [SQLITE_OK] is returned and the new 
81263 ** [sqlite3_blob | blob handle] is written to *ppBlob. 
81264 ** {F17814} Otherwise an error code is returned and 
81265 ** any value written to *ppBlob should not be used by the caller.
81266 ** {F17815} This function sets the database-handle error code and message
81267 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()].
81268 ** <todo>We should go through and mark all interfaces that behave this
81269 ** way with a similar statement</todo>
81270 */
81271 int sqlite3_blob_open(
81272   sqlite3*,
81273   const char *zDb,
81274   const char *zTable,
81275   const char *zColumn,
81276   sqlite3_int64 iRow,
81277   int flags,
81278   sqlite3_blob **ppBlob
81279 );
81280
81281 /*
81282 ** CAPI3REF:  Close A BLOB Handle {F17830}
81283 **
81284 ** Close an open [sqlite3_blob | blob handle].
81285 **
81286 ** {F17831} Closing a BLOB shall cause the current transaction to commit
81287 ** if there are no other BLOBs, no pending prepared statements, and the
81288 ** database connection is in autocommit mode.
81289 ** {F17832} If any writes were made to the BLOB, they might be held in cache
81290 ** until the close operation if they will fit. {END}
81291 ** Closing the BLOB often forces the changes
81292 ** out to disk and so if any I/O errors occur, they will likely occur
81293 ** at the time when the BLOB is closed.  {F17833} Any errors that occur during
81294 ** closing are reported as a non-zero return value.
81295 **
81296 ** {F17839} The BLOB is closed unconditionally.  Even if this routine returns
81297 ** an error code, the BLOB is still closed.
81298 */
81299 int sqlite3_blob_close(sqlite3_blob *);
81300
81301 /*
81302 ** CAPI3REF:  Return The Size Of An Open BLOB {F17805}
81303 **
81304 ** {F16806} Return the size in bytes of the blob accessible via the open 
81305 ** [sqlite3_blob | blob-handle] passed as an argument.
81306 */
81307 int sqlite3_blob_bytes(sqlite3_blob *);
81308
81309 /*
81310 ** CAPI3REF:  Read Data From A BLOB Incrementally {F17850}
81311 **
81312 ** This function is used to read data from an open 
81313 ** [sqlite3_blob | blob-handle] into a caller supplied buffer.
81314 ** {F17851} n bytes of data are copied into buffer
81315 ** z from the open blob, starting at offset iOffset.
81316 **
81317 ** {F17852} If offset iOffset is less than n bytes from the end of the blob, 
81318 ** [SQLITE_ERROR] is returned and no data is read.  {F17853} If n is
81319 ** less than zero [SQLITE_ERROR] is returned and no data is read.
81320 **
81321 ** {F17854} On success, SQLITE_OK is returned. Otherwise, an 
81322 ** [SQLITE_ERROR | SQLite error code] or an
81323 ** [SQLITE_IOERR_READ | extended error code] is returned.
81324 */
81325 int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset);
81326
81327 /*
81328 ** CAPI3REF:  Write Data Into A BLOB Incrementally {F17870}
81329 **
81330 ** This function is used to write data into an open 
81331 ** [sqlite3_blob | blob-handle] from a user supplied buffer.
81332 ** {F17871} n bytes of data are copied from the buffer
81333 ** pointed to by z into the open blob, starting at offset iOffset.
81334 **
81335 ** {F17872} If the [sqlite3_blob | blob-handle] passed as the first argument
81336 ** was not opened for writing (the flags parameter to [sqlite3_blob_open()]
81337 *** was zero), this function returns [SQLITE_READONLY].
81338 **
81339 ** {F17873} This function may only modify the contents of the blob; it is
81340 ** not possible to increase the size of a blob using this API.
81341 ** {F17874} If offset iOffset is less than n bytes from the end of the blob, 
81342 ** [SQLITE_ERROR] is returned and no data is written.  {F17875} If n is
81343 ** less than zero [SQLITE_ERROR] is returned and no data is written.
81344 **
81345 ** {F17876} On success, SQLITE_OK is returned. Otherwise, an 
81346 ** [SQLITE_ERROR | SQLite error code] or an
81347 ** [SQLITE_IOERR_READ | extended error code] is returned.
81348 */
81349 int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
81350
81351 /*
81352 ** CAPI3REF:  Virtual File System Objects {F11200}
81353 **
81354 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
81355 ** that SQLite uses to interact
81356 ** with the underlying operating system.  Most builds come with a
81357 ** single default VFS that is appropriate for the host computer.
81358 ** New VFSes can be registered and existing VFSes can be unregistered.
81359 ** The following interfaces are provided.
81360 **
81361 ** {F11201} The sqlite3_vfs_find() interface returns a pointer to 
81362 ** a VFS given its name.  {F11202} Names are case sensitive.
81363 ** {F11203} Names are zero-terminated UTF-8 strings.
81364 ** {F11204} If there is no match, a NULL
81365 ** pointer is returned. {F11205} If zVfsName is NULL then the default 
81366 ** VFS is returned. {END}
81367 **
81368 ** {F11210} New VFSes are registered with sqlite3_vfs_register().
81369 ** {F11211} Each new VFS becomes the default VFS if the makeDflt flag is set.
81370 ** {F11212} The same VFS can be registered multiple times without injury.
81371 ** {F11213} To make an existing VFS into the default VFS, register it again
81372 ** with the makeDflt flag set. {U11214} If two different VFSes with the
81373 ** same name are registered, the behavior is undefined.  {U11215} If a
81374 ** VFS is registered with a name that is NULL or an empty string,
81375 ** then the behavior is undefined.
81376 ** 
81377 ** {F11220} Unregister a VFS with the sqlite3_vfs_unregister() interface.
81378 ** {F11221} If the default VFS is unregistered, another VFS is chosen as
81379 ** the default.  The choice for the new VFS is arbitrary.
81380 */
81381 sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
81382 int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
81383 int sqlite3_vfs_unregister(sqlite3_vfs*);
81384
81385 /*
81386 ** CAPI3REF: Mutexes {F17000}
81387 **
81388 ** The SQLite core uses these routines for thread
81389 ** synchronization.  Though they are intended for internal
81390 ** use by SQLite, code that links against SQLite is
81391 ** permitted to use any of these routines.
81392 **
81393 ** The SQLite source code contains multiple implementations 
81394 ** of these mutex routines.  An appropriate implementation
81395 ** is selected automatically at compile-time.  The following
81396 ** implementations are available in the SQLite core:
81397 **
81398 ** <ul>
81399 ** <li>   SQLITE_MUTEX_OS2
81400 ** <li>   SQLITE_MUTEX_PTHREAD
81401 ** <li>   SQLITE_MUTEX_W32
81402 ** <li>   SQLITE_MUTEX_NOOP
81403 ** </ul>
81404 **
81405 ** The SQLITE_MUTEX_NOOP implementation is a set of routines 
81406 ** that does no real locking and is appropriate for use in 
81407 ** a single-threaded application.  The SQLITE_MUTEX_OS2,
81408 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
81409 ** are appropriate for use on os/2, unix, and windows.
81410 ** 
81411 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
81412 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
81413 ** implementation is included with the library.  The
81414 ** mutex interface routines defined here become external
81415 ** references in the SQLite library for which implementations
81416 ** must be provided by the application.  This facility allows an
81417 ** application that links against SQLite to provide its own mutex
81418 ** implementation without having to modify the SQLite core.
81419 **
81420 ** {F17011} The sqlite3_mutex_alloc() routine allocates a new
81421 ** mutex and returns a pointer to it. {F17012} If it returns NULL
81422 ** that means that a mutex could not be allocated. {F17013} SQLite
81423 ** will unwind its stack and return an error. {F17014} The argument
81424 ** to sqlite3_mutex_alloc() is one of these integer constants:
81425 **
81426 ** <ul>
81427 ** <li>  SQLITE_MUTEX_FAST
81428 ** <li>  SQLITE_MUTEX_RECURSIVE
81429 ** <li>  SQLITE_MUTEX_STATIC_MASTER
81430 ** <li>  SQLITE_MUTEX_STATIC_MEM
81431 ** <li>  SQLITE_MUTEX_STATIC_MEM2
81432 ** <li>  SQLITE_MUTEX_STATIC_PRNG
81433 ** <li>  SQLITE_MUTEX_STATIC_LRU
81434 ** </ul> {END}
81435 **
81436 ** {F17015} The first two constants cause sqlite3_mutex_alloc() to create
81437 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
81438 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END}
81439 ** The mutex implementation does not need to make a distinction
81440 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
81441 ** not want to.  {F17016} But SQLite will only request a recursive mutex in
81442 ** cases where it really needs one.  {END} If a faster non-recursive mutex
81443 ** implementation is available on the host platform, the mutex subsystem
81444 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
81445 **
81446 ** {F17017} The other allowed parameters to sqlite3_mutex_alloc() each return
81447 ** a pointer to a static preexisting mutex. {END}  Four static mutexes are
81448 ** used by the current version of SQLite.  Future versions of SQLite
81449 ** may add additional static mutexes.  Static mutexes are for internal
81450 ** use by SQLite only.  Applications that use SQLite mutexes should
81451 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
81452 ** SQLITE_MUTEX_RECURSIVE.
81453 **
81454 ** {F17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
81455 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
81456 ** returns a different mutex on every call.  {F17034} But for the static 
81457 ** mutex types, the same mutex is returned on every call that has
81458 ** the same type number. {END}
81459 **
81460 ** {F17019} The sqlite3_mutex_free() routine deallocates a previously
81461 ** allocated dynamic mutex. {F17020} SQLite is careful to deallocate every
81462 ** dynamic mutex that it allocates. {U17021} The dynamic mutexes must not be in 
81463 ** use when they are deallocated. {U17022} Attempting to deallocate a static
81464 ** mutex results in undefined behavior. {F17023} SQLite never deallocates
81465 ** a static mutex. {END}
81466 **
81467 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
81468 ** to enter a mutex. {F17024} If another thread is already within the mutex,
81469 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
81470 ** SQLITE_BUSY. {F17025}  The sqlite3_mutex_try() interface returns SQLITE_OK
81471 ** upon successful entry.  {F17026} Mutexes created using
81472 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
81473 ** {F17027} In such cases the,
81474 ** mutex must be exited an equal number of times before another thread
81475 ** can enter.  {U17028} If the same thread tries to enter any other
81476 ** kind of mutex more than once, the behavior is undefined.
81477 ** {F17029} SQLite will never exhibit
81478 ** such behavior in its own use of mutexes. {END}
81479 **
81480 ** Some systems (ex: windows95) do not the operation implemented by
81481 ** sqlite3_mutex_try().  On those systems, sqlite3_mutex_try() will
81482 ** always return SQLITE_BUSY.  {F17030} The SQLite core only ever uses
81483 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior. {END}
81484 **
81485 ** {F17031} The sqlite3_mutex_leave() routine exits a mutex that was
81486 ** previously entered by the same thread.  {U17032} The behavior
81487 ** is undefined if the mutex is not currently entered by the
81488 ** calling thread or is not currently allocated.  {F17033} SQLite will
81489 ** never do either. {END}
81490 **
81491 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
81492 */
81493 sqlite3_mutex *sqlite3_mutex_alloc(int);
81494 void sqlite3_mutex_free(sqlite3_mutex*);
81495 void sqlite3_mutex_enter(sqlite3_mutex*);
81496 int sqlite3_mutex_try(sqlite3_mutex*);
81497 void sqlite3_mutex_leave(sqlite3_mutex*);
81498
81499 /*
81500 ** CAPI3REF: Mutex Verifcation Routines {F17080}
81501 **
81502 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
81503 ** are intended for use inside assert() statements. {F17081} The SQLite core
81504 ** never uses these routines except inside an assert() and applications
81505 ** are advised to follow the lead of the core.  {F17082} The core only
81506 ** provides implementations for these routines when it is compiled
81507 ** with the SQLITE_DEBUG flag.  {U17087} External mutex implementations
81508 ** are only required to provide these routines if SQLITE_DEBUG is
81509 ** defined and if NDEBUG is not defined.
81510 **
81511 ** {F17083} These routines should return true if the mutex in their argument
81512 ** is held or not held, respectively, by the calling thread. {END}
81513 **
81514 ** {X17084} The implementation is not required to provided versions of these
81515 ** routines that actually work.
81516 ** If the implementation does not provide working
81517 ** versions of these routines, it should at least provide stubs
81518 ** that always return true so that one does not get spurious
81519 ** assertion failures. {END}
81520 **
81521 ** {F17085} If the argument to sqlite3_mutex_held() is a NULL pointer then
81522 ** the routine should return 1.  {END} This seems counter-intuitive since
81523 ** clearly the mutex cannot be held if it does not exist.  But the
81524 ** the reason the mutex does not exist is because the build is not
81525 ** using mutexes.  And we do not want the assert() containing the
81526 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
81527 ** the appropriate thing to do.  {F17086} The sqlite3_mutex_notheld() 
81528 ** interface should also return 1 when given a NULL pointer.
81529 */
81530 int sqlite3_mutex_held(sqlite3_mutex*);
81531 int sqlite3_mutex_notheld(sqlite3_mutex*);
81532
81533 /*
81534 ** CAPI3REF: Mutex Types {F17001}
81535 **
81536 ** {F17002} The [sqlite3_mutex_alloc()] interface takes a single argument
81537 ** which is one of these integer constants. {END}
81538 */
81539 #define SQLITE_MUTEX_FAST             0
81540 #define SQLITE_MUTEX_RECURSIVE        1
81541 #define SQLITE_MUTEX_STATIC_MASTER    2
81542 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
81543 #define SQLITE_MUTEX_STATIC_MEM2      4  /* sqlite3_release_memory() */
81544 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
81545 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
81546
81547 /*
81548 ** CAPI3REF: Low-Level Control Of Database Files {F11300}
81549 **
81550 ** {F11301} The [sqlite3_file_control()] interface makes a direct call to the
81551 ** xFileControl method for the [sqlite3_io_methods] object associated
81552 ** with a particular database identified by the second argument. {F11302} The
81553 ** name of the database is the name assigned to the database by the
81554 ** <a href="lang_attach.html">ATTACH</a> SQL command that opened the
81555 ** database. {F11303} To control the main database file, use the name "main"
81556 ** or a NULL pointer. {F11304} The third and fourth parameters to this routine
81557 ** are passed directly through to the second and third parameters of
81558 ** the xFileControl method.  {F11305} The return value of the xFileControl
81559 ** method becomes the return value of this routine.
81560 **
81561 ** {F11306} If the second parameter (zDbName) does not match the name of any
81562 ** open database file, then SQLITE_ERROR is returned. {F11307} This error
81563 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
81564 ** or [sqlite3_errmsg()]. {U11308} The underlying xFileControl method might
81565 ** also return SQLITE_ERROR.  {U11309} There is no way to distinguish between
81566 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
81567 ** xFileControl method. {END}
81568 **
81569 ** See also: [SQLITE_FCNTL_LOCKSTATE]
81570 */
81571 int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
81572
81573 /*
81574 ** Undo the hack that converts floating point types to integer for
81575 ** builds on processors without floating point support.
81576 */
81577 #ifdef SQLITE_OMIT_FLOATING_POINT
81578 # undef double
81579 #endif
81580
81581 #if 0
81582 }  /* End of the 'extern "C"' block */
81583 #endif
81584 #endif
81585
81586 /************** End of sqlite3.h *********************************************/
81587 /************** Continuing where we left off in fts3_tokenizer.h *************/
81588
81589 /*
81590 ** Structures used by the tokenizer interface. When a new tokenizer
81591 ** implementation is registered, the caller provides a pointer to
81592 ** an sqlite3_tokenizer_module containing pointers to the callback
81593 ** functions that make up an implementation.
81594 **
81595 ** When an fts3 table is created, it passes any arguments passed to
81596 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
81597 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
81598 ** implementation. The xCreate() function in turn returns an 
81599 ** sqlite3_tokenizer structure representing the specific tokenizer to
81600 ** be used for the fts3 table (customized by the tokenizer clause arguments).
81601 **
81602 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
81603 ** method is called. It returns an sqlite3_tokenizer_cursor object
81604 ** that may be used to tokenize a specific input buffer based on
81605 ** the tokenization rules supplied by a specific sqlite3_tokenizer
81606 ** object.
81607 */
81608 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
81609 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
81610 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
81611
81612 struct sqlite3_tokenizer_module {
81613
81614   /*
81615   ** Structure version. Should always be set to 0.
81616   */
81617   int iVersion;
81618
81619   /*
81620   ** Create a new tokenizer. The values in the argv[] array are the
81621   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
81622   ** TABLE statement that created the fts3 table. For example, if
81623   ** the following SQL is executed:
81624   **
81625   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
81626   **
81627   ** then argc is set to 2, and the argv[] array contains pointers
81628   ** to the strings "arg1" and "arg2".
81629   **
81630   ** This method should return either SQLITE_OK (0), or an SQLite error 
81631   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
81632   ** to point at the newly created tokenizer structure. The generic
81633   ** sqlite3_tokenizer.pModule variable should not be initialised by
81634   ** this callback. The caller will do so.
81635   */
81636   int (*xCreate)(
81637     int argc,                           /* Size of argv array */
81638     const char *const*argv,             /* Tokenizer argument strings */
81639     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
81640   );
81641
81642   /*
81643   ** Destroy an existing tokenizer. The fts3 module calls this method
81644   ** exactly once for each successful call to xCreate().
81645   */
81646   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
81647
81648   /*
81649   ** Create a tokenizer cursor to tokenize an input buffer. The caller
81650   ** is responsible for ensuring that the input buffer remains valid
81651   ** until the cursor is closed (using the xClose() method). 
81652   */
81653   int (*xOpen)(
81654     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
81655     const char *pInput, int nBytes,      /* Input buffer */
81656     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
81657   );
81658
81659   /*
81660   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
81661   ** method exactly once for each successful call to xOpen().
81662   */
81663   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
81664
81665   /*
81666   ** Retrieve the next token from the tokenizer cursor pCursor. This
81667   ** method should either return SQLITE_OK and set the values of the
81668   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
81669   ** the end of the buffer has been reached, or an SQLite error code.
81670   **
81671   ** *ppToken should be set to point at a buffer containing the 
81672   ** normalized version of the token (i.e. after any case-folding and/or
81673   ** stemming has been performed). *pnBytes should be set to the length
81674   ** of this buffer in bytes. The input text that generated the token is
81675   ** identified by the byte offsets returned in *piStartOffset and
81676   ** *piEndOffset.
81677   **
81678   ** The buffer *ppToken is set to point at is managed by the tokenizer
81679   ** implementation. It is only required to be valid until the next call
81680   ** to xNext() or xClose(). 
81681   */
81682   /* TODO(shess) current implementation requires pInput to be
81683   ** nul-terminated.  This should either be fixed, or pInput/nBytes
81684   ** should be converted to zInput.
81685   */
81686   int (*xNext)(
81687     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
81688     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
81689     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
81690     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
81691     int *piPosition      /* OUT: Number of tokens returned before this one */
81692   );
81693 };
81694
81695 struct sqlite3_tokenizer {
81696   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
81697   /* Tokenizer implementations will typically add additional fields */
81698 };
81699
81700 struct sqlite3_tokenizer_cursor {
81701   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
81702   /* Tokenizer implementations will typically add additional fields */
81703 };
81704
81705 #endif /* _FTS3_TOKENIZER_H_ */
81706
81707 /************** End of fts3_tokenizer.h **************************************/
81708 /************** Continuing where we left off in fts3.c ***********************/
81709 #ifndef SQLITE_CORE 
81710   #include "sqlite3ext.h"
81711   SQLITE_EXTENSION_INIT1
81712 #endif
81713
81714
81715 /* TODO(shess) MAN, this thing needs some refactoring.  At minimum, it
81716 ** would be nice to order the file better, perhaps something along the
81717 ** lines of:
81718 **
81719 **  - utility functions
81720 **  - table setup functions
81721 **  - table update functions
81722 **  - table query functions
81723 **
81724 ** Put the query functions last because they're likely to reference
81725 ** typedefs or functions from the table update section.
81726 */
81727
81728 #if 0
81729 # define FTSTRACE(A)  printf A; fflush(stdout)
81730 #else
81731 # define FTSTRACE(A)
81732 #endif
81733
81734 /*
81735 ** Default span for NEAR operators.
81736 */
81737 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
81738
81739 /* It is not safe to call isspace(), tolower(), or isalnum() on
81740 ** hi-bit-set characters.  This is the same solution used in the
81741 ** tokenizer.
81742 */
81743 /* TODO(shess) The snippet-generation code should be using the
81744 ** tokenizer-generated tokens rather than doing its own local
81745 ** tokenization.
81746 */
81747 /* TODO(shess) Is __isascii() a portable version of (c&0x80)==0? */
81748 static int safe_isspace(char c){
81749   return (c&0x80)==0 ? isspace(c) : 0;
81750 }
81751 static int safe_tolower(char c){
81752   return (c&0x80)==0 ? tolower(c) : c;
81753 }
81754 static int safe_isalnum(char c){
81755   return (c&0x80)==0 ? isalnum(c) : 0;
81756 }
81757
81758 typedef enum DocListType {
81759   DL_DOCIDS,              /* docids only */
81760   DL_POSITIONS,           /* docids + positions */
81761   DL_POSITIONS_OFFSETS    /* docids + positions + offsets */
81762 } DocListType;
81763
81764 /*
81765 ** By default, only positions and not offsets are stored in the doclists.
81766 ** To change this so that offsets are stored too, compile with
81767 **
81768 **          -DDL_DEFAULT=DL_POSITIONS_OFFSETS
81769 **
81770 ** If DL_DEFAULT is set to DL_DOCIDS, your table can only be inserted
81771 ** into (no deletes or updates).
81772 */
81773 #ifndef DL_DEFAULT
81774 # define DL_DEFAULT DL_POSITIONS
81775 #endif
81776
81777 enum {
81778   POS_END = 0,        /* end of this position list */
81779   POS_COLUMN,         /* followed by new column number */
81780   POS_BASE
81781 };
81782
81783 /* MERGE_COUNT controls how often we merge segments (see comment at
81784 ** top of file).
81785 */
81786 #define MERGE_COUNT 16
81787
81788 /* utility functions */
81789
81790 /* CLEAR() and SCRAMBLE() abstract memset() on a pointer to a single
81791 ** record to prevent errors of the form:
81792 **
81793 ** my_function(SomeType *b){
81794 **   memset(b, '\0', sizeof(b));  // sizeof(b)!=sizeof(*b)
81795 ** }
81796 */
81797 /* TODO(shess) Obvious candidates for a header file. */
81798 #define CLEAR(b) memset(b, '\0', sizeof(*(b)))
81799
81800 #ifndef NDEBUG
81801 #  define SCRAMBLE(b) memset(b, 0x55, sizeof(*(b)))
81802 #else
81803 #  define SCRAMBLE(b)
81804 #endif
81805
81806 /* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */
81807 #define VARINT_MAX 10
81808
81809 /* Write a 64-bit variable-length integer to memory starting at p[0].
81810  * The length of data written will be between 1 and VARINT_MAX bytes.
81811  * The number of bytes written is returned. */
81812 static int fts3PutVarint(char *p, sqlite_int64 v){
81813   unsigned char *q = (unsigned char *) p;
81814   sqlite_uint64 vu = v;
81815   do{
81816     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
81817     vu >>= 7;
81818   }while( vu!=0 );
81819   q[-1] &= 0x7f;  /* turn off high bit in final byte */
81820   assert( q - (unsigned char *)p <= VARINT_MAX );
81821   return (int) (q - (unsigned char *)p);
81822 }
81823
81824 /* Read a 64-bit variable-length integer from memory starting at p[0].
81825  * Return the number of bytes read, or 0 on error.
81826  * The value is stored in *v. */
81827 static int fts3GetVarint(const char *p, sqlite_int64 *v){
81828   const unsigned char *q = (const unsigned char *) p;
81829   sqlite_uint64 x = 0, y = 1;
81830   while( (*q & 0x80) == 0x80 ){
81831     x += y * (*q++ & 0x7f);
81832     y <<= 7;
81833     if( q - (unsigned char *)p >= VARINT_MAX ){  /* bad data */
81834       assert( 0 );
81835       return 0;
81836     }
81837   }
81838   x += y * (*q++);
81839   *v = (sqlite_int64) x;
81840   return (int) (q - (unsigned char *)p);
81841 }
81842
81843 static int fts3GetVarint32(const char *p, int *pi){
81844  sqlite_int64 i;
81845  int ret = fts3GetVarint(p, &i);
81846  *pi = (int) i;
81847  assert( *pi==i );
81848  return ret;
81849 }
81850
81851 /*******************************************************************/
81852 /* DataBuffer is used to collect data into a buffer in piecemeal
81853 ** fashion.  It implements the usual distinction between amount of
81854 ** data currently stored (nData) and buffer capacity (nCapacity).
81855 **
81856 ** dataBufferInit - create a buffer with given initial capacity.
81857 ** dataBufferReset - forget buffer's data, retaining capacity.
81858 ** dataBufferDestroy - free buffer's data.
81859 ** dataBufferSwap - swap contents of two buffers.
81860 ** dataBufferExpand - expand capacity without adding data.
81861 ** dataBufferAppend - append data.
81862 ** dataBufferAppend2 - append two pieces of data at once.
81863 ** dataBufferReplace - replace buffer's data.
81864 */
81865 typedef struct DataBuffer {
81866   char *pData;          /* Pointer to malloc'ed buffer. */
81867   int nCapacity;        /* Size of pData buffer. */
81868   int nData;            /* End of data loaded into pData. */
81869 } DataBuffer;
81870
81871 static void dataBufferInit(DataBuffer *pBuffer, int nCapacity){
81872   assert( nCapacity>=0 );
81873   pBuffer->nData = 0;
81874   pBuffer->nCapacity = nCapacity;
81875   pBuffer->pData = nCapacity==0 ? NULL : sqlite3_malloc(nCapacity);
81876 }
81877 static void dataBufferReset(DataBuffer *pBuffer){
81878   pBuffer->nData = 0;
81879 }
81880 static void dataBufferDestroy(DataBuffer *pBuffer){
81881   if( pBuffer->pData!=NULL ) sqlite3_free(pBuffer->pData);
81882   SCRAMBLE(pBuffer);
81883 }
81884 static void dataBufferSwap(DataBuffer *pBuffer1, DataBuffer *pBuffer2){
81885   DataBuffer tmp = *pBuffer1;
81886   *pBuffer1 = *pBuffer2;
81887   *pBuffer2 = tmp;
81888 }
81889 static void dataBufferExpand(DataBuffer *pBuffer, int nAddCapacity){
81890   assert( nAddCapacity>0 );
81891   /* TODO(shess) Consider expanding more aggressively.  Note that the
81892   ** underlying malloc implementation may take care of such things for
81893   ** us already.
81894   */
81895   if( pBuffer->nData+nAddCapacity>pBuffer->nCapacity ){
81896     pBuffer->nCapacity = pBuffer->nData+nAddCapacity;
81897     pBuffer->pData = sqlite3_realloc(pBuffer->pData, pBuffer->nCapacity);
81898   }
81899 }
81900 static void dataBufferAppend(DataBuffer *pBuffer,
81901                              const char *pSource, int nSource){
81902   assert( nSource>0 && pSource!=NULL );
81903   dataBufferExpand(pBuffer, nSource);
81904   memcpy(pBuffer->pData+pBuffer->nData, pSource, nSource);
81905   pBuffer->nData += nSource;
81906 }
81907 static void dataBufferAppend2(DataBuffer *pBuffer,
81908                               const char *pSource1, int nSource1,
81909                               const char *pSource2, int nSource2){
81910   assert( nSource1>0 && pSource1!=NULL );
81911   assert( nSource2>0 && pSource2!=NULL );
81912   dataBufferExpand(pBuffer, nSource1+nSource2);
81913   memcpy(pBuffer->pData+pBuffer->nData, pSource1, nSource1);
81914   memcpy(pBuffer->pData+pBuffer->nData+nSource1, pSource2, nSource2);
81915   pBuffer->nData += nSource1+nSource2;
81916 }
81917 static void dataBufferReplace(DataBuffer *pBuffer,
81918                               const char *pSource, int nSource){
81919   dataBufferReset(pBuffer);
81920   dataBufferAppend(pBuffer, pSource, nSource);
81921 }
81922
81923 /* StringBuffer is a null-terminated version of DataBuffer. */
81924 typedef struct StringBuffer {
81925   DataBuffer b;            /* Includes null terminator. */
81926 } StringBuffer;
81927
81928 static void initStringBuffer(StringBuffer *sb){
81929   dataBufferInit(&sb->b, 100);
81930   dataBufferReplace(&sb->b, "", 1);
81931 }
81932 static int stringBufferLength(StringBuffer *sb){
81933   return sb->b.nData-1;
81934 }
81935 static char *stringBufferData(StringBuffer *sb){
81936   return sb->b.pData;
81937 }
81938 static void stringBufferDestroy(StringBuffer *sb){
81939   dataBufferDestroy(&sb->b);
81940 }
81941
81942 static void nappend(StringBuffer *sb, const char *zFrom, int nFrom){
81943   assert( sb->b.nData>0 );
81944   if( nFrom>0 ){
81945     sb->b.nData--;
81946     dataBufferAppend2(&sb->b, zFrom, nFrom, "", 1);
81947   }
81948 }
81949 static void append(StringBuffer *sb, const char *zFrom){
81950   nappend(sb, zFrom, strlen(zFrom));
81951 }
81952
81953 /* Append a list of strings separated by commas. */
81954 static void appendList(StringBuffer *sb, int nString, char **azString){
81955   int i;
81956   for(i=0; i<nString; ++i){
81957     if( i>0 ) append(sb, ", ");
81958     append(sb, azString[i]);
81959   }
81960 }
81961
81962 static int endsInWhiteSpace(StringBuffer *p){
81963   return stringBufferLength(p)>0 &&
81964     safe_isspace(stringBufferData(p)[stringBufferLength(p)-1]);
81965 }
81966
81967 /* If the StringBuffer ends in something other than white space, add a
81968 ** single space character to the end.
81969 */
81970 static void appendWhiteSpace(StringBuffer *p){
81971   if( stringBufferLength(p)==0 ) return;
81972   if( !endsInWhiteSpace(p) ) append(p, " ");
81973 }
81974
81975 /* Remove white space from the end of the StringBuffer */
81976 static void trimWhiteSpace(StringBuffer *p){
81977   while( endsInWhiteSpace(p) ){
81978     p->b.pData[--p->b.nData-1] = '\0';
81979   }
81980 }
81981
81982 /*******************************************************************/
81983 /* DLReader is used to read document elements from a doclist.  The
81984 ** current docid is cached, so dlrDocid() is fast.  DLReader does not
81985 ** own the doclist buffer.
81986 **
81987 ** dlrAtEnd - true if there's no more data to read.
81988 ** dlrDocid - docid of current document.
81989 ** dlrDocData - doclist data for current document (including docid).
81990 ** dlrDocDataBytes - length of same.
81991 ** dlrAllDataBytes - length of all remaining data.
81992 ** dlrPosData - position data for current document.
81993 ** dlrPosDataLen - length of pos data for current document (incl POS_END).
81994 ** dlrStep - step to current document.
81995 ** dlrInit - initial for doclist of given type against given data.
81996 ** dlrDestroy - clean up.
81997 **
81998 ** Expected usage is something like:
81999 **
82000 **   DLReader reader;
82001 **   dlrInit(&reader, pData, nData);
82002 **   while( !dlrAtEnd(&reader) ){
82003 **     // calls to dlrDocid() and kin.
82004 **     dlrStep(&reader);
82005 **   }
82006 **   dlrDestroy(&reader);
82007 */
82008 typedef struct DLReader {
82009   DocListType iType;
82010   const char *pData;
82011   int nData;
82012
82013   sqlite_int64 iDocid;
82014   int nElement;
82015 } DLReader;
82016
82017 static int dlrAtEnd(DLReader *pReader){
82018   assert( pReader->nData>=0 );
82019   return pReader->nData==0;
82020 }
82021 static sqlite_int64 dlrDocid(DLReader *pReader){
82022   assert( !dlrAtEnd(pReader) );
82023   return pReader->iDocid;
82024 }
82025 static const char *dlrDocData(DLReader *pReader){
82026   assert( !dlrAtEnd(pReader) );
82027   return pReader->pData;
82028 }
82029 static int dlrDocDataBytes(DLReader *pReader){
82030   assert( !dlrAtEnd(pReader) );
82031   return pReader->nElement;
82032 }
82033 static int dlrAllDataBytes(DLReader *pReader){
82034   assert( !dlrAtEnd(pReader) );
82035   return pReader->nData;
82036 }
82037 /* TODO(shess) Consider adding a field to track iDocid varint length
82038 ** to make these two functions faster.  This might matter (a tiny bit)
82039 ** for queries.
82040 */
82041 static const char *dlrPosData(DLReader *pReader){
82042   sqlite_int64 iDummy;
82043   int n = fts3GetVarint(pReader->pData, &iDummy);
82044   assert( !dlrAtEnd(pReader) );
82045   return pReader->pData+n;
82046 }
82047 static int dlrPosDataLen(DLReader *pReader){
82048   sqlite_int64 iDummy;
82049   int n = fts3GetVarint(pReader->pData, &iDummy);
82050   assert( !dlrAtEnd(pReader) );
82051   return pReader->nElement-n;
82052 }
82053 static void dlrStep(DLReader *pReader){
82054   assert( !dlrAtEnd(pReader) );
82055
82056   /* Skip past current doclist element. */
82057   assert( pReader->nElement<=pReader->nData );
82058   pReader->pData += pReader->nElement;
82059   pReader->nData -= pReader->nElement;
82060
82061   /* If there is more data, read the next doclist element. */
82062   if( pReader->nData!=0 ){
82063     sqlite_int64 iDocidDelta;
82064     int iDummy, n = fts3GetVarint(pReader->pData, &iDocidDelta);
82065     pReader->iDocid += iDocidDelta;
82066     if( pReader->iType>=DL_POSITIONS ){
82067       assert( n<pReader->nData );
82068       while( 1 ){
82069         n += fts3GetVarint32(pReader->pData+n, &iDummy);
82070         assert( n<=pReader->nData );
82071         if( iDummy==POS_END ) break;
82072         if( iDummy==POS_COLUMN ){
82073           n += fts3GetVarint32(pReader->pData+n, &iDummy);
82074           assert( n<pReader->nData );
82075         }else if( pReader->iType==DL_POSITIONS_OFFSETS ){
82076           n += fts3GetVarint32(pReader->pData+n, &iDummy);
82077           n += fts3GetVarint32(pReader->pData+n, &iDummy);
82078           assert( n<pReader->nData );
82079         }
82080       }
82081     }
82082     pReader->nElement = n;
82083     assert( pReader->nElement<=pReader->nData );
82084   }
82085 }
82086 static void dlrInit(DLReader *pReader, DocListType iType,
82087                     const char *pData, int nData){
82088   assert( pData!=NULL && nData!=0 );
82089   pReader->iType = iType;
82090   pReader->pData = pData;
82091   pReader->nData = nData;
82092   pReader->nElement = 0;
82093   pReader->iDocid = 0;
82094
82095   /* Load the first element's data.  There must be a first element. */
82096   dlrStep(pReader);
82097 }
82098 static void dlrDestroy(DLReader *pReader){
82099   SCRAMBLE(pReader);
82100 }
82101
82102 #ifndef NDEBUG
82103 /* Verify that the doclist can be validly decoded.  Also returns the
82104 ** last docid found because it is convenient in other assertions for
82105 ** DLWriter.
82106 */
82107 static void docListValidate(DocListType iType, const char *pData, int nData,
82108                             sqlite_int64 *pLastDocid){
82109   sqlite_int64 iPrevDocid = 0;
82110   assert( nData>0 );
82111   assert( pData!=0 );
82112   assert( pData+nData>pData );
82113   while( nData!=0 ){
82114     sqlite_int64 iDocidDelta;
82115     int n = fts3GetVarint(pData, &iDocidDelta);
82116     iPrevDocid += iDocidDelta;
82117     if( iType>DL_DOCIDS ){
82118       int iDummy;
82119       while( 1 ){
82120         n += fts3GetVarint32(pData+n, &iDummy);
82121         if( iDummy==POS_END ) break;
82122         if( iDummy==POS_COLUMN ){
82123           n += fts3GetVarint32(pData+n, &iDummy);
82124         }else if( iType>DL_POSITIONS ){
82125           n += fts3GetVarint32(pData+n, &iDummy);
82126           n += fts3GetVarint32(pData+n, &iDummy);
82127         }
82128         assert( n<=nData );
82129       }
82130     }
82131     assert( n<=nData );
82132     pData += n;
82133     nData -= n;
82134   }
82135   if( pLastDocid ) *pLastDocid = iPrevDocid;
82136 }
82137 #define ASSERT_VALID_DOCLIST(i, p, n, o) docListValidate(i, p, n, o)
82138 #else
82139 #define ASSERT_VALID_DOCLIST(i, p, n, o) assert( 1 )
82140 #endif
82141
82142 /*******************************************************************/
82143 /* DLWriter is used to write doclist data to a DataBuffer.  DLWriter
82144 ** always appends to the buffer and does not own it.
82145 **
82146 ** dlwInit - initialize to write a given type doclistto a buffer.
82147 ** dlwDestroy - clear the writer's memory.  Does not free buffer.
82148 ** dlwAppend - append raw doclist data to buffer.
82149 ** dlwCopy - copy next doclist from reader to writer.
82150 ** dlwAdd - construct doclist element and append to buffer.
82151 **    Only apply dlwAdd() to DL_DOCIDS doclists (else use PLWriter).
82152 */
82153 typedef struct DLWriter {
82154   DocListType iType;
82155   DataBuffer *b;
82156   sqlite_int64 iPrevDocid;
82157 #ifndef NDEBUG
82158   int has_iPrevDocid;
82159 #endif
82160 } DLWriter;
82161
82162 static void dlwInit(DLWriter *pWriter, DocListType iType, DataBuffer *b){
82163   pWriter->b = b;
82164   pWriter->iType = iType;
82165   pWriter->iPrevDocid = 0;
82166 #ifndef NDEBUG
82167   pWriter->has_iPrevDocid = 0;
82168 #endif
82169 }
82170 static void dlwDestroy(DLWriter *pWriter){
82171   SCRAMBLE(pWriter);
82172 }
82173 /* iFirstDocid is the first docid in the doclist in pData.  It is
82174 ** needed because pData may point within a larger doclist, in which
82175 ** case the first item would be delta-encoded.
82176 **
82177 ** iLastDocid is the final docid in the doclist in pData.  It is
82178 ** needed to create the new iPrevDocid for future delta-encoding.  The
82179 ** code could decode the passed doclist to recreate iLastDocid, but
82180 ** the only current user (docListMerge) already has decoded this
82181 ** information.
82182 */
82183 /* TODO(shess) This has become just a helper for docListMerge.
82184 ** Consider a refactor to make this cleaner.
82185 */
82186 static void dlwAppend(DLWriter *pWriter,
82187                       const char *pData, int nData,
82188                       sqlite_int64 iFirstDocid, sqlite_int64 iLastDocid){
82189   sqlite_int64 iDocid = 0;
82190   char c[VARINT_MAX];
82191   int nFirstOld, nFirstNew;     /* Old and new varint len of first docid. */
82192 #ifndef NDEBUG
82193   sqlite_int64 iLastDocidDelta;
82194 #endif
82195
82196   /* Recode the initial docid as delta from iPrevDocid. */
82197   nFirstOld = fts3GetVarint(pData, &iDocid);
82198   assert( nFirstOld<nData || (nFirstOld==nData && pWriter->iType==DL_DOCIDS) );
82199   nFirstNew = fts3PutVarint(c, iFirstDocid-pWriter->iPrevDocid);
82200
82201   /* Verify that the incoming doclist is valid AND that it ends with
82202   ** the expected docid.  This is essential because we'll trust this
82203   ** docid in future delta-encoding.
82204   */
82205   ASSERT_VALID_DOCLIST(pWriter->iType, pData, nData, &iLastDocidDelta);
82206   assert( iLastDocid==iFirstDocid-iDocid+iLastDocidDelta );
82207
82208   /* Append recoded initial docid and everything else.  Rest of docids
82209   ** should have been delta-encoded from previous initial docid.
82210   */
82211   if( nFirstOld<nData ){
82212     dataBufferAppend2(pWriter->b, c, nFirstNew,
82213                       pData+nFirstOld, nData-nFirstOld);
82214   }else{
82215     dataBufferAppend(pWriter->b, c, nFirstNew);
82216   }
82217   pWriter->iPrevDocid = iLastDocid;
82218 }
82219 static void dlwCopy(DLWriter *pWriter, DLReader *pReader){
82220   dlwAppend(pWriter, dlrDocData(pReader), dlrDocDataBytes(pReader),
82221             dlrDocid(pReader), dlrDocid(pReader));
82222 }
82223 static void dlwAdd(DLWriter *pWriter, sqlite_int64 iDocid){
82224   char c[VARINT_MAX];
82225   int n = fts3PutVarint(c, iDocid-pWriter->iPrevDocid);
82226
82227   /* Docids must ascend. */
82228   assert( !pWriter->has_iPrevDocid || iDocid>pWriter->iPrevDocid );
82229   assert( pWriter->iType==DL_DOCIDS );
82230
82231   dataBufferAppend(pWriter->b, c, n);
82232   pWriter->iPrevDocid = iDocid;
82233 #ifndef NDEBUG
82234   pWriter->has_iPrevDocid = 1;
82235 #endif
82236 }
82237
82238 /*******************************************************************/
82239 /* PLReader is used to read data from a document's position list.  As
82240 ** the caller steps through the list, data is cached so that varints
82241 ** only need to be decoded once.
82242 **
82243 ** plrInit, plrDestroy - create/destroy a reader.
82244 ** plrColumn, plrPosition, plrStartOffset, plrEndOffset - accessors
82245 ** plrAtEnd - at end of stream, only call plrDestroy once true.
82246 ** plrStep - step to the next element.
82247 */
82248 typedef struct PLReader {
82249   /* These refer to the next position's data.  nData will reach 0 when
82250   ** reading the last position, so plrStep() signals EOF by setting
82251   ** pData to NULL.
82252   */
82253   const char *pData;
82254   int nData;
82255
82256   DocListType iType;
82257   int iColumn;         /* the last column read */
82258   int iPosition;       /* the last position read */
82259   int iStartOffset;    /* the last start offset read */
82260   int iEndOffset;      /* the last end offset read */
82261 } PLReader;
82262
82263 static int plrAtEnd(PLReader *pReader){
82264   return pReader->pData==NULL;
82265 }
82266 static int plrColumn(PLReader *pReader){
82267   assert( !plrAtEnd(pReader) );
82268   return pReader->iColumn;
82269 }
82270 static int plrPosition(PLReader *pReader){
82271   assert( !plrAtEnd(pReader) );
82272   return pReader->iPosition;
82273 }
82274 static int plrStartOffset(PLReader *pReader){
82275   assert( !plrAtEnd(pReader) );
82276   return pReader->iStartOffset;
82277 }
82278 static int plrEndOffset(PLReader *pReader){
82279   assert( !plrAtEnd(pReader) );
82280   return pReader->iEndOffset;
82281 }
82282 static void plrStep(PLReader *pReader){
82283   int i, n;
82284
82285   assert( !plrAtEnd(pReader) );
82286
82287   if( pReader->nData==0 ){
82288     pReader->pData = NULL;
82289     return;
82290   }
82291
82292   n = fts3GetVarint32(pReader->pData, &i);
82293   if( i==POS_COLUMN ){
82294     n += fts3GetVarint32(pReader->pData+n, &pReader->iColumn);
82295     pReader->iPosition = 0;
82296     pReader->iStartOffset = 0;
82297     n += fts3GetVarint32(pReader->pData+n, &i);
82298   }
82299   /* Should never see adjacent column changes. */
82300   assert( i!=POS_COLUMN );
82301
82302   if( i==POS_END ){
82303     pReader->nData = 0;
82304     pReader->pData = NULL;
82305     return;
82306   }
82307
82308   pReader->iPosition += i-POS_BASE;
82309   if( pReader->iType==DL_POSITIONS_OFFSETS ){
82310     n += fts3GetVarint32(pReader->pData+n, &i);
82311     pReader->iStartOffset += i;
82312     n += fts3GetVarint32(pReader->pData+n, &i);
82313     pReader->iEndOffset = pReader->iStartOffset+i;
82314   }
82315   assert( n<=pReader->nData );
82316   pReader->pData += n;
82317   pReader->nData -= n;
82318 }
82319
82320 static void plrInit(PLReader *pReader, DLReader *pDLReader){
82321   pReader->pData = dlrPosData(pDLReader);
82322   pReader->nData = dlrPosDataLen(pDLReader);
82323   pReader->iType = pDLReader->iType;
82324   pReader->iColumn = 0;
82325   pReader->iPosition = 0;
82326   pReader->iStartOffset = 0;
82327   pReader->iEndOffset = 0;
82328   plrStep(pReader);
82329 }
82330 static void plrDestroy(PLReader *pReader){
82331   SCRAMBLE(pReader);
82332 }
82333
82334 /*******************************************************************/
82335 /* PLWriter is used in constructing a document's position list.  As a
82336 ** convenience, if iType is DL_DOCIDS, PLWriter becomes a no-op.
82337 ** PLWriter writes to the associated DLWriter's buffer.
82338 **
82339 ** plwInit - init for writing a document's poslist.
82340 ** plwDestroy - clear a writer.
82341 ** plwAdd - append position and offset information.
82342 ** plwCopy - copy next position's data from reader to writer.
82343 ** plwTerminate - add any necessary doclist terminator.
82344 **
82345 ** Calling plwAdd() after plwTerminate() may result in a corrupt
82346 ** doclist.
82347 */
82348 /* TODO(shess) Until we've written the second item, we can cache the
82349 ** first item's information.  Then we'd have three states:
82350 **
82351 ** - initialized with docid, no positions.
82352 ** - docid and one position.
82353 ** - docid and multiple positions.
82354 **
82355 ** Only the last state needs to actually write to dlw->b, which would
82356 ** be an improvement in the DLCollector case.
82357 */
82358 typedef struct PLWriter {
82359   DLWriter *dlw;
82360
82361   int iColumn;    /* the last column written */
82362   int iPos;       /* the last position written */
82363   int iOffset;    /* the last start offset written */
82364 } PLWriter;
82365
82366 /* TODO(shess) In the case where the parent is reading these values
82367 ** from a PLReader, we could optimize to a copy if that PLReader has
82368 ** the same type as pWriter.
82369 */
82370 static void plwAdd(PLWriter *pWriter, int iColumn, int iPos,
82371                    int iStartOffset, int iEndOffset){
82372   /* Worst-case space for POS_COLUMN, iColumn, iPosDelta,
82373   ** iStartOffsetDelta, and iEndOffsetDelta.
82374   */
82375   char c[5*VARINT_MAX];
82376   int n = 0;
82377
82378   /* Ban plwAdd() after plwTerminate(). */
82379   assert( pWriter->iPos!=-1 );
82380
82381   if( pWriter->dlw->iType==DL_DOCIDS ) return;
82382
82383   if( iColumn!=pWriter->iColumn ){
82384     n += fts3PutVarint(c+n, POS_COLUMN);
82385     n += fts3PutVarint(c+n, iColumn);
82386     pWriter->iColumn = iColumn;
82387     pWriter->iPos = 0;
82388     pWriter->iOffset = 0;
82389   }
82390   assert( iPos>=pWriter->iPos );
82391   n += fts3PutVarint(c+n, POS_BASE+(iPos-pWriter->iPos));
82392   pWriter->iPos = iPos;
82393   if( pWriter->dlw->iType==DL_POSITIONS_OFFSETS ){
82394     assert( iStartOffset>=pWriter->iOffset );
82395     n += fts3PutVarint(c+n, iStartOffset-pWriter->iOffset);
82396     pWriter->iOffset = iStartOffset;
82397     assert( iEndOffset>=iStartOffset );
82398     n += fts3PutVarint(c+n, iEndOffset-iStartOffset);
82399   }
82400   dataBufferAppend(pWriter->dlw->b, c, n);
82401 }
82402 static void plwCopy(PLWriter *pWriter, PLReader *pReader){
82403   plwAdd(pWriter, plrColumn(pReader), plrPosition(pReader),
82404          plrStartOffset(pReader), plrEndOffset(pReader));
82405 }
82406 static void plwInit(PLWriter *pWriter, DLWriter *dlw, sqlite_int64 iDocid){
82407   char c[VARINT_MAX];
82408   int n;
82409
82410   pWriter->dlw = dlw;
82411
82412   /* Docids must ascend. */
82413   assert( !pWriter->dlw->has_iPrevDocid || iDocid>pWriter->dlw->iPrevDocid );
82414   n = fts3PutVarint(c, iDocid-pWriter->dlw->iPrevDocid);
82415   dataBufferAppend(pWriter->dlw->b, c, n);
82416   pWriter->dlw->iPrevDocid = iDocid;
82417 #ifndef NDEBUG
82418   pWriter->dlw->has_iPrevDocid = 1;
82419 #endif
82420
82421   pWriter->iColumn = 0;
82422   pWriter->iPos = 0;
82423   pWriter->iOffset = 0;
82424 }
82425 /* TODO(shess) Should plwDestroy() also terminate the doclist?  But
82426 ** then plwDestroy() would no longer be just a destructor, it would
82427 ** also be doing work, which isn't consistent with the overall idiom.
82428 ** Another option would be for plwAdd() to always append any necessary
82429 ** terminator, so that the output is always correct.  But that would
82430 ** add incremental work to the common case with the only benefit being
82431 ** API elegance.  Punt for now.
82432 */
82433 static void plwTerminate(PLWriter *pWriter){
82434   if( pWriter->dlw->iType>DL_DOCIDS ){
82435     char c[VARINT_MAX];
82436     int n = fts3PutVarint(c, POS_END);
82437     dataBufferAppend(pWriter->dlw->b, c, n);
82438   }
82439 #ifndef NDEBUG
82440   /* Mark as terminated for assert in plwAdd(). */
82441   pWriter->iPos = -1;
82442 #endif
82443 }
82444 static void plwDestroy(PLWriter *pWriter){
82445   SCRAMBLE(pWriter);
82446 }
82447
82448 /*******************************************************************/
82449 /* DLCollector wraps PLWriter and DLWriter to provide a
82450 ** dynamically-allocated doclist area to use during tokenization.
82451 **
82452 ** dlcNew - malloc up and initialize a collector.
82453 ** dlcDelete - destroy a collector and all contained items.
82454 ** dlcAddPos - append position and offset information.
82455 ** dlcAddDoclist - add the collected doclist to the given buffer.
82456 ** dlcNext - terminate the current document and open another.
82457 */
82458 typedef struct DLCollector {
82459   DataBuffer b;
82460   DLWriter dlw;
82461   PLWriter plw;
82462 } DLCollector;
82463
82464 /* TODO(shess) This could also be done by calling plwTerminate() and
82465 ** dataBufferAppend().  I tried that, expecting nominal performance
82466 ** differences, but it seemed to pretty reliably be worth 1% to code
82467 ** it this way.  I suspect it is the incremental malloc overhead (some
82468 ** percentage of the plwTerminate() calls will cause a realloc), so
82469 ** this might be worth revisiting if the DataBuffer implementation
82470 ** changes.
82471 */
82472 static void dlcAddDoclist(DLCollector *pCollector, DataBuffer *b){
82473   if( pCollector->dlw.iType>DL_DOCIDS ){
82474     char c[VARINT_MAX];
82475     int n = fts3PutVarint(c, POS_END);
82476     dataBufferAppend2(b, pCollector->b.pData, pCollector->b.nData, c, n);
82477   }else{
82478     dataBufferAppend(b, pCollector->b.pData, pCollector->b.nData);
82479   }
82480 }
82481 static void dlcNext(DLCollector *pCollector, sqlite_int64 iDocid){
82482   plwTerminate(&pCollector->plw);
82483   plwDestroy(&pCollector->plw);
82484   plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
82485 }
82486 static void dlcAddPos(DLCollector *pCollector, int iColumn, int iPos,
82487                       int iStartOffset, int iEndOffset){
82488   plwAdd(&pCollector->plw, iColumn, iPos, iStartOffset, iEndOffset);
82489 }
82490
82491 static DLCollector *dlcNew(sqlite_int64 iDocid, DocListType iType){
82492   DLCollector *pCollector = sqlite3_malloc(sizeof(DLCollector));
82493   dataBufferInit(&pCollector->b, 0);
82494   dlwInit(&pCollector->dlw, iType, &pCollector->b);
82495   plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
82496   return pCollector;
82497 }
82498 static void dlcDelete(DLCollector *pCollector){
82499   plwDestroy(&pCollector->plw);
82500   dlwDestroy(&pCollector->dlw);
82501   dataBufferDestroy(&pCollector->b);
82502   SCRAMBLE(pCollector);
82503   sqlite3_free(pCollector);
82504 }
82505
82506
82507 /* Copy the doclist data of iType in pData/nData into *out, trimming
82508 ** unnecessary data as we go.  Only columns matching iColumn are
82509 ** copied, all columns copied if iColumn is -1.  Elements with no
82510 ** matching columns are dropped.  The output is an iOutType doclist.
82511 */
82512 /* NOTE(shess) This code is only valid after all doclists are merged.
82513 ** If this is run before merges, then doclist items which represent
82514 ** deletion will be trimmed, and will thus not effect a deletion
82515 ** during the merge.
82516 */
82517 static void docListTrim(DocListType iType, const char *pData, int nData,
82518                         int iColumn, DocListType iOutType, DataBuffer *out){
82519   DLReader dlReader;
82520   DLWriter dlWriter;
82521
82522   assert( iOutType<=iType );
82523
82524   dlrInit(&dlReader, iType, pData, nData);
82525   dlwInit(&dlWriter, iOutType, out);
82526
82527   while( !dlrAtEnd(&dlReader) ){
82528     PLReader plReader;
82529     PLWriter plWriter;
82530     int match = 0;
82531
82532     plrInit(&plReader, &dlReader);
82533
82534     while( !plrAtEnd(&plReader) ){
82535       if( iColumn==-1 || plrColumn(&plReader)==iColumn ){
82536         if( !match ){
82537           plwInit(&plWriter, &dlWriter, dlrDocid(&dlReader));
82538           match = 1;
82539         }
82540         plwAdd(&plWriter, plrColumn(&plReader), plrPosition(&plReader),
82541                plrStartOffset(&plReader), plrEndOffset(&plReader));
82542       }
82543       plrStep(&plReader);
82544     }
82545     if( match ){
82546       plwTerminate(&plWriter);
82547       plwDestroy(&plWriter);
82548     }
82549
82550     plrDestroy(&plReader);
82551     dlrStep(&dlReader);
82552   }
82553   dlwDestroy(&dlWriter);
82554   dlrDestroy(&dlReader);
82555 }
82556
82557 /* Used by docListMerge() to keep doclists in the ascending order by
82558 ** docid, then ascending order by age (so the newest comes first).
82559 */
82560 typedef struct OrderedDLReader {
82561   DLReader *pReader;
82562
82563   /* TODO(shess) If we assume that docListMerge pReaders is ordered by
82564   ** age (which we do), then we could use pReader comparisons to break
82565   ** ties.
82566   */
82567   int idx;
82568 } OrderedDLReader;
82569
82570 /* Order eof to end, then by docid asc, idx desc. */
82571 static int orderedDLReaderCmp(OrderedDLReader *r1, OrderedDLReader *r2){
82572   if( dlrAtEnd(r1->pReader) ){
82573     if( dlrAtEnd(r2->pReader) ) return 0;  /* Both atEnd(). */
82574     return 1;                              /* Only r1 atEnd(). */
82575   }
82576   if( dlrAtEnd(r2->pReader) ) return -1;   /* Only r2 atEnd(). */
82577
82578   if( dlrDocid(r1->pReader)<dlrDocid(r2->pReader) ) return -1;
82579   if( dlrDocid(r1->pReader)>dlrDocid(r2->pReader) ) return 1;
82580
82581   /* Descending on idx. */
82582   return r2->idx-r1->idx;
82583 }
82584
82585 /* Bubble p[0] to appropriate place in p[1..n-1].  Assumes that
82586 ** p[1..n-1] is already sorted.
82587 */
82588 /* TODO(shess) Is this frequent enough to warrant a binary search?
82589 ** Before implementing that, instrument the code to check.  In most
82590 ** current usage, I expect that p[0] will be less than p[1] a very
82591 ** high proportion of the time.
82592 */
82593 static void orderedDLReaderReorder(OrderedDLReader *p, int n){
82594   while( n>1 && orderedDLReaderCmp(p, p+1)>0 ){
82595     OrderedDLReader tmp = p[0];
82596     p[0] = p[1];
82597     p[1] = tmp;
82598     n--;
82599     p++;
82600   }
82601 }
82602
82603 /* Given an array of doclist readers, merge their doclist elements
82604 ** into out in sorted order (by docid), dropping elements from older
82605 ** readers when there is a duplicate docid.  pReaders is assumed to be
82606 ** ordered by age, oldest first.
82607 */
82608 /* TODO(shess) nReaders must be <= MERGE_COUNT.  This should probably
82609 ** be fixed.
82610 */
82611 static void docListMerge(DataBuffer *out,
82612                          DLReader *pReaders, int nReaders){
82613   OrderedDLReader readers[MERGE_COUNT];
82614   DLWriter writer;
82615   int i, n;
82616   const char *pStart = 0;
82617   int nStart = 0;
82618   sqlite_int64 iFirstDocid = 0, iLastDocid = 0;
82619
82620   assert( nReaders>0 );
82621   if( nReaders==1 ){
82622     dataBufferAppend(out, dlrDocData(pReaders), dlrAllDataBytes(pReaders));
82623     return;
82624   }
82625
82626   assert( nReaders<=MERGE_COUNT );
82627   n = 0;
82628   for(i=0; i<nReaders; i++){
82629     assert( pReaders[i].iType==pReaders[0].iType );
82630     readers[i].pReader = pReaders+i;
82631     readers[i].idx = i;
82632     n += dlrAllDataBytes(&pReaders[i]);
82633   }
82634   /* Conservatively size output to sum of inputs.  Output should end
82635   ** up strictly smaller than input.
82636   */
82637   dataBufferExpand(out, n);
82638
82639   /* Get the readers into sorted order. */
82640   while( i-->0 ){
82641     orderedDLReaderReorder(readers+i, nReaders-i);
82642   }
82643
82644   dlwInit(&writer, pReaders[0].iType, out);
82645   while( !dlrAtEnd(readers[0].pReader) ){
82646     sqlite_int64 iDocid = dlrDocid(readers[0].pReader);
82647
82648     /* If this is a continuation of the current buffer to copy, extend
82649     ** that buffer.  memcpy() seems to be more efficient if it has a
82650     ** lots of data to copy.
82651     */
82652     if( dlrDocData(readers[0].pReader)==pStart+nStart ){
82653       nStart += dlrDocDataBytes(readers[0].pReader);
82654     }else{
82655       if( pStart!=0 ){
82656         dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
82657       }
82658       pStart = dlrDocData(readers[0].pReader);
82659       nStart = dlrDocDataBytes(readers[0].pReader);
82660       iFirstDocid = iDocid;
82661     }
82662     iLastDocid = iDocid;
82663     dlrStep(readers[0].pReader);
82664
82665     /* Drop all of the older elements with the same docid. */
82666     for(i=1; i<nReaders &&
82667              !dlrAtEnd(readers[i].pReader) &&
82668              dlrDocid(readers[i].pReader)==iDocid; i++){
82669       dlrStep(readers[i].pReader);
82670     }
82671
82672     /* Get the readers back into order. */
82673     while( i-->0 ){
82674       orderedDLReaderReorder(readers+i, nReaders-i);
82675     }
82676   }
82677
82678   /* Copy over any remaining elements. */
82679   if( nStart>0 ) dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
82680   dlwDestroy(&writer);
82681 }
82682
82683 /* Helper function for posListUnion().  Compares the current position
82684 ** between left and right, returning as standard C idiom of <0 if
82685 ** left<right, >0 if left>right, and 0 if left==right.  "End" always
82686 ** compares greater.
82687 */
82688 static int posListCmp(PLReader *pLeft, PLReader *pRight){
82689   assert( pLeft->iType==pRight->iType );
82690   if( pLeft->iType==DL_DOCIDS ) return 0;
82691
82692   if( plrAtEnd(pLeft) ) return plrAtEnd(pRight) ? 0 : 1;
82693   if( plrAtEnd(pRight) ) return -1;
82694
82695   if( plrColumn(pLeft)<plrColumn(pRight) ) return -1;
82696   if( plrColumn(pLeft)>plrColumn(pRight) ) return 1;
82697
82698   if( plrPosition(pLeft)<plrPosition(pRight) ) return -1;
82699   if( plrPosition(pLeft)>plrPosition(pRight) ) return 1;
82700   if( pLeft->iType==DL_POSITIONS ) return 0;
82701
82702   if( plrStartOffset(pLeft)<plrStartOffset(pRight) ) return -1;
82703   if( plrStartOffset(pLeft)>plrStartOffset(pRight) ) return 1;
82704
82705   if( plrEndOffset(pLeft)<plrEndOffset(pRight) ) return -1;
82706   if( plrEndOffset(pLeft)>plrEndOffset(pRight) ) return 1;
82707
82708   return 0;
82709 }
82710
82711 /* Write the union of position lists in pLeft and pRight to pOut.
82712 ** "Union" in this case meaning "All unique position tuples".  Should
82713 ** work with any doclist type, though both inputs and the output
82714 ** should be the same type.
82715 */
82716 static void posListUnion(DLReader *pLeft, DLReader *pRight, DLWriter *pOut){
82717   PLReader left, right;
82718   PLWriter writer;
82719
82720   assert( dlrDocid(pLeft)==dlrDocid(pRight) );
82721   assert( pLeft->iType==pRight->iType );
82722   assert( pLeft->iType==pOut->iType );
82723
82724   plrInit(&left, pLeft);
82725   plrInit(&right, pRight);
82726   plwInit(&writer, pOut, dlrDocid(pLeft));
82727
82728   while( !plrAtEnd(&left) || !plrAtEnd(&right) ){
82729     int c = posListCmp(&left, &right);
82730     if( c<0 ){
82731       plwCopy(&writer, &left);
82732       plrStep(&left);
82733     }else if( c>0 ){
82734       plwCopy(&writer, &right);
82735       plrStep(&right);
82736     }else{
82737       plwCopy(&writer, &left);
82738       plrStep(&left);
82739       plrStep(&right);
82740     }
82741   }
82742
82743   plwTerminate(&writer);
82744   plwDestroy(&writer);
82745   plrDestroy(&left);
82746   plrDestroy(&right);
82747 }
82748
82749 /* Write the union of doclists in pLeft and pRight to pOut.  For
82750 ** docids in common between the inputs, the union of the position
82751 ** lists is written.  Inputs and outputs are always type DL_DEFAULT.
82752 */
82753 static void docListUnion(
82754   const char *pLeft, int nLeft,
82755   const char *pRight, int nRight,
82756   DataBuffer *pOut      /* Write the combined doclist here */
82757 ){
82758   DLReader left, right;
82759   DLWriter writer;
82760
82761   if( nLeft==0 ){
82762     if( nRight!=0) dataBufferAppend(pOut, pRight, nRight);
82763     return;
82764   }
82765   if( nRight==0 ){
82766     dataBufferAppend(pOut, pLeft, nLeft);
82767     return;
82768   }
82769
82770   dlrInit(&left, DL_DEFAULT, pLeft, nLeft);
82771   dlrInit(&right, DL_DEFAULT, pRight, nRight);
82772   dlwInit(&writer, DL_DEFAULT, pOut);
82773
82774   while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
82775     if( dlrAtEnd(&right) ){
82776       dlwCopy(&writer, &left);
82777       dlrStep(&left);
82778     }else if( dlrAtEnd(&left) ){
82779       dlwCopy(&writer, &right);
82780       dlrStep(&right);
82781     }else if( dlrDocid(&left)<dlrDocid(&right) ){
82782       dlwCopy(&writer, &left);
82783       dlrStep(&left);
82784     }else if( dlrDocid(&left)>dlrDocid(&right) ){
82785       dlwCopy(&writer, &right);
82786       dlrStep(&right);
82787     }else{
82788       posListUnion(&left, &right, &writer);
82789       dlrStep(&left);
82790       dlrStep(&right);
82791     }
82792   }
82793
82794   dlrDestroy(&left);
82795   dlrDestroy(&right);
82796   dlwDestroy(&writer);
82797 }
82798
82799 /* 
82800 ** This function is used as part of the implementation of phrase and
82801 ** NEAR matching.
82802 **
82803 ** pLeft and pRight are DLReaders positioned to the same docid in
82804 ** lists of type DL_POSITION. This function writes an entry to the
82805 ** DLWriter pOut for each position in pRight that is less than
82806 ** (nNear+1) greater (but not equal to or smaller) than a position 
82807 ** in pLeft. For example, if nNear is 0, and the positions contained
82808 ** by pLeft and pRight are:
82809 **
82810 **    pLeft:  5 10 15 20
82811 **    pRight: 6  9 17 21
82812 **
82813 ** then the docid is added to pOut. If pOut is of type DL_POSITIONS,
82814 ** then a positionids "6" and "21" are also added to pOut.
82815 **
82816 ** If boolean argument isSaveLeft is true, then positionids are copied
82817 ** from pLeft instead of pRight. In the example above, the positions "5"
82818 ** and "20" would be added instead of "6" and "21".
82819 */
82820 static void posListPhraseMerge(
82821   DLReader *pLeft, 
82822   DLReader *pRight,
82823   int nNear,
82824   int isSaveLeft,
82825   DLWriter *pOut
82826 ){
82827   PLReader left, right;
82828   PLWriter writer;
82829   int match = 0;
82830
82831   assert( dlrDocid(pLeft)==dlrDocid(pRight) );
82832   assert( pOut->iType!=DL_POSITIONS_OFFSETS );
82833
82834   plrInit(&left, pLeft);
82835   plrInit(&right, pRight);
82836
82837   while( !plrAtEnd(&left) && !plrAtEnd(&right) ){
82838     if( plrColumn(&left)<plrColumn(&right) ){
82839       plrStep(&left);
82840     }else if( plrColumn(&left)>plrColumn(&right) ){
82841       plrStep(&right);
82842     }else if( plrPosition(&left)>=plrPosition(&right) ){
82843       plrStep(&right);
82844     }else{
82845       if( (plrPosition(&right)-plrPosition(&left))<=(nNear+1) ){
82846         if( !match ){
82847           plwInit(&writer, pOut, dlrDocid(pLeft));
82848           match = 1;
82849         }
82850         if( !isSaveLeft ){
82851           plwAdd(&writer, plrColumn(&right), plrPosition(&right), 0, 0);
82852         }else{
82853           plwAdd(&writer, plrColumn(&left), plrPosition(&left), 0, 0);
82854         }
82855         plrStep(&right);
82856       }else{
82857         plrStep(&left);
82858       }
82859     }
82860   }
82861
82862   if( match ){
82863     plwTerminate(&writer);
82864     plwDestroy(&writer);
82865   }
82866
82867   plrDestroy(&left);
82868   plrDestroy(&right);
82869 }
82870
82871 /*
82872 ** Compare the values pointed to by the PLReaders passed as arguments. 
82873 ** Return -1 if the value pointed to by pLeft is considered less than
82874 ** the value pointed to by pRight, +1 if it is considered greater
82875 ** than it, or 0 if it is equal. i.e.
82876 **
82877 **     (*pLeft - *pRight)
82878 **
82879 ** A PLReader that is in the EOF condition is considered greater than
82880 ** any other. If neither argument is in EOF state, the return value of
82881 ** plrColumn() is used. If the plrColumn() values are equal, the
82882 ** comparison is on the basis of plrPosition().
82883 */
82884 static int plrCompare(PLReader *pLeft, PLReader *pRight){
82885   assert(!plrAtEnd(pLeft) || !plrAtEnd(pRight));
82886
82887   if( plrAtEnd(pRight) || plrAtEnd(pLeft) ){
82888     return (plrAtEnd(pRight) ? -1 : 1);
82889   }
82890   if( plrColumn(pLeft)!=plrColumn(pRight) ){
82891     return ((plrColumn(pLeft)<plrColumn(pRight)) ? -1 : 1);
82892   }
82893   if( plrPosition(pLeft)!=plrPosition(pRight) ){
82894     return ((plrPosition(pLeft)<plrPosition(pRight)) ? -1 : 1);
82895   }
82896   return 0;
82897 }
82898
82899 /* We have two doclists with positions:  pLeft and pRight. Depending
82900 ** on the value of the nNear parameter, perform either a phrase
82901 ** intersection (if nNear==0) or a NEAR intersection (if nNear>0)
82902 ** and write the results into pOut.
82903 **
82904 ** A phrase intersection means that two documents only match
82905 ** if pLeft.iPos+1==pRight.iPos.
82906 **
82907 ** A NEAR intersection means that two documents only match if 
82908 ** (abs(pLeft.iPos-pRight.iPos)<nNear).
82909 **
82910 ** If a NEAR intersection is requested, then the nPhrase argument should
82911 ** be passed the number of tokens in the two operands to the NEAR operator
82912 ** combined. For example:
82913 **
82914 **       Query syntax               nPhrase
82915 **      ------------------------------------
82916 **       "A B C" NEAR "D E"         5
82917 **       A NEAR B                   2
82918 **
82919 ** iType controls the type of data written to pOut.  If iType is
82920 ** DL_POSITIONS, the positions are those from pRight.
82921 */
82922 static void docListPhraseMerge(
82923   const char *pLeft, int nLeft,
82924   const char *pRight, int nRight,
82925   int nNear,            /* 0 for a phrase merge, non-zero for a NEAR merge */
82926   int nPhrase,          /* Number of tokens in left+right operands to NEAR */
82927   DocListType iType,    /* Type of doclist to write to pOut */
82928   DataBuffer *pOut      /* Write the combined doclist here */
82929 ){
82930   DLReader left, right;
82931   DLWriter writer;
82932
82933   if( nLeft==0 || nRight==0 ) return;
82934
82935   assert( iType!=DL_POSITIONS_OFFSETS );
82936
82937   dlrInit(&left, DL_POSITIONS, pLeft, nLeft);
82938   dlrInit(&right, DL_POSITIONS, pRight, nRight);
82939   dlwInit(&writer, iType, pOut);
82940
82941   while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
82942     if( dlrDocid(&left)<dlrDocid(&right) ){
82943       dlrStep(&left);
82944     }else if( dlrDocid(&right)<dlrDocid(&left) ){
82945       dlrStep(&right);
82946     }else{
82947       if( nNear==0 ){
82948         posListPhraseMerge(&left, &right, 0, 0, &writer);
82949       }else{
82950         /* This case occurs when two terms (simple terms or phrases) are
82951          * connected by a NEAR operator, span (nNear+1). i.e.
82952          *
82953          *     '"terrible company" NEAR widget'
82954          */
82955         DataBuffer one = {0, 0, 0};
82956         DataBuffer two = {0, 0, 0};
82957
82958         DLWriter dlwriter2;
82959         DLReader dr1 = {0, 0, 0, 0, 0}; 
82960         DLReader dr2 = {0, 0, 0, 0, 0};
82961
82962         dlwInit(&dlwriter2, iType, &one);
82963         posListPhraseMerge(&right, &left, nNear-3+nPhrase, 1, &dlwriter2);
82964         dlwInit(&dlwriter2, iType, &two);
82965         posListPhraseMerge(&left, &right, nNear-1, 0, &dlwriter2);
82966
82967         if( one.nData) dlrInit(&dr1, iType, one.pData, one.nData);
82968         if( two.nData) dlrInit(&dr2, iType, two.pData, two.nData);
82969
82970         if( !dlrAtEnd(&dr1) || !dlrAtEnd(&dr2) ){
82971           PLReader pr1 = {0};
82972           PLReader pr2 = {0};
82973
82974           PLWriter plwriter;
82975           plwInit(&plwriter, &writer, dlrDocid(dlrAtEnd(&dr1)?&dr2:&dr1));
82976
82977           if( one.nData ) plrInit(&pr1, &dr1);
82978           if( two.nData ) plrInit(&pr2, &dr2);
82979           while( !plrAtEnd(&pr1) || !plrAtEnd(&pr2) ){
82980             int iCompare = plrCompare(&pr1, &pr2);
82981             switch( iCompare ){
82982               case -1:
82983                 plwCopy(&plwriter, &pr1);
82984                 plrStep(&pr1);
82985                 break;
82986               case 1:
82987                 plwCopy(&plwriter, &pr2);
82988                 plrStep(&pr2);
82989                 break;
82990               case 0:
82991                 plwCopy(&plwriter, &pr1);
82992                 plrStep(&pr1);
82993                 plrStep(&pr2);
82994                 break;
82995             }
82996           }
82997           plwTerminate(&plwriter);
82998         }
82999         dataBufferDestroy(&one);
83000         dataBufferDestroy(&two);
83001       }
83002       dlrStep(&left);
83003       dlrStep(&right);
83004     }
83005   }
83006
83007   dlrDestroy(&left);
83008   dlrDestroy(&right);
83009   dlwDestroy(&writer);
83010 }
83011
83012 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
83013 ** Write the intersection of these two doclists into pOut as a
83014 ** DL_DOCIDS doclist.
83015 */
83016 static void docListAndMerge(
83017   const char *pLeft, int nLeft,
83018   const char *pRight, int nRight,
83019   DataBuffer *pOut      /* Write the combined doclist here */
83020 ){
83021   DLReader left, right;
83022   DLWriter writer;
83023
83024   if( nLeft==0 || nRight==0 ) return;
83025
83026   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
83027   dlrInit(&right, DL_DOCIDS, pRight, nRight);
83028   dlwInit(&writer, DL_DOCIDS, pOut);
83029
83030   while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
83031     if( dlrDocid(&left)<dlrDocid(&right) ){
83032       dlrStep(&left);
83033     }else if( dlrDocid(&right)<dlrDocid(&left) ){
83034       dlrStep(&right);
83035     }else{
83036       dlwAdd(&writer, dlrDocid(&left));
83037       dlrStep(&left);
83038       dlrStep(&right);
83039     }
83040   }
83041
83042   dlrDestroy(&left);
83043   dlrDestroy(&right);
83044   dlwDestroy(&writer);
83045 }
83046
83047 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
83048 ** Write the union of these two doclists into pOut as a
83049 ** DL_DOCIDS doclist.
83050 */
83051 static void docListOrMerge(
83052   const char *pLeft, int nLeft,
83053   const char *pRight, int nRight,
83054   DataBuffer *pOut      /* Write the combined doclist here */
83055 ){
83056   DLReader left, right;
83057   DLWriter writer;
83058
83059   if( nLeft==0 ){
83060     if( nRight!=0 ) dataBufferAppend(pOut, pRight, nRight);
83061     return;
83062   }
83063   if( nRight==0 ){
83064     dataBufferAppend(pOut, pLeft, nLeft);
83065     return;
83066   }
83067
83068   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
83069   dlrInit(&right, DL_DOCIDS, pRight, nRight);
83070   dlwInit(&writer, DL_DOCIDS, pOut);
83071
83072   while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
83073     if( dlrAtEnd(&right) ){
83074       dlwAdd(&writer, dlrDocid(&left));
83075       dlrStep(&left);
83076     }else if( dlrAtEnd(&left) ){
83077       dlwAdd(&writer, dlrDocid(&right));
83078       dlrStep(&right);
83079     }else if( dlrDocid(&left)<dlrDocid(&right) ){
83080       dlwAdd(&writer, dlrDocid(&left));
83081       dlrStep(&left);
83082     }else if( dlrDocid(&right)<dlrDocid(&left) ){
83083       dlwAdd(&writer, dlrDocid(&right));
83084       dlrStep(&right);
83085     }else{
83086       dlwAdd(&writer, dlrDocid(&left));
83087       dlrStep(&left);
83088       dlrStep(&right);
83089     }
83090   }
83091
83092   dlrDestroy(&left);
83093   dlrDestroy(&right);
83094   dlwDestroy(&writer);
83095 }
83096
83097 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
83098 ** Write into pOut as DL_DOCIDS doclist containing all documents that
83099 ** occur in pLeft but not in pRight.
83100 */
83101 static void docListExceptMerge(
83102   const char *pLeft, int nLeft,
83103   const char *pRight, int nRight,
83104   DataBuffer *pOut      /* Write the combined doclist here */
83105 ){
83106   DLReader left, right;
83107   DLWriter writer;
83108
83109   if( nLeft==0 ) return;
83110   if( nRight==0 ){
83111     dataBufferAppend(pOut, pLeft, nLeft);
83112     return;
83113   }
83114
83115   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
83116   dlrInit(&right, DL_DOCIDS, pRight, nRight);
83117   dlwInit(&writer, DL_DOCIDS, pOut);
83118
83119   while( !dlrAtEnd(&left) ){
83120     while( !dlrAtEnd(&right) && dlrDocid(&right)<dlrDocid(&left) ){
83121       dlrStep(&right);
83122     }
83123     if( dlrAtEnd(&right) || dlrDocid(&left)<dlrDocid(&right) ){
83124       dlwAdd(&writer, dlrDocid(&left));
83125     }
83126     dlrStep(&left);
83127   }
83128
83129   dlrDestroy(&left);
83130   dlrDestroy(&right);
83131   dlwDestroy(&writer);
83132 }
83133
83134 static char *string_dup_n(const char *s, int n){
83135   char *str = sqlite3_malloc(n + 1);
83136   memcpy(str, s, n);
83137   str[n] = '\0';
83138   return str;
83139 }
83140
83141 /* Duplicate a string; the caller must free() the returned string.
83142  * (We don't use strdup() since it is not part of the standard C library and
83143  * may not be available everywhere.) */
83144 static char *string_dup(const char *s){
83145   return string_dup_n(s, strlen(s));
83146 }
83147
83148 /* Format a string, replacing each occurrence of the % character with
83149  * zDb.zName.  This may be more convenient than sqlite_mprintf()
83150  * when one string is used repeatedly in a format string.
83151  * The caller must free() the returned string. */
83152 static char *string_format(const char *zFormat,
83153                            const char *zDb, const char *zName){
83154   const char *p;
83155   size_t len = 0;
83156   size_t nDb = strlen(zDb);
83157   size_t nName = strlen(zName);
83158   size_t nFullTableName = nDb+1+nName;
83159   char *result;
83160   char *r;
83161
83162   /* first compute length needed */
83163   for(p = zFormat ; *p ; ++p){
83164     len += (*p=='%' ? nFullTableName : 1);
83165   }
83166   len += 1;  /* for null terminator */
83167
83168   r = result = sqlite3_malloc(len);
83169   for(p = zFormat; *p; ++p){
83170     if( *p=='%' ){
83171       memcpy(r, zDb, nDb);
83172       r += nDb;
83173       *r++ = '.';
83174       memcpy(r, zName, nName);
83175       r += nName;
83176     } else {
83177       *r++ = *p;
83178     }
83179   }
83180   *r++ = '\0';
83181   assert( r == result + len );
83182   return result;
83183 }
83184
83185 static int sql_exec(sqlite3 *db, const char *zDb, const char *zName,
83186                     const char *zFormat){
83187   char *zCommand = string_format(zFormat, zDb, zName);
83188   int rc;
83189   FTSTRACE(("FTS3 sql: %s\n", zCommand));
83190   rc = sqlite3_exec(db, zCommand, NULL, 0, NULL);
83191   sqlite3_free(zCommand);
83192   return rc;
83193 }
83194
83195 static int sql_prepare(sqlite3 *db, const char *zDb, const char *zName,
83196                        sqlite3_stmt **ppStmt, const char *zFormat){
83197   char *zCommand = string_format(zFormat, zDb, zName);
83198   int rc;
83199   FTSTRACE(("FTS3 prepare: %s\n", zCommand));
83200   rc = sqlite3_prepare_v2(db, zCommand, -1, ppStmt, NULL);
83201   sqlite3_free(zCommand);
83202   return rc;
83203 }
83204
83205 /* end utility functions */
83206
83207 /* Forward reference */
83208 typedef struct fulltext_vtab fulltext_vtab;
83209
83210 /* A single term in a query is represented by an instances of
83211 ** the following structure. Each word which may match against
83212 ** document content is a term. Operators, like NEAR or OR, are
83213 ** not terms. Query terms are organized as a flat list stored
83214 ** in the Query.pTerms array.
83215 **
83216 ** If the QueryTerm.nPhrase variable is non-zero, then the QueryTerm
83217 ** is the first in a contiguous string of terms that are either part
83218 ** of the same phrase, or connected by the NEAR operator.
83219 **
83220 ** If the QueryTerm.nNear variable is non-zero, then the token is followed 
83221 ** by a NEAR operator with span set to (nNear-1). For example, the 
83222 ** following query:
83223 **
83224 ** The QueryTerm.iPhrase variable stores the index of the token within
83225 ** its phrase, indexed starting at 1, or 1 if the token is not part 
83226 ** of any phrase.
83227 **
83228 ** For example, the data structure used to represent the following query:
83229 **
83230 **     ... MATCH 'sqlite NEAR/5 google NEAR/2 "search engine"'
83231 **
83232 ** is:
83233 **
83234 **     {nPhrase=4, iPhrase=1, nNear=6, pTerm="sqlite"},
83235 **     {nPhrase=0, iPhrase=1, nNear=3, pTerm="google"},
83236 **     {nPhrase=0, iPhrase=1, nNear=0, pTerm="search"},
83237 **     {nPhrase=0, iPhrase=2, nNear=0, pTerm="engine"},
83238 **
83239 ** compiling the FTS3 syntax to Query structures is done by the parseQuery()
83240 ** function.
83241 */
83242 typedef struct QueryTerm {
83243   short int nPhrase; /* How many following terms are part of the same phrase */
83244   short int iPhrase; /* This is the i-th term of a phrase. */
83245   short int iColumn; /* Column of the index that must match this term */
83246   signed char nNear; /* term followed by a NEAR operator with span=(nNear-1) */
83247   signed char isOr;  /* this term is preceded by "OR" */
83248   signed char isNot; /* this term is preceded by "-" */
83249   signed char isPrefix; /* this term is followed by "*" */
83250   char *pTerm;       /* text of the term.  '\000' terminated.  malloced */
83251   int nTerm;         /* Number of bytes in pTerm[] */
83252 } QueryTerm;
83253
83254
83255 /* A query string is parsed into a Query structure.
83256  *
83257  * We could, in theory, allow query strings to be complicated
83258  * nested expressions with precedence determined by parentheses.
83259  * But none of the major search engines do this.  (Perhaps the
83260  * feeling is that an parenthesized expression is two complex of
83261  * an idea for the average user to grasp.)  Taking our lead from
83262  * the major search engines, we will allow queries to be a list
83263  * of terms (with an implied AND operator) or phrases in double-quotes,
83264  * with a single optional "-" before each non-phrase term to designate
83265  * negation and an optional OR connector.
83266  *
83267  * OR binds more tightly than the implied AND, which is what the
83268  * major search engines seem to do.  So, for example:
83269  * 
83270  *    [one two OR three]     ==>    one AND (two OR three)
83271  *    [one OR two three]     ==>    (one OR two) AND three
83272  *
83273  * A "-" before a term matches all entries that lack that term.
83274  * The "-" must occur immediately before the term with in intervening
83275  * space.  This is how the search engines do it.
83276  *
83277  * A NOT term cannot be the right-hand operand of an OR.  If this
83278  * occurs in the query string, the NOT is ignored:
83279  *
83280  *    [one OR -two]          ==>    one OR two
83281  *
83282  */
83283 typedef struct Query {
83284   fulltext_vtab *pFts;  /* The full text index */
83285   int nTerms;           /* Number of terms in the query */
83286   QueryTerm *pTerms;    /* Array of terms.  Space obtained from malloc() */
83287   int nextIsOr;         /* Set the isOr flag on the next inserted term */
83288   int nextIsNear;       /* Set the isOr flag on the next inserted term */
83289   int nextColumn;       /* Next word parsed must be in this column */
83290   int dfltColumn;       /* The default column */
83291 } Query;
83292
83293
83294 /*
83295 ** An instance of the following structure keeps track of generated
83296 ** matching-word offset information and snippets.
83297 */
83298 typedef struct Snippet {
83299   int nMatch;     /* Total number of matches */
83300   int nAlloc;     /* Space allocated for aMatch[] */
83301   struct snippetMatch { /* One entry for each matching term */
83302     char snStatus;       /* Status flag for use while constructing snippets */
83303     short int iCol;      /* The column that contains the match */
83304     short int iTerm;     /* The index in Query.pTerms[] of the matching term */
83305     int iToken;          /* The index of the matching document token */
83306     short int nByte;     /* Number of bytes in the term */
83307     int iStart;          /* The offset to the first character of the term */
83308   } *aMatch;      /* Points to space obtained from malloc */
83309   char *zOffset;  /* Text rendering of aMatch[] */
83310   int nOffset;    /* strlen(zOffset) */
83311   char *zSnippet; /* Snippet text */
83312   int nSnippet;   /* strlen(zSnippet) */
83313 } Snippet;
83314
83315
83316 typedef enum QueryType {
83317   QUERY_GENERIC,   /* table scan */
83318   QUERY_DOCID,     /* lookup by docid */
83319   QUERY_FULLTEXT   /* QUERY_FULLTEXT + [i] is a full-text search for column i*/
83320 } QueryType;
83321
83322 typedef enum fulltext_statement {
83323   CONTENT_INSERT_STMT,
83324   CONTENT_SELECT_STMT,
83325   CONTENT_UPDATE_STMT,
83326   CONTENT_DELETE_STMT,
83327
83328   BLOCK_INSERT_STMT,
83329   BLOCK_SELECT_STMT,
83330   BLOCK_DELETE_STMT,
83331
83332   SEGDIR_MAX_INDEX_STMT,
83333   SEGDIR_SET_STMT,
83334   SEGDIR_SELECT_STMT,
83335   SEGDIR_SPAN_STMT,
83336   SEGDIR_DELETE_STMT,
83337   SEGDIR_SELECT_ALL_STMT,
83338
83339   MAX_STMT                     /* Always at end! */
83340 } fulltext_statement;
83341
83342 /* These must exactly match the enum above. */
83343 /* TODO(shess): Is there some risk that a statement will be used in two
83344 ** cursors at once, e.g.  if a query joins a virtual table to itself?
83345 ** If so perhaps we should move some of these to the cursor object.
83346 */
83347 static const char *const fulltext_zStatement[MAX_STMT] = {
83348   /* CONTENT_INSERT */ NULL,  /* generated in contentInsertStatement() */
83349   /* CONTENT_SELECT */ NULL,  /* generated in contentSelectStatement() */
83350   /* CONTENT_UPDATE */ NULL,  /* generated in contentUpdateStatement() */
83351   /* CONTENT_DELETE */ "delete from %_content where docid = ?",
83352
83353   /* BLOCK_INSERT */
83354   "insert into %_segments (blockid, block) values (null, ?)",
83355   /* BLOCK_SELECT */ "select block from %_segments where blockid = ?",
83356   /* BLOCK_DELETE */ "delete from %_segments where blockid between ? and ?",
83357
83358   /* SEGDIR_MAX_INDEX */ "select max(idx) from %_segdir where level = ?",
83359   /* SEGDIR_SET */ "insert into %_segdir values (?, ?, ?, ?, ?, ?)",
83360   /* SEGDIR_SELECT */
83361   "select start_block, leaves_end_block, root from %_segdir "
83362   " where level = ? order by idx",
83363   /* SEGDIR_SPAN */
83364   "select min(start_block), max(end_block) from %_segdir "
83365   " where level = ? and start_block <> 0",
83366   /* SEGDIR_DELETE */ "delete from %_segdir where level = ?",
83367   /* SEGDIR_SELECT_ALL */
83368   "select root, leaves_end_block from %_segdir order by level desc, idx",
83369 };
83370
83371 /*
83372 ** A connection to a fulltext index is an instance of the following
83373 ** structure.  The xCreate and xConnect methods create an instance
83374 ** of this structure and xDestroy and xDisconnect free that instance.
83375 ** All other methods receive a pointer to the structure as one of their
83376 ** arguments.
83377 */
83378 struct fulltext_vtab {
83379   sqlite3_vtab base;               /* Base class used by SQLite core */
83380   sqlite3 *db;                     /* The database connection */
83381   const char *zDb;                 /* logical database name */
83382   const char *zName;               /* virtual table name */
83383   int nColumn;                     /* number of columns in virtual table */
83384   char **azColumn;                 /* column names.  malloced */
83385   char **azContentColumn;          /* column names in content table; malloced */
83386   sqlite3_tokenizer *pTokenizer;   /* tokenizer for inserts and queries */
83387
83388   /* Precompiled statements which we keep as long as the table is
83389   ** open.
83390   */
83391   sqlite3_stmt *pFulltextStatements[MAX_STMT];
83392
83393   /* Precompiled statements used for segment merges.  We run a
83394   ** separate select across the leaf level of each tree being merged.
83395   */
83396   sqlite3_stmt *pLeafSelectStmts[MERGE_COUNT];
83397   /* The statement used to prepare pLeafSelectStmts. */
83398 #define LEAF_SELECT \
83399   "select block from %_segments where blockid between ? and ? order by blockid"
83400
83401   /* These buffer pending index updates during transactions.
83402   ** nPendingData estimates the memory size of the pending data.  It
83403   ** doesn't include the hash-bucket overhead, nor any malloc
83404   ** overhead.  When nPendingData exceeds kPendingThreshold, the
83405   ** buffer is flushed even before the transaction closes.
83406   ** pendingTerms stores the data, and is only valid when nPendingData
83407   ** is >=0 (nPendingData<0 means pendingTerms has not been
83408   ** initialized).  iPrevDocid is the last docid written, used to make
83409   ** certain we're inserting in sorted order.
83410   */
83411   int nPendingData;
83412 #define kPendingThreshold (1*1024*1024)
83413   sqlite_int64 iPrevDocid;
83414   fts3Hash pendingTerms;
83415 };
83416
83417 /*
83418 ** When the core wants to do a query, it create a cursor using a
83419 ** call to xOpen.  This structure is an instance of a cursor.  It
83420 ** is destroyed by xClose.
83421 */
83422 typedef struct fulltext_cursor {
83423   sqlite3_vtab_cursor base;        /* Base class used by SQLite core */
83424   QueryType iCursorType;           /* Copy of sqlite3_index_info.idxNum */
83425   sqlite3_stmt *pStmt;             /* Prepared statement in use by the cursor */
83426   int eof;                         /* True if at End Of Results */
83427   Query q;                         /* Parsed query string */
83428   Snippet snippet;                 /* Cached snippet for the current row */
83429   int iColumn;                     /* Column being searched */
83430   DataBuffer result;               /* Doclist results from fulltextQuery */
83431   DLReader reader;                 /* Result reader if result not empty */
83432 } fulltext_cursor;
83433
83434 static struct fulltext_vtab *cursor_vtab(fulltext_cursor *c){
83435   return (fulltext_vtab *) c->base.pVtab;
83436 }
83437
83438 static const sqlite3_module fts3Module;   /* forward declaration */
83439
83440 /* Return a dynamically generated statement of the form
83441  *   insert into %_content (docid, ...) values (?, ...)
83442  */
83443 static const char *contentInsertStatement(fulltext_vtab *v){
83444   StringBuffer sb;
83445   int i;
83446
83447   initStringBuffer(&sb);
83448   append(&sb, "insert into %_content (docid, ");
83449   appendList(&sb, v->nColumn, v->azContentColumn);
83450   append(&sb, ") values (?");
83451   for(i=0; i<v->nColumn; ++i)
83452     append(&sb, ", ?");
83453   append(&sb, ")");
83454   return stringBufferData(&sb);
83455 }
83456
83457 /* Return a dynamically generated statement of the form
83458  *   select <content columns> from %_content where docid = ?
83459  */
83460 static const char *contentSelectStatement(fulltext_vtab *v){
83461   StringBuffer sb;
83462   initStringBuffer(&sb);
83463   append(&sb, "SELECT ");
83464   appendList(&sb, v->nColumn, v->azContentColumn);
83465   append(&sb, " FROM %_content WHERE docid = ?");
83466   return stringBufferData(&sb);
83467 }
83468
83469 /* Return a dynamically generated statement of the form
83470  *   update %_content set [col_0] = ?, [col_1] = ?, ...
83471  *                    where docid = ?
83472  */
83473 static const char *contentUpdateStatement(fulltext_vtab *v){
83474   StringBuffer sb;
83475   int i;
83476
83477   initStringBuffer(&sb);
83478   append(&sb, "update %_content set ");
83479   for(i=0; i<v->nColumn; ++i) {
83480     if( i>0 ){
83481       append(&sb, ", ");
83482     }
83483     append(&sb, v->azContentColumn[i]);
83484     append(&sb, " = ?");
83485   }
83486   append(&sb, " where docid = ?");
83487   return stringBufferData(&sb);
83488 }
83489
83490 /* Puts a freshly-prepared statement determined by iStmt in *ppStmt.
83491 ** If the indicated statement has never been prepared, it is prepared
83492 ** and cached, otherwise the cached version is reset.
83493 */
83494 static int sql_get_statement(fulltext_vtab *v, fulltext_statement iStmt,
83495                              sqlite3_stmt **ppStmt){
83496   assert( iStmt<MAX_STMT );
83497   if( v->pFulltextStatements[iStmt]==NULL ){
83498     const char *zStmt;
83499     int rc;
83500     switch( iStmt ){
83501       case CONTENT_INSERT_STMT:
83502         zStmt = contentInsertStatement(v); break;
83503       case CONTENT_SELECT_STMT:
83504         zStmt = contentSelectStatement(v); break;
83505       case CONTENT_UPDATE_STMT:
83506         zStmt = contentUpdateStatement(v); break;
83507       default:
83508         zStmt = fulltext_zStatement[iStmt];
83509     }
83510     rc = sql_prepare(v->db, v->zDb, v->zName, &v->pFulltextStatements[iStmt],
83511                          zStmt);
83512     if( zStmt != fulltext_zStatement[iStmt]) sqlite3_free((void *) zStmt);
83513     if( rc!=SQLITE_OK ) return rc;
83514   } else {
83515     int rc = sqlite3_reset(v->pFulltextStatements[iStmt]);
83516     if( rc!=SQLITE_OK ) return rc;
83517   }
83518
83519   *ppStmt = v->pFulltextStatements[iStmt];
83520   return SQLITE_OK;
83521 }
83522
83523 /* Like sqlite3_step(), but convert SQLITE_DONE to SQLITE_OK and
83524 ** SQLITE_ROW to SQLITE_ERROR.  Useful for statements like UPDATE,
83525 ** where we expect no results.
83526 */
83527 static int sql_single_step(sqlite3_stmt *s){
83528   int rc = sqlite3_step(s);
83529   return (rc==SQLITE_DONE) ? SQLITE_OK : rc;
83530 }
83531
83532 /* Like sql_get_statement(), but for special replicated LEAF_SELECT
83533 ** statements.
83534 */
83535 /* TODO(shess) Write version for generic statements and then share
83536 ** that between the cached-statement functions.
83537 */
83538 static int sql_get_leaf_statement(fulltext_vtab *v, int idx,
83539                                   sqlite3_stmt **ppStmt){
83540   assert( idx>=0 && idx<MERGE_COUNT );
83541   if( v->pLeafSelectStmts[idx]==NULL ){
83542     int rc = sql_prepare(v->db, v->zDb, v->zName, &v->pLeafSelectStmts[idx],
83543                          LEAF_SELECT);
83544     if( rc!=SQLITE_OK ) return rc;
83545   }else{
83546     int rc = sqlite3_reset(v->pLeafSelectStmts[idx]);
83547     if( rc!=SQLITE_OK ) return rc;
83548   }
83549
83550   *ppStmt = v->pLeafSelectStmts[idx];
83551   return SQLITE_OK;
83552 }
83553
83554 /* insert into %_content (docid, ...) values ([docid], [pValues])
83555 ** If the docid contains SQL NULL, then a unique docid will be
83556 ** generated.
83557 */
83558 static int content_insert(fulltext_vtab *v, sqlite3_value *docid,
83559                           sqlite3_value **pValues){
83560   sqlite3_stmt *s;
83561   int i;
83562   int rc = sql_get_statement(v, CONTENT_INSERT_STMT, &s);
83563   if( rc!=SQLITE_OK ) return rc;
83564
83565   rc = sqlite3_bind_value(s, 1, docid);
83566   if( rc!=SQLITE_OK ) return rc;
83567
83568   for(i=0; i<v->nColumn; ++i){
83569     rc = sqlite3_bind_value(s, 2+i, pValues[i]);
83570     if( rc!=SQLITE_OK ) return rc;
83571   }
83572
83573   return sql_single_step(s);
83574 }
83575
83576 /* update %_content set col0 = pValues[0], col1 = pValues[1], ...
83577  *                  where docid = [iDocid] */
83578 static int content_update(fulltext_vtab *v, sqlite3_value **pValues,
83579                           sqlite_int64 iDocid){
83580   sqlite3_stmt *s;
83581   int i;
83582   int rc = sql_get_statement(v, CONTENT_UPDATE_STMT, &s);
83583   if( rc!=SQLITE_OK ) return rc;
83584
83585   for(i=0; i<v->nColumn; ++i){
83586     rc = sqlite3_bind_value(s, 1+i, pValues[i]);
83587     if( rc!=SQLITE_OK ) return rc;
83588   }
83589
83590   rc = sqlite3_bind_int64(s, 1+v->nColumn, iDocid);
83591   if( rc!=SQLITE_OK ) return rc;
83592
83593   return sql_single_step(s);
83594 }
83595
83596 static void freeStringArray(int nString, const char **pString){
83597   int i;
83598
83599   for (i=0 ; i < nString ; ++i) {
83600     if( pString[i]!=NULL ) sqlite3_free((void *) pString[i]);
83601   }
83602   sqlite3_free((void *) pString);
83603 }
83604
83605 /* select * from %_content where docid = [iDocid]
83606  * The caller must delete the returned array and all strings in it.
83607  * null fields will be NULL in the returned array.
83608  *
83609  * TODO: Perhaps we should return pointer/length strings here for consistency
83610  * with other code which uses pointer/length. */
83611 static int content_select(fulltext_vtab *v, sqlite_int64 iDocid,
83612                           const char ***pValues){
83613   sqlite3_stmt *s;
83614   const char **values;
83615   int i;
83616   int rc;
83617
83618   *pValues = NULL;
83619
83620   rc = sql_get_statement(v, CONTENT_SELECT_STMT, &s);
83621   if( rc!=SQLITE_OK ) return rc;
83622
83623   rc = sqlite3_bind_int64(s, 1, iDocid);
83624   if( rc!=SQLITE_OK ) return rc;
83625
83626   rc = sqlite3_step(s);
83627   if( rc!=SQLITE_ROW ) return rc;
83628
83629   values = (const char **) sqlite3_malloc(v->nColumn * sizeof(const char *));
83630   for(i=0; i<v->nColumn; ++i){
83631     if( sqlite3_column_type(s, i)==SQLITE_NULL ){
83632       values[i] = NULL;
83633     }else{
83634       values[i] = string_dup((char*)sqlite3_column_text(s, i));
83635     }
83636   }
83637
83638   /* We expect only one row.  We must execute another sqlite3_step()
83639    * to complete the iteration; otherwise the table will remain locked. */
83640   rc = sqlite3_step(s);
83641   if( rc==SQLITE_DONE ){
83642     *pValues = values;
83643     return SQLITE_OK;
83644   }
83645
83646   freeStringArray(v->nColumn, values);
83647   return rc;
83648 }
83649
83650 /* delete from %_content where docid = [iDocid ] */
83651 static int content_delete(fulltext_vtab *v, sqlite_int64 iDocid){
83652   sqlite3_stmt *s;
83653   int rc = sql_get_statement(v, CONTENT_DELETE_STMT, &s);
83654   if( rc!=SQLITE_OK ) return rc;
83655
83656   rc = sqlite3_bind_int64(s, 1, iDocid);
83657   if( rc!=SQLITE_OK ) return rc;
83658
83659   return sql_single_step(s);
83660 }
83661
83662 /* insert into %_segments values ([pData])
83663 **   returns assigned blockid in *piBlockid
83664 */
83665 static int block_insert(fulltext_vtab *v, const char *pData, int nData,
83666                         sqlite_int64 *piBlockid){
83667   sqlite3_stmt *s;
83668   int rc = sql_get_statement(v, BLOCK_INSERT_STMT, &s);
83669   if( rc!=SQLITE_OK ) return rc;
83670
83671   rc = sqlite3_bind_blob(s, 1, pData, nData, SQLITE_STATIC);
83672   if( rc!=SQLITE_OK ) return rc;
83673
83674   rc = sqlite3_step(s);
83675   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
83676   if( rc!=SQLITE_DONE ) return rc;
83677
83678   /* blockid column is an alias for rowid. */
83679   *piBlockid = sqlite3_last_insert_rowid(v->db);
83680   return SQLITE_OK;
83681 }
83682
83683 /* delete from %_segments
83684 **   where blockid between [iStartBlockid] and [iEndBlockid]
83685 **
83686 ** Deletes the range of blocks, inclusive, used to delete the blocks
83687 ** which form a segment.
83688 */
83689 static int block_delete(fulltext_vtab *v,
83690                         sqlite_int64 iStartBlockid, sqlite_int64 iEndBlockid){
83691   sqlite3_stmt *s;
83692   int rc = sql_get_statement(v, BLOCK_DELETE_STMT, &s);
83693   if( rc!=SQLITE_OK ) return rc;
83694
83695   rc = sqlite3_bind_int64(s, 1, iStartBlockid);
83696   if( rc!=SQLITE_OK ) return rc;
83697
83698   rc = sqlite3_bind_int64(s, 2, iEndBlockid);
83699   if( rc!=SQLITE_OK ) return rc;
83700
83701   return sql_single_step(s);
83702 }
83703
83704 /* Returns SQLITE_ROW with *pidx set to the maximum segment idx found
83705 ** at iLevel.  Returns SQLITE_DONE if there are no segments at
83706 ** iLevel.  Otherwise returns an error.
83707 */
83708 static int segdir_max_index(fulltext_vtab *v, int iLevel, int *pidx){
83709   sqlite3_stmt *s;
83710   int rc = sql_get_statement(v, SEGDIR_MAX_INDEX_STMT, &s);
83711   if( rc!=SQLITE_OK ) return rc;
83712
83713   rc = sqlite3_bind_int(s, 1, iLevel);
83714   if( rc!=SQLITE_OK ) return rc;
83715
83716   rc = sqlite3_step(s);
83717   /* Should always get at least one row due to how max() works. */
83718   if( rc==SQLITE_DONE ) return SQLITE_DONE;
83719   if( rc!=SQLITE_ROW ) return rc;
83720
83721   /* NULL means that there were no inputs to max(). */
83722   if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
83723     rc = sqlite3_step(s);
83724     if( rc==SQLITE_ROW ) return SQLITE_ERROR;
83725     return rc;
83726   }
83727
83728   *pidx = sqlite3_column_int(s, 0);
83729
83730   /* We expect only one row.  We must execute another sqlite3_step()
83731    * to complete the iteration; otherwise the table will remain locked. */
83732   rc = sqlite3_step(s);
83733   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
83734   if( rc!=SQLITE_DONE ) return rc;
83735   return SQLITE_ROW;
83736 }
83737
83738 /* insert into %_segdir values (
83739 **   [iLevel], [idx],
83740 **   [iStartBlockid], [iLeavesEndBlockid], [iEndBlockid],
83741 **   [pRootData]
83742 ** )
83743 */
83744 static int segdir_set(fulltext_vtab *v, int iLevel, int idx,
83745                       sqlite_int64 iStartBlockid,
83746                       sqlite_int64 iLeavesEndBlockid,
83747                       sqlite_int64 iEndBlockid,
83748                       const char *pRootData, int nRootData){
83749   sqlite3_stmt *s;
83750   int rc = sql_get_statement(v, SEGDIR_SET_STMT, &s);
83751   if( rc!=SQLITE_OK ) return rc;
83752
83753   rc = sqlite3_bind_int(s, 1, iLevel);
83754   if( rc!=SQLITE_OK ) return rc;
83755
83756   rc = sqlite3_bind_int(s, 2, idx);
83757   if( rc!=SQLITE_OK ) return rc;
83758
83759   rc = sqlite3_bind_int64(s, 3, iStartBlockid);
83760   if( rc!=SQLITE_OK ) return rc;
83761
83762   rc = sqlite3_bind_int64(s, 4, iLeavesEndBlockid);
83763   if( rc!=SQLITE_OK ) return rc;
83764
83765   rc = sqlite3_bind_int64(s, 5, iEndBlockid);
83766   if( rc!=SQLITE_OK ) return rc;
83767
83768   rc = sqlite3_bind_blob(s, 6, pRootData, nRootData, SQLITE_STATIC);
83769   if( rc!=SQLITE_OK ) return rc;
83770
83771   return sql_single_step(s);
83772 }
83773
83774 /* Queries %_segdir for the block span of the segments in level
83775 ** iLevel.  Returns SQLITE_DONE if there are no blocks for iLevel,
83776 ** SQLITE_ROW if there are blocks, else an error.
83777 */
83778 static int segdir_span(fulltext_vtab *v, int iLevel,
83779                        sqlite_int64 *piStartBlockid,
83780                        sqlite_int64 *piEndBlockid){
83781   sqlite3_stmt *s;
83782   int rc = sql_get_statement(v, SEGDIR_SPAN_STMT, &s);
83783   if( rc!=SQLITE_OK ) return rc;
83784
83785   rc = sqlite3_bind_int(s, 1, iLevel);
83786   if( rc!=SQLITE_OK ) return rc;
83787
83788   rc = sqlite3_step(s);
83789   if( rc==SQLITE_DONE ) return SQLITE_DONE;  /* Should never happen */
83790   if( rc!=SQLITE_ROW ) return rc;
83791
83792   /* This happens if all segments at this level are entirely inline. */
83793   if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
83794     /* We expect only one row.  We must execute another sqlite3_step()
83795      * to complete the iteration; otherwise the table will remain locked. */
83796     int rc2 = sqlite3_step(s);
83797     if( rc2==SQLITE_ROW ) return SQLITE_ERROR;
83798     return rc2;
83799   }
83800
83801   *piStartBlockid = sqlite3_column_int64(s, 0);
83802   *piEndBlockid = sqlite3_column_int64(s, 1);
83803
83804   /* We expect only one row.  We must execute another sqlite3_step()
83805    * to complete the iteration; otherwise the table will remain locked. */
83806   rc = sqlite3_step(s);
83807   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
83808   if( rc!=SQLITE_DONE ) return rc;
83809   return SQLITE_ROW;
83810 }
83811
83812 /* Delete the segment blocks and segment directory records for all
83813 ** segments at iLevel.
83814 */
83815 static int segdir_delete(fulltext_vtab *v, int iLevel){
83816   sqlite3_stmt *s;
83817   sqlite_int64 iStartBlockid, iEndBlockid;
83818   int rc = segdir_span(v, iLevel, &iStartBlockid, &iEndBlockid);
83819   if( rc!=SQLITE_ROW && rc!=SQLITE_DONE ) return rc;
83820
83821   if( rc==SQLITE_ROW ){
83822     rc = block_delete(v, iStartBlockid, iEndBlockid);
83823     if( rc!=SQLITE_OK ) return rc;
83824   }
83825
83826   /* Delete the segment directory itself. */
83827   rc = sql_get_statement(v, SEGDIR_DELETE_STMT, &s);
83828   if( rc!=SQLITE_OK ) return rc;
83829
83830   rc = sqlite3_bind_int64(s, 1, iLevel);
83831   if( rc!=SQLITE_OK ) return rc;
83832
83833   return sql_single_step(s);
83834 }
83835
83836 /* TODO(shess) clearPendingTerms() is far down the file because
83837 ** writeZeroSegment() is far down the file because LeafWriter is far
83838 ** down the file.  Consider refactoring the code to move the non-vtab
83839 ** code above the vtab code so that we don't need this forward
83840 ** reference.
83841 */
83842 static int clearPendingTerms(fulltext_vtab *v);
83843
83844 /*
83845 ** Free the memory used to contain a fulltext_vtab structure.
83846 */
83847 static void fulltext_vtab_destroy(fulltext_vtab *v){
83848   int iStmt, i;
83849
83850   FTSTRACE(("FTS3 Destroy %p\n", v));
83851   for( iStmt=0; iStmt<MAX_STMT; iStmt++ ){
83852     if( v->pFulltextStatements[iStmt]!=NULL ){
83853       sqlite3_finalize(v->pFulltextStatements[iStmt]);
83854       v->pFulltextStatements[iStmt] = NULL;
83855     }
83856   }
83857
83858   for( i=0; i<MERGE_COUNT; i++ ){
83859     if( v->pLeafSelectStmts[i]!=NULL ){
83860       sqlite3_finalize(v->pLeafSelectStmts[i]);
83861       v->pLeafSelectStmts[i] = NULL;
83862     }
83863   }
83864
83865   if( v->pTokenizer!=NULL ){
83866     v->pTokenizer->pModule->xDestroy(v->pTokenizer);
83867     v->pTokenizer = NULL;
83868   }
83869
83870   clearPendingTerms(v);
83871
83872   sqlite3_free(v->azColumn);
83873   for(i = 0; i < v->nColumn; ++i) {
83874     sqlite3_free(v->azContentColumn[i]);
83875   }
83876   sqlite3_free(v->azContentColumn);
83877   sqlite3_free(v);
83878 }
83879
83880 /*
83881 ** Token types for parsing the arguments to xConnect or xCreate.
83882 */
83883 #define TOKEN_EOF         0    /* End of file */
83884 #define TOKEN_SPACE       1    /* Any kind of whitespace */
83885 #define TOKEN_ID          2    /* An identifier */
83886 #define TOKEN_STRING      3    /* A string literal */
83887 #define TOKEN_PUNCT       4    /* A single punctuation character */
83888
83889 /*
83890 ** If X is a character that can be used in an identifier then
83891 ** ftsIdChar(X) will be true.  Otherwise it is false.
83892 **
83893 ** For ASCII, any character with the high-order bit set is
83894 ** allowed in an identifier.  For 7-bit characters, 
83895 ** isFtsIdChar[X] must be 1.
83896 **
83897 ** Ticket #1066.  the SQL standard does not allow '$' in the
83898 ** middle of identfiers.  But many SQL implementations do. 
83899 ** SQLite will allow '$' in identifiers for compatibility.
83900 ** But the feature is undocumented.
83901 */
83902 static const char isFtsIdChar[] = {
83903 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
83904     0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
83905     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
83906     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
83907     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
83908     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
83909     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
83910 };
83911 #define ftsIdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && isFtsIdChar[c-0x20]))
83912
83913
83914 /*
83915 ** Return the length of the token that begins at z[0]. 
83916 ** Store the token type in *tokenType before returning.
83917 */
83918 static int ftsGetToken(const char *z, int *tokenType){
83919   int i, c;
83920   switch( *z ){
83921     case 0: {
83922       *tokenType = TOKEN_EOF;
83923       return 0;
83924     }
83925     case ' ': case '\t': case '\n': case '\f': case '\r': {
83926       for(i=1; safe_isspace(z[i]); i++){}
83927       *tokenType = TOKEN_SPACE;
83928       return i;
83929     }
83930     case '`':
83931     case '\'':
83932     case '"': {
83933       int delim = z[0];
83934       for(i=1; (c=z[i])!=0; i++){
83935         if( c==delim ){
83936           if( z[i+1]==delim ){
83937             i++;
83938           }else{
83939             break;
83940           }
83941         }
83942       }
83943       *tokenType = TOKEN_STRING;
83944       return i + (c!=0);
83945     }
83946     case '[': {
83947       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
83948       *tokenType = TOKEN_ID;
83949       return i;
83950     }
83951     default: {
83952       if( !ftsIdChar(*z) ){
83953         break;
83954       }
83955       for(i=1; ftsIdChar(z[i]); i++){}
83956       *tokenType = TOKEN_ID;
83957       return i;
83958     }
83959   }
83960   *tokenType = TOKEN_PUNCT;
83961   return 1;
83962 }
83963
83964 /*
83965 ** A token extracted from a string is an instance of the following
83966 ** structure.
83967 */
83968 typedef struct FtsToken {
83969   const char *z;       /* Pointer to token text.  Not '\000' terminated */
83970   short int n;         /* Length of the token text in bytes. */
83971 } FtsToken;
83972
83973 /*
83974 ** Given a input string (which is really one of the argv[] parameters
83975 ** passed into xConnect or xCreate) split the string up into tokens.
83976 ** Return an array of pointers to '\000' terminated strings, one string
83977 ** for each non-whitespace token.
83978 **
83979 ** The returned array is terminated by a single NULL pointer.
83980 **
83981 ** Space to hold the returned array is obtained from a single
83982 ** malloc and should be freed by passing the return value to free().
83983 ** The individual strings within the token list are all a part of
83984 ** the single memory allocation and will all be freed at once.
83985 */
83986 static char **tokenizeString(const char *z, int *pnToken){
83987   int nToken = 0;
83988   FtsToken *aToken = sqlite3_malloc( strlen(z) * sizeof(aToken[0]) );
83989   int n = 1;
83990   int e, i;
83991   int totalSize = 0;
83992   char **azToken;
83993   char *zCopy;
83994   while( n>0 ){
83995     n = ftsGetToken(z, &e);
83996     if( e!=TOKEN_SPACE ){
83997       aToken[nToken].z = z;
83998       aToken[nToken].n = n;
83999       nToken++;
84000       totalSize += n+1;
84001     }
84002     z += n;
84003   }
84004   azToken = (char**)sqlite3_malloc( nToken*sizeof(char*) + totalSize );
84005   zCopy = (char*)&azToken[nToken];
84006   nToken--;
84007   for(i=0; i<nToken; i++){
84008     azToken[i] = zCopy;
84009     n = aToken[i].n;
84010     memcpy(zCopy, aToken[i].z, n);
84011     zCopy[n] = 0;
84012     zCopy += n+1;
84013   }
84014   azToken[nToken] = 0;
84015   sqlite3_free(aToken);
84016   *pnToken = nToken;
84017   return azToken;
84018 }
84019
84020 /*
84021 ** Convert an SQL-style quoted string into a normal string by removing
84022 ** the quote characters.  The conversion is done in-place.  If the
84023 ** input does not begin with a quote character, then this routine
84024 ** is a no-op.
84025 **
84026 ** Examples:
84027 **
84028 **     "abc"   becomes   abc
84029 **     'xyz'   becomes   xyz
84030 **     [pqr]   becomes   pqr
84031 **     `mno`   becomes   mno
84032 */
84033 static void dequoteString(char *z){
84034   int quote;
84035   int i, j;
84036   if( z==0 ) return;
84037   quote = z[0];
84038   switch( quote ){
84039     case '\'':  break;
84040     case '"':   break;
84041     case '`':   break;                /* For MySQL compatibility */
84042     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
84043     default:    return;
84044   }
84045   for(i=1, j=0; z[i]; i++){
84046     if( z[i]==quote ){
84047       if( z[i+1]==quote ){
84048         z[j++] = quote;
84049         i++;
84050       }else{
84051         z[j++] = 0;
84052         break;
84053       }
84054     }else{
84055       z[j++] = z[i];
84056     }
84057   }
84058 }
84059
84060 /*
84061 ** The input azIn is a NULL-terminated list of tokens.  Remove the first
84062 ** token and all punctuation tokens.  Remove the quotes from
84063 ** around string literal tokens.
84064 **
84065 ** Example:
84066 **
84067 **     input:      tokenize chinese ( 'simplifed' , 'mixed' )
84068 **     output:     chinese simplifed mixed
84069 **
84070 ** Another example:
84071 **
84072 **     input:      delimiters ( '[' , ']' , '...' )
84073 **     output:     [ ] ...
84074 */
84075 static void tokenListToIdList(char **azIn){
84076   int i, j;
84077   if( azIn ){
84078     for(i=0, j=-1; azIn[i]; i++){
84079       if( safe_isalnum(azIn[i][0]) || azIn[i][1] ){
84080         dequoteString(azIn[i]);
84081         if( j>=0 ){
84082           azIn[j] = azIn[i];
84083         }
84084         j++;
84085       }
84086     }
84087     azIn[j] = 0;
84088   }
84089 }
84090
84091
84092 /*
84093 ** Find the first alphanumeric token in the string zIn.  Null-terminate
84094 ** this token.  Remove any quotation marks.  And return a pointer to
84095 ** the result.
84096 */
84097 static char *firstToken(char *zIn, char **pzTail){
84098   int n, ttype;
84099   while(1){
84100     n = ftsGetToken(zIn, &ttype);
84101     if( ttype==TOKEN_SPACE ){
84102       zIn += n;
84103     }else if( ttype==TOKEN_EOF ){
84104       *pzTail = zIn;
84105       return 0;
84106     }else{
84107       zIn[n] = 0;
84108       *pzTail = &zIn[1];
84109       dequoteString(zIn);
84110       return zIn;
84111     }
84112   }
84113   /*NOTREACHED*/
84114 }
84115
84116 /* Return true if...
84117 **
84118 **   *  s begins with the string t, ignoring case
84119 **   *  s is longer than t
84120 **   *  The first character of s beyond t is not a alphanumeric
84121 ** 
84122 ** Ignore leading space in *s.
84123 **
84124 ** To put it another way, return true if the first token of
84125 ** s[] is t[].
84126 */
84127 static int startsWith(const char *s, const char *t){
84128   while( safe_isspace(*s) ){ s++; }
84129   while( *t ){
84130     if( safe_tolower(*s++)!=safe_tolower(*t++) ) return 0;
84131   }
84132   return *s!='_' && !safe_isalnum(*s);
84133 }
84134
84135 /*
84136 ** An instance of this structure defines the "spec" of a
84137 ** full text index.  This structure is populated by parseSpec
84138 ** and use by fulltextConnect and fulltextCreate.
84139 */
84140 typedef struct TableSpec {
84141   const char *zDb;         /* Logical database name */
84142   const char *zName;       /* Name of the full-text index */
84143   int nColumn;             /* Number of columns to be indexed */
84144   char **azColumn;         /* Original names of columns to be indexed */
84145   char **azContentColumn;  /* Column names for %_content */
84146   char **azTokenizer;      /* Name of tokenizer and its arguments */
84147 } TableSpec;
84148
84149 /*
84150 ** Reclaim all of the memory used by a TableSpec
84151 */
84152 static void clearTableSpec(TableSpec *p) {
84153   sqlite3_free(p->azColumn);
84154   sqlite3_free(p->azContentColumn);
84155   sqlite3_free(p->azTokenizer);
84156 }
84157
84158 /* Parse a CREATE VIRTUAL TABLE statement, which looks like this:
84159  *
84160  * CREATE VIRTUAL TABLE email
84161  *        USING fts3(subject, body, tokenize mytokenizer(myarg))
84162  *
84163  * We return parsed information in a TableSpec structure.
84164  * 
84165  */
84166 static int parseSpec(TableSpec *pSpec, int argc, const char *const*argv,
84167                      char**pzErr){
84168   int i, n;
84169   char *z, *zDummy;
84170   char **azArg;
84171   const char *zTokenizer = 0;    /* argv[] entry describing the tokenizer */
84172
84173   assert( argc>=3 );
84174   /* Current interface:
84175   ** argv[0] - module name
84176   ** argv[1] - database name
84177   ** argv[2] - table name
84178   ** argv[3..] - columns, optionally followed by tokenizer specification
84179   **             and snippet delimiters specification.
84180   */
84181
84182   /* Make a copy of the complete argv[][] array in a single allocation.
84183   ** The argv[][] array is read-only and transient.  We can write to the
84184   ** copy in order to modify things and the copy is persistent.
84185   */
84186   CLEAR(pSpec);
84187   for(i=n=0; i<argc; i++){
84188     n += strlen(argv[i]) + 1;
84189   }
84190   azArg = sqlite3_malloc( sizeof(char*)*argc + n );
84191   if( azArg==0 ){
84192     return SQLITE_NOMEM;
84193   }
84194   z = (char*)&azArg[argc];
84195   for(i=0; i<argc; i++){
84196     azArg[i] = z;
84197     strcpy(z, argv[i]);
84198     z += strlen(z)+1;
84199   }
84200
84201   /* Identify the column names and the tokenizer and delimiter arguments
84202   ** in the argv[][] array.
84203   */
84204   pSpec->zDb = azArg[1];
84205   pSpec->zName = azArg[2];
84206   pSpec->nColumn = 0;
84207   pSpec->azColumn = azArg;
84208   zTokenizer = "tokenize simple";
84209   for(i=3; i<argc; ++i){
84210     if( startsWith(azArg[i],"tokenize") ){
84211       zTokenizer = azArg[i];
84212     }else{
84213       z = azArg[pSpec->nColumn] = firstToken(azArg[i], &zDummy);
84214       pSpec->nColumn++;
84215     }
84216   }
84217   if( pSpec->nColumn==0 ){
84218     azArg[0] = "content";
84219     pSpec->nColumn = 1;
84220   }
84221
84222   /*
84223   ** Construct the list of content column names.
84224   **
84225   ** Each content column name will be of the form cNNAAAA
84226   ** where NN is the column number and AAAA is the sanitized
84227   ** column name.  "sanitized" means that special characters are
84228   ** converted to "_".  The cNN prefix guarantees that all column
84229   ** names are unique.
84230   **
84231   ** The AAAA suffix is not strictly necessary.  It is included
84232   ** for the convenience of people who might examine the generated
84233   ** %_content table and wonder what the columns are used for.
84234   */
84235   pSpec->azContentColumn = sqlite3_malloc( pSpec->nColumn * sizeof(char *) );
84236   if( pSpec->azContentColumn==0 ){
84237     clearTableSpec(pSpec);
84238     return SQLITE_NOMEM;
84239   }
84240   for(i=0; i<pSpec->nColumn; i++){
84241     char *p;
84242     pSpec->azContentColumn[i] = sqlite3_mprintf("c%d%s", i, azArg[i]);
84243     for (p = pSpec->azContentColumn[i]; *p ; ++p) {
84244       if( !safe_isalnum(*p) ) *p = '_';
84245     }
84246   }
84247
84248   /*
84249   ** Parse the tokenizer specification string.
84250   */
84251   pSpec->azTokenizer = tokenizeString(zTokenizer, &n);
84252   tokenListToIdList(pSpec->azTokenizer);
84253
84254   return SQLITE_OK;
84255 }
84256
84257 /*
84258 ** Generate a CREATE TABLE statement that describes the schema of
84259 ** the virtual table.  Return a pointer to this schema string.
84260 **
84261 ** Space is obtained from sqlite3_mprintf() and should be freed
84262 ** using sqlite3_free().
84263 */
84264 static char *fulltextSchema(
84265   int nColumn,                  /* Number of columns */
84266   const char *const* azColumn,  /* List of columns */
84267   const char *zTableName        /* Name of the table */
84268 ){
84269   int i;
84270   char *zSchema, *zNext;
84271   const char *zSep = "(";
84272   zSchema = sqlite3_mprintf("CREATE TABLE x");
84273   for(i=0; i<nColumn; i++){
84274     zNext = sqlite3_mprintf("%s%s%Q", zSchema, zSep, azColumn[i]);
84275     sqlite3_free(zSchema);
84276     zSchema = zNext;
84277     zSep = ",";
84278   }
84279   zNext = sqlite3_mprintf("%s,%Q HIDDEN", zSchema, zTableName);
84280   sqlite3_free(zSchema);
84281   zSchema = zNext;
84282   zNext = sqlite3_mprintf("%s,docid HIDDEN)", zSchema);
84283   sqlite3_free(zSchema);
84284   return zNext;
84285 }
84286
84287 /*
84288 ** Build a new sqlite3_vtab structure that will describe the
84289 ** fulltext index defined by spec.
84290 */
84291 static int constructVtab(
84292   sqlite3 *db,              /* The SQLite database connection */
84293   fts3Hash *pHash,          /* Hash table containing tokenizers */
84294   TableSpec *spec,          /* Parsed spec information from parseSpec() */
84295   sqlite3_vtab **ppVTab,    /* Write the resulting vtab structure here */
84296   char **pzErr              /* Write any error message here */
84297 ){
84298   int rc;
84299   int n;
84300   fulltext_vtab *v = 0;
84301   const sqlite3_tokenizer_module *m = NULL;
84302   char *schema;
84303
84304   char const *zTok;         /* Name of tokenizer to use for this fts table */
84305   int nTok;                 /* Length of zTok, including nul terminator */
84306
84307   v = (fulltext_vtab *) sqlite3_malloc(sizeof(fulltext_vtab));
84308   if( v==0 ) return SQLITE_NOMEM;
84309   CLEAR(v);
84310   /* sqlite will initialize v->base */
84311   v->db = db;
84312   v->zDb = spec->zDb;       /* Freed when azColumn is freed */
84313   v->zName = spec->zName;   /* Freed when azColumn is freed */
84314   v->nColumn = spec->nColumn;
84315   v->azContentColumn = spec->azContentColumn;
84316   spec->azContentColumn = 0;
84317   v->azColumn = spec->azColumn;
84318   spec->azColumn = 0;
84319
84320   if( spec->azTokenizer==0 ){
84321     return SQLITE_NOMEM;
84322   }
84323
84324   zTok = spec->azTokenizer[0]; 
84325   if( !zTok ){
84326     zTok = "simple";
84327   }
84328   nTok = strlen(zTok)+1;
84329
84330   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zTok, nTok);
84331   if( !m ){
84332     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", spec->azTokenizer[0]);
84333     rc = SQLITE_ERROR;
84334     goto err;
84335   }
84336
84337   for(n=0; spec->azTokenizer[n]; n++){}
84338   if( n ){
84339     rc = m->xCreate(n-1, (const char*const*)&spec->azTokenizer[1],
84340                     &v->pTokenizer);
84341   }else{
84342     rc = m->xCreate(0, 0, &v->pTokenizer);
84343   }
84344   if( rc!=SQLITE_OK ) goto err;
84345   v->pTokenizer->pModule = m;
84346
84347   /* TODO: verify the existence of backing tables foo_content, foo_term */
84348
84349   schema = fulltextSchema(v->nColumn, (const char*const*)v->azColumn,
84350                           spec->zName);
84351   rc = sqlite3_declare_vtab(db, schema);
84352   sqlite3_free(schema);
84353   if( rc!=SQLITE_OK ) goto err;
84354
84355   memset(v->pFulltextStatements, 0, sizeof(v->pFulltextStatements));
84356
84357   /* Indicate that the buffer is not live. */
84358   v->nPendingData = -1;
84359
84360   *ppVTab = &v->base;
84361   FTSTRACE(("FTS3 Connect %p\n", v));
84362
84363   return rc;
84364
84365 err:
84366   fulltext_vtab_destroy(v);
84367   return rc;
84368 }
84369
84370 static int fulltextConnect(
84371   sqlite3 *db,
84372   void *pAux,
84373   int argc, const char *const*argv,
84374   sqlite3_vtab **ppVTab,
84375   char **pzErr
84376 ){
84377   TableSpec spec;
84378   int rc = parseSpec(&spec, argc, argv, pzErr);
84379   if( rc!=SQLITE_OK ) return rc;
84380
84381   rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
84382   clearTableSpec(&spec);
84383   return rc;
84384 }
84385
84386 /* The %_content table holds the text of each document, with
84387 ** the docid column exposed as the SQLite rowid for the table.
84388 */
84389 /* TODO(shess) This comment needs elaboration to match the updated
84390 ** code.  Work it into the top-of-file comment at that time.
84391 */
84392 static int fulltextCreate(sqlite3 *db, void *pAux,
84393                           int argc, const char * const *argv,
84394                           sqlite3_vtab **ppVTab, char **pzErr){
84395   int rc;
84396   TableSpec spec;
84397   StringBuffer schema;
84398   FTSTRACE(("FTS3 Create\n"));
84399
84400   rc = parseSpec(&spec, argc, argv, pzErr);
84401   if( rc!=SQLITE_OK ) return rc;
84402
84403   initStringBuffer(&schema);
84404   append(&schema, "CREATE TABLE %_content(");
84405   append(&schema, "  docid INTEGER PRIMARY KEY,");
84406   appendList(&schema, spec.nColumn, spec.azContentColumn);
84407   append(&schema, ")");
84408   rc = sql_exec(db, spec.zDb, spec.zName, stringBufferData(&schema));
84409   stringBufferDestroy(&schema);
84410   if( rc!=SQLITE_OK ) goto out;
84411
84412   rc = sql_exec(db, spec.zDb, spec.zName,
84413                 "create table %_segments("
84414                 "  blockid INTEGER PRIMARY KEY,"
84415                 "  block blob"
84416                 ");"
84417                 );
84418   if( rc!=SQLITE_OK ) goto out;
84419
84420   rc = sql_exec(db, spec.zDb, spec.zName,
84421                 "create table %_segdir("
84422                 "  level integer,"
84423                 "  idx integer,"
84424                 "  start_block integer,"
84425                 "  leaves_end_block integer,"
84426                 "  end_block integer,"
84427                 "  root blob,"
84428                 "  primary key(level, idx)"
84429                 ");");
84430   if( rc!=SQLITE_OK ) goto out;
84431
84432   rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
84433
84434 out:
84435   clearTableSpec(&spec);
84436   return rc;
84437 }
84438
84439 /* Decide how to handle an SQL query. */
84440 static int fulltextBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
84441   fulltext_vtab *v = (fulltext_vtab *)pVTab;
84442   int i;
84443   FTSTRACE(("FTS3 BestIndex\n"));
84444
84445   for(i=0; i<pInfo->nConstraint; ++i){
84446     const struct sqlite3_index_constraint *pConstraint;
84447     pConstraint = &pInfo->aConstraint[i];
84448     if( pConstraint->usable ) {
84449       if( (pConstraint->iColumn==-1 || pConstraint->iColumn==v->nColumn+1) &&
84450           pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
84451         pInfo->idxNum = QUERY_DOCID;      /* lookup by docid */
84452         FTSTRACE(("FTS3 QUERY_DOCID\n"));
84453       } else if( pConstraint->iColumn>=0 && pConstraint->iColumn<=v->nColumn &&
84454                  pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
84455         /* full-text search */
84456         pInfo->idxNum = QUERY_FULLTEXT + pConstraint->iColumn;
84457         FTSTRACE(("FTS3 QUERY_FULLTEXT %d\n", pConstraint->iColumn));
84458       } else continue;
84459
84460       pInfo->aConstraintUsage[i].argvIndex = 1;
84461       pInfo->aConstraintUsage[i].omit = 1;
84462
84463       /* An arbitrary value for now.
84464        * TODO: Perhaps docid matches should be considered cheaper than
84465        * full-text searches. */
84466       pInfo->estimatedCost = 1.0;   
84467
84468       return SQLITE_OK;
84469     }
84470   }
84471   pInfo->idxNum = QUERY_GENERIC;
84472   return SQLITE_OK;
84473 }
84474
84475 static int fulltextDisconnect(sqlite3_vtab *pVTab){
84476   FTSTRACE(("FTS3 Disconnect %p\n", pVTab));
84477   fulltext_vtab_destroy((fulltext_vtab *)pVTab);
84478   return SQLITE_OK;
84479 }
84480
84481 static int fulltextDestroy(sqlite3_vtab *pVTab){
84482   fulltext_vtab *v = (fulltext_vtab *)pVTab;
84483   int rc;
84484
84485   FTSTRACE(("FTS3 Destroy %p\n", pVTab));
84486   rc = sql_exec(v->db, v->zDb, v->zName,
84487                 "drop table if exists %_content;"
84488                 "drop table if exists %_segments;"
84489                 "drop table if exists %_segdir;"
84490                 );
84491   if( rc!=SQLITE_OK ) return rc;
84492
84493   fulltext_vtab_destroy((fulltext_vtab *)pVTab);
84494   return SQLITE_OK;
84495 }
84496
84497 static int fulltextOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
84498   fulltext_cursor *c;
84499
84500   c = (fulltext_cursor *) sqlite3_malloc(sizeof(fulltext_cursor));
84501   if( c ){
84502     memset(c, 0, sizeof(fulltext_cursor));
84503     /* sqlite will initialize c->base */
84504     *ppCursor = &c->base;
84505     FTSTRACE(("FTS3 Open %p: %p\n", pVTab, c));
84506     return SQLITE_OK;
84507   }else{
84508     return SQLITE_NOMEM;
84509   }
84510 }
84511
84512
84513 /* Free all of the dynamically allocated memory held by *q
84514 */
84515 static void queryClear(Query *q){
84516   int i;
84517   for(i = 0; i < q->nTerms; ++i){
84518     sqlite3_free(q->pTerms[i].pTerm);
84519   }
84520   sqlite3_free(q->pTerms);
84521   CLEAR(q);
84522 }
84523
84524 /* Free all of the dynamically allocated memory held by the
84525 ** Snippet
84526 */
84527 static void snippetClear(Snippet *p){
84528   sqlite3_free(p->aMatch);
84529   sqlite3_free(p->zOffset);
84530   sqlite3_free(p->zSnippet);
84531   CLEAR(p);
84532 }
84533 /*
84534 ** Append a single entry to the p->aMatch[] log.
84535 */
84536 static void snippetAppendMatch(
84537   Snippet *p,               /* Append the entry to this snippet */
84538   int iCol, int iTerm,      /* The column and query term */
84539   int iToken,               /* Matching token in document */
84540   int iStart, int nByte     /* Offset and size of the match */
84541 ){
84542   int i;
84543   struct snippetMatch *pMatch;
84544   if( p->nMatch+1>=p->nAlloc ){
84545     p->nAlloc = p->nAlloc*2 + 10;
84546     p->aMatch = sqlite3_realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) );
84547     if( p->aMatch==0 ){
84548       p->nMatch = 0;
84549       p->nAlloc = 0;
84550       return;
84551     }
84552   }
84553   i = p->nMatch++;
84554   pMatch = &p->aMatch[i];
84555   pMatch->iCol = iCol;
84556   pMatch->iTerm = iTerm;
84557   pMatch->iToken = iToken;
84558   pMatch->iStart = iStart;
84559   pMatch->nByte = nByte;
84560 }
84561
84562 /*
84563 ** Sizing information for the circular buffer used in snippetOffsetsOfColumn()
84564 */
84565 #define FTS3_ROTOR_SZ   (32)
84566 #define FTS3_ROTOR_MASK (FTS3_ROTOR_SZ-1)
84567
84568 /*
84569 ** Add entries to pSnippet->aMatch[] for every match that occurs against
84570 ** document zDoc[0..nDoc-1] which is stored in column iColumn.
84571 */
84572 static void snippetOffsetsOfColumn(
84573   Query *pQuery,
84574   Snippet *pSnippet,
84575   int iColumn,
84576   const char *zDoc,
84577   int nDoc
84578 ){
84579   const sqlite3_tokenizer_module *pTModule;  /* The tokenizer module */
84580   sqlite3_tokenizer *pTokenizer;             /* The specific tokenizer */
84581   sqlite3_tokenizer_cursor *pTCursor;        /* Tokenizer cursor */
84582   fulltext_vtab *pVtab;                /* The full text index */
84583   int nColumn;                         /* Number of columns in the index */
84584   const QueryTerm *aTerm;              /* Query string terms */
84585   int nTerm;                           /* Number of query string terms */  
84586   int i, j;                            /* Loop counters */
84587   int rc;                              /* Return code */
84588   unsigned int match, prevMatch;       /* Phrase search bitmasks */
84589   const char *zToken;                  /* Next token from the tokenizer */
84590   int nToken;                          /* Size of zToken */
84591   int iBegin, iEnd, iPos;              /* Offsets of beginning and end */
84592
84593   /* The following variables keep a circular buffer of the last
84594   ** few tokens */
84595   unsigned int iRotor = 0;             /* Index of current token */
84596   int iRotorBegin[FTS3_ROTOR_SZ];      /* Beginning offset of token */
84597   int iRotorLen[FTS3_ROTOR_SZ];        /* Length of token */
84598
84599   pVtab = pQuery->pFts;
84600   nColumn = pVtab->nColumn;
84601   pTokenizer = pVtab->pTokenizer;
84602   pTModule = pTokenizer->pModule;
84603   rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor);
84604   if( rc ) return;
84605   pTCursor->pTokenizer = pTokenizer;
84606   aTerm = pQuery->pTerms;
84607   nTerm = pQuery->nTerms;
84608   if( nTerm>=FTS3_ROTOR_SZ ){
84609     nTerm = FTS3_ROTOR_SZ - 1;
84610   }
84611   prevMatch = 0;
84612   while(1){
84613     rc = pTModule->xNext(pTCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
84614     if( rc ) break;
84615     iRotorBegin[iRotor&FTS3_ROTOR_MASK] = iBegin;
84616     iRotorLen[iRotor&FTS3_ROTOR_MASK] = iEnd-iBegin;
84617     match = 0;
84618     for(i=0; i<nTerm; i++){
84619       int iCol;
84620       iCol = aTerm[i].iColumn;
84621       if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue;
84622       if( aTerm[i].nTerm>nToken ) continue;
84623       if( !aTerm[i].isPrefix && aTerm[i].nTerm<nToken ) continue;
84624       assert( aTerm[i].nTerm<=nToken );
84625       if( memcmp(aTerm[i].pTerm, zToken, aTerm[i].nTerm) ) continue;
84626       if( aTerm[i].iPhrase>1 && (prevMatch & (1<<i))==0 ) continue;
84627       match |= 1<<i;
84628       if( i==nTerm-1 || aTerm[i+1].iPhrase==1 ){
84629         for(j=aTerm[i].iPhrase-1; j>=0; j--){
84630           int k = (iRotor-j) & FTS3_ROTOR_MASK;
84631           snippetAppendMatch(pSnippet, iColumn, i-j, iPos-j,
84632                 iRotorBegin[k], iRotorLen[k]);
84633         }
84634       }
84635     }
84636     prevMatch = match<<1;
84637     iRotor++;
84638   }
84639   pTModule->xClose(pTCursor);  
84640 }
84641
84642 /*
84643 ** Remove entries from the pSnippet structure to account for the NEAR
84644 ** operator. When this is called, pSnippet contains the list of token 
84645 ** offsets produced by treating all NEAR operators as AND operators.
84646 ** This function removes any entries that should not be present after
84647 ** accounting for the NEAR restriction. For example, if the queried
84648 ** document is:
84649 **
84650 **     "A B C D E A"
84651 **
84652 ** and the query is:
84653 ** 
84654 **     A NEAR/0 E
84655 **
84656 ** then when this function is called the Snippet contains token offsets
84657 ** 0, 4 and 5. This function removes the "0" entry (because the first A
84658 ** is not near enough to an E).
84659 */
84660 static void trimSnippetOffsetsForNear(Query *pQuery, Snippet *pSnippet){
84661   int ii;
84662   int iDir = 1;
84663
84664   while(iDir>-2) {
84665     assert( iDir==1 || iDir==-1 );
84666     for(ii=0; ii<pSnippet->nMatch; ii++){
84667       int jj;
84668       int nNear;
84669       struct snippetMatch *pMatch = &pSnippet->aMatch[ii];
84670       QueryTerm *pQueryTerm = &pQuery->pTerms[pMatch->iTerm];
84671
84672       if( (pMatch->iTerm+iDir)<0 
84673        || (pMatch->iTerm+iDir)>=pQuery->nTerms
84674       ){
84675         continue;
84676       }
84677      
84678       nNear = pQueryTerm->nNear;
84679       if( iDir<0 ){
84680         nNear = pQueryTerm[-1].nNear;
84681       }
84682   
84683       if( pMatch->iTerm>=0 && nNear ){
84684         int isOk = 0;
84685         int iNextTerm = pMatch->iTerm+iDir;
84686         int iPrevTerm = iNextTerm;
84687
84688         int iEndToken;
84689         int iStartToken;
84690
84691         if( iDir<0 ){
84692           int nPhrase = 1;
84693           iStartToken = pMatch->iToken;
84694           while( (pMatch->iTerm+nPhrase)<pQuery->nTerms 
84695               && pQuery->pTerms[pMatch->iTerm+nPhrase].iPhrase>1 
84696           ){
84697             nPhrase++;
84698           }
84699           iEndToken = iStartToken + nPhrase - 1;
84700         }else{
84701           iEndToken   = pMatch->iToken;
84702           iStartToken = pMatch->iToken+1-pQueryTerm->iPhrase;
84703         }
84704
84705         while( pQuery->pTerms[iNextTerm].iPhrase>1 ){
84706           iNextTerm--;
84707         }
84708         while( (iPrevTerm+1)<pQuery->nTerms && 
84709                pQuery->pTerms[iPrevTerm+1].iPhrase>1 
84710         ){
84711           iPrevTerm++;
84712         }
84713   
84714         for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
84715           struct snippetMatch *p = &pSnippet->aMatch[jj];
84716           if( p->iCol==pMatch->iCol && ((
84717                p->iTerm==iNextTerm && 
84718                p->iToken>iEndToken && 
84719                p->iToken<=iEndToken+nNear
84720           ) || (
84721                p->iTerm==iPrevTerm && 
84722                p->iToken<iStartToken && 
84723                p->iToken>=iStartToken-nNear
84724           ))){
84725             isOk = 1;
84726           }
84727         }
84728         if( !isOk ){
84729           for(jj=1-pQueryTerm->iPhrase; jj<=0; jj++){
84730             pMatch[jj].iTerm = -1;
84731           }
84732           ii = -1;
84733           iDir = 1;
84734         }
84735       }
84736     }
84737     iDir -= 2;
84738   }
84739 }
84740
84741 /*
84742 ** Compute all offsets for the current row of the query.  
84743 ** If the offsets have already been computed, this routine is a no-op.
84744 */
84745 static void snippetAllOffsets(fulltext_cursor *p){
84746   int nColumn;
84747   int iColumn, i;
84748   int iFirst, iLast;
84749   fulltext_vtab *pFts;
84750
84751   if( p->snippet.nMatch ) return;
84752   if( p->q.nTerms==0 ) return;
84753   pFts = p->q.pFts;
84754   nColumn = pFts->nColumn;
84755   iColumn = (p->iCursorType - QUERY_FULLTEXT);
84756   if( iColumn<0 || iColumn>=nColumn ){
84757     iFirst = 0;
84758     iLast = nColumn-1;
84759   }else{
84760     iFirst = iColumn;
84761     iLast = iColumn;
84762   }
84763   for(i=iFirst; i<=iLast; i++){
84764     const char *zDoc;
84765     int nDoc;
84766     zDoc = (const char*)sqlite3_column_text(p->pStmt, i+1);
84767     nDoc = sqlite3_column_bytes(p->pStmt, i+1);
84768     snippetOffsetsOfColumn(&p->q, &p->snippet, i, zDoc, nDoc);
84769   }
84770
84771   trimSnippetOffsetsForNear(&p->q, &p->snippet);
84772 }
84773
84774 /*
84775 ** Convert the information in the aMatch[] array of the snippet
84776 ** into the string zOffset[0..nOffset-1].
84777 */
84778 static void snippetOffsetText(Snippet *p){
84779   int i;
84780   int cnt = 0;
84781   StringBuffer sb;
84782   char zBuf[200];
84783   if( p->zOffset ) return;
84784   initStringBuffer(&sb);
84785   for(i=0; i<p->nMatch; i++){
84786     struct snippetMatch *pMatch = &p->aMatch[i];
84787     if( pMatch->iTerm>=0 ){
84788       /* If snippetMatch.iTerm is less than 0, then the match was 
84789       ** discarded as part of processing the NEAR operator (see the 
84790       ** trimSnippetOffsetsForNear() function for details). Ignore 
84791       ** it in this case
84792       */
84793       zBuf[0] = ' ';
84794       sprintf(&zBuf[cnt>0], "%d %d %d %d", pMatch->iCol,
84795           pMatch->iTerm, pMatch->iStart, pMatch->nByte);
84796       append(&sb, zBuf);
84797       cnt++;
84798     }
84799   }
84800   p->zOffset = stringBufferData(&sb);
84801   p->nOffset = stringBufferLength(&sb);
84802 }
84803
84804 /*
84805 ** zDoc[0..nDoc-1] is phrase of text.  aMatch[0..nMatch-1] are a set
84806 ** of matching words some of which might be in zDoc.  zDoc is column
84807 ** number iCol.
84808 **
84809 ** iBreak is suggested spot in zDoc where we could begin or end an
84810 ** excerpt.  Return a value similar to iBreak but possibly adjusted
84811 ** to be a little left or right so that the break point is better.
84812 */
84813 static int wordBoundary(
84814   int iBreak,                   /* The suggested break point */
84815   const char *zDoc,             /* Document text */
84816   int nDoc,                     /* Number of bytes in zDoc[] */
84817   struct snippetMatch *aMatch,  /* Matching words */
84818   int nMatch,                   /* Number of entries in aMatch[] */
84819   int iCol                      /* The column number for zDoc[] */
84820 ){
84821   int i;
84822   if( iBreak<=10 ){
84823     return 0;
84824   }
84825   if( iBreak>=nDoc-10 ){
84826     return nDoc;
84827   }
84828   for(i=0; i<nMatch && aMatch[i].iCol<iCol; i++){}
84829   while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; }
84830   if( i<nMatch ){
84831     if( aMatch[i].iStart<iBreak+10 ){
84832       return aMatch[i].iStart;
84833     }
84834     if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){
84835       return aMatch[i-1].iStart;
84836     }
84837   }
84838   for(i=1; i<=10; i++){
84839     if( safe_isspace(zDoc[iBreak-i]) ){
84840       return iBreak - i + 1;
84841     }
84842     if( safe_isspace(zDoc[iBreak+i]) ){
84843       return iBreak + i + 1;
84844     }
84845   }
84846   return iBreak;
84847 }
84848
84849
84850
84851 /*
84852 ** Allowed values for Snippet.aMatch[].snStatus
84853 */
84854 #define SNIPPET_IGNORE  0   /* It is ok to omit this match from the snippet */
84855 #define SNIPPET_DESIRED 1   /* We want to include this match in the snippet */
84856
84857 /*
84858 ** Generate the text of a snippet.
84859 */
84860 static void snippetText(
84861   fulltext_cursor *pCursor,   /* The cursor we need the snippet for */
84862   const char *zStartMark,     /* Markup to appear before each match */
84863   const char *zEndMark,       /* Markup to appear after each match */
84864   const char *zEllipsis       /* Ellipsis mark */
84865 ){
84866   int i, j;
84867   struct snippetMatch *aMatch;
84868   int nMatch;
84869   int nDesired;
84870   StringBuffer sb;
84871   int tailCol;
84872   int tailOffset;
84873   int iCol;
84874   int nDoc;
84875   const char *zDoc;
84876   int iStart, iEnd;
84877   int tailEllipsis = 0;
84878   int iMatch;
84879   
84880
84881   sqlite3_free(pCursor->snippet.zSnippet);
84882   pCursor->snippet.zSnippet = 0;
84883   aMatch = pCursor->snippet.aMatch;
84884   nMatch = pCursor->snippet.nMatch;
84885   initStringBuffer(&sb);
84886
84887   for(i=0; i<nMatch; i++){
84888     aMatch[i].snStatus = SNIPPET_IGNORE;
84889   }
84890   nDesired = 0;
84891   for(i=0; i<pCursor->q.nTerms; i++){
84892     for(j=0; j<nMatch; j++){
84893       if( aMatch[j].iTerm==i ){
84894         aMatch[j].snStatus = SNIPPET_DESIRED;
84895         nDesired++;
84896         break;
84897       }
84898     }
84899   }
84900
84901   iMatch = 0;
84902   tailCol = -1;
84903   tailOffset = 0;
84904   for(i=0; i<nMatch && nDesired>0; i++){
84905     if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue;
84906     nDesired--;
84907     iCol = aMatch[i].iCol;
84908     zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1);
84909     nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1);
84910     iStart = aMatch[i].iStart - 40;
84911     iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol);
84912     if( iStart<=10 ){
84913       iStart = 0;
84914     }
84915     if( iCol==tailCol && iStart<=tailOffset+20 ){
84916       iStart = tailOffset;
84917     }
84918     if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){
84919       trimWhiteSpace(&sb);
84920       appendWhiteSpace(&sb);
84921       append(&sb, zEllipsis);
84922       appendWhiteSpace(&sb);
84923     }
84924     iEnd = aMatch[i].iStart + aMatch[i].nByte + 40;
84925     iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol);
84926     if( iEnd>=nDoc-10 ){
84927       iEnd = nDoc;
84928       tailEllipsis = 0;
84929     }else{
84930       tailEllipsis = 1;
84931     }
84932     while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; }
84933     while( iStart<iEnd ){
84934       while( iMatch<nMatch && aMatch[iMatch].iStart<iStart
84935              && aMatch[iMatch].iCol<=iCol ){
84936         iMatch++;
84937       }
84938       if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd
84939              && aMatch[iMatch].iCol==iCol ){
84940         nappend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart);
84941         iStart = aMatch[iMatch].iStart;
84942         append(&sb, zStartMark);
84943         nappend(&sb, &zDoc[iStart], aMatch[iMatch].nByte);
84944         append(&sb, zEndMark);
84945         iStart += aMatch[iMatch].nByte;
84946         for(j=iMatch+1; j<nMatch; j++){
84947           if( aMatch[j].iTerm==aMatch[iMatch].iTerm
84948               && aMatch[j].snStatus==SNIPPET_DESIRED ){
84949             nDesired--;
84950             aMatch[j].snStatus = SNIPPET_IGNORE;
84951           }
84952         }
84953       }else{
84954         nappend(&sb, &zDoc[iStart], iEnd - iStart);
84955         iStart = iEnd;
84956       }
84957     }
84958     tailCol = iCol;
84959     tailOffset = iEnd;
84960   }
84961   trimWhiteSpace(&sb);
84962   if( tailEllipsis ){
84963     appendWhiteSpace(&sb);
84964     append(&sb, zEllipsis);
84965   }
84966   pCursor->snippet.zSnippet = stringBufferData(&sb);
84967   pCursor->snippet.nSnippet = stringBufferLength(&sb);
84968 }
84969
84970
84971 /*
84972 ** Close the cursor.  For additional information see the documentation
84973 ** on the xClose method of the virtual table interface.
84974 */
84975 static int fulltextClose(sqlite3_vtab_cursor *pCursor){
84976   fulltext_cursor *c = (fulltext_cursor *) pCursor;
84977   FTSTRACE(("FTS3 Close %p\n", c));
84978   sqlite3_finalize(c->pStmt);
84979   queryClear(&c->q);
84980   snippetClear(&c->snippet);
84981   if( c->result.nData!=0 ) dlrDestroy(&c->reader);
84982   dataBufferDestroy(&c->result);
84983   sqlite3_free(c);
84984   return SQLITE_OK;
84985 }
84986
84987 static int fulltextNext(sqlite3_vtab_cursor *pCursor){
84988   fulltext_cursor *c = (fulltext_cursor *) pCursor;
84989   int rc;
84990
84991   FTSTRACE(("FTS3 Next %p\n", pCursor));
84992   snippetClear(&c->snippet);
84993   if( c->iCursorType < QUERY_FULLTEXT ){
84994     /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
84995     rc = sqlite3_step(c->pStmt);
84996     switch( rc ){
84997       case SQLITE_ROW:
84998         c->eof = 0;
84999         return SQLITE_OK;
85000       case SQLITE_DONE:
85001         c->eof = 1;
85002         return SQLITE_OK;
85003       default:
85004         c->eof = 1;
85005         return rc;
85006     }
85007   } else {  /* full-text query */
85008     rc = sqlite3_reset(c->pStmt);
85009     if( rc!=SQLITE_OK ) return rc;
85010
85011     if( c->result.nData==0 || dlrAtEnd(&c->reader) ){
85012       c->eof = 1;
85013       return SQLITE_OK;
85014     }
85015     rc = sqlite3_bind_int64(c->pStmt, 1, dlrDocid(&c->reader));
85016     dlrStep(&c->reader);
85017     if( rc!=SQLITE_OK ) return rc;
85018     /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
85019     rc = sqlite3_step(c->pStmt);
85020     if( rc==SQLITE_ROW ){   /* the case we expect */
85021       c->eof = 0;
85022       return SQLITE_OK;
85023     }
85024     /* an error occurred; abort */
85025     return rc==SQLITE_DONE ? SQLITE_ERROR : rc;
85026   }
85027 }
85028
85029
85030 /* TODO(shess) If we pushed LeafReader to the top of the file, or to
85031 ** another file, term_select() could be pushed above
85032 ** docListOfTerm().
85033 */
85034 static int termSelect(fulltext_vtab *v, int iColumn,
85035                       const char *pTerm, int nTerm, int isPrefix,
85036                       DocListType iType, DataBuffer *out);
85037
85038 /* Return a DocList corresponding to the query term *pTerm.  If *pTerm
85039 ** is the first term of a phrase query, go ahead and evaluate the phrase
85040 ** query and return the doclist for the entire phrase query.
85041 **
85042 ** The resulting DL_DOCIDS doclist is stored in pResult, which is
85043 ** overwritten.
85044 */
85045 static int docListOfTerm(
85046   fulltext_vtab *v,    /* The full text index */
85047   int iColumn,         /* column to restrict to.  No restriction if >=nColumn */
85048   QueryTerm *pQTerm,   /* Term we are looking for, or 1st term of a phrase */
85049   DataBuffer *pResult  /* Write the result here */
85050 ){
85051   DataBuffer left, right, new;
85052   int i, rc;
85053
85054   /* No phrase search if no position info. */
85055   assert( pQTerm->nPhrase==0 || DL_DEFAULT!=DL_DOCIDS );
85056
85057   /* This code should never be called with buffered updates. */
85058   assert( v->nPendingData<0 );
85059
85060   dataBufferInit(&left, 0);
85061   rc = termSelect(v, iColumn, pQTerm->pTerm, pQTerm->nTerm, pQTerm->isPrefix,
85062                   (0<pQTerm->nPhrase ? DL_POSITIONS : DL_DOCIDS), &left);
85063   if( rc ) return rc;
85064   for(i=1; i<=pQTerm->nPhrase && left.nData>0; i++){
85065     /* If this token is connected to the next by a NEAR operator, and
85066     ** the next token is the start of a phrase, then set nPhraseRight
85067     ** to the number of tokens in the phrase. Otherwise leave it at 1.
85068     */
85069     int nPhraseRight = 1;
85070     while( (i+nPhraseRight)<=pQTerm->nPhrase 
85071         && pQTerm[i+nPhraseRight].nNear==0 
85072     ){
85073       nPhraseRight++;
85074     }
85075
85076     dataBufferInit(&right, 0);
85077     rc = termSelect(v, iColumn, pQTerm[i].pTerm, pQTerm[i].nTerm,
85078                     pQTerm[i].isPrefix, DL_POSITIONS, &right);
85079     if( rc ){
85080       dataBufferDestroy(&left);
85081       return rc;
85082     }
85083     dataBufferInit(&new, 0);
85084     docListPhraseMerge(left.pData, left.nData, right.pData, right.nData,
85085                        pQTerm[i-1].nNear, pQTerm[i-1].iPhrase + nPhraseRight,
85086                        ((i<pQTerm->nPhrase) ? DL_POSITIONS : DL_DOCIDS),
85087                        &new);
85088     dataBufferDestroy(&left);
85089     dataBufferDestroy(&right);
85090     left = new;
85091   }
85092   *pResult = left;
85093   return SQLITE_OK;
85094 }
85095
85096 /* Add a new term pTerm[0..nTerm-1] to the query *q.
85097 */
85098 static void queryAdd(Query *q, const char *pTerm, int nTerm){
85099   QueryTerm *t;
85100   ++q->nTerms;
85101   q->pTerms = sqlite3_realloc(q->pTerms, q->nTerms * sizeof(q->pTerms[0]));
85102   if( q->pTerms==0 ){
85103     q->nTerms = 0;
85104     return;
85105   }
85106   t = &q->pTerms[q->nTerms - 1];
85107   CLEAR(t);
85108   t->pTerm = sqlite3_malloc(nTerm+1);
85109   memcpy(t->pTerm, pTerm, nTerm);
85110   t->pTerm[nTerm] = 0;
85111   t->nTerm = nTerm;
85112   t->isOr = q->nextIsOr;
85113   t->isPrefix = 0;
85114   q->nextIsOr = 0;
85115   t->iColumn = q->nextColumn;
85116   q->nextColumn = q->dfltColumn;
85117 }
85118
85119 /*
85120 ** Check to see if the string zToken[0...nToken-1] matches any
85121 ** column name in the virtual table.   If it does,
85122 ** return the zero-indexed column number.  If not, return -1.
85123 */
85124 static int checkColumnSpecifier(
85125   fulltext_vtab *pVtab,    /* The virtual table */
85126   const char *zToken,      /* Text of the token */
85127   int nToken               /* Number of characters in the token */
85128 ){
85129   int i;
85130   for(i=0; i<pVtab->nColumn; i++){
85131     if( memcmp(pVtab->azColumn[i], zToken, nToken)==0
85132         && pVtab->azColumn[i][nToken]==0 ){
85133       return i;
85134     }
85135   }
85136   return -1;
85137 }
85138
85139 /*
85140 ** Parse the text at pSegment[0..nSegment-1].  Add additional terms
85141 ** to the query being assemblied in pQuery.
85142 **
85143 ** inPhrase is true if pSegment[0..nSegement-1] is contained within
85144 ** double-quotes.  If inPhrase is true, then the first term
85145 ** is marked with the number of terms in the phrase less one and
85146 ** OR and "-" syntax is ignored.  If inPhrase is false, then every
85147 ** term found is marked with nPhrase=0 and OR and "-" syntax is significant.
85148 */
85149 static int tokenizeSegment(
85150   sqlite3_tokenizer *pTokenizer,          /* The tokenizer to use */
85151   const char *pSegment, int nSegment,     /* Query expression being parsed */
85152   int inPhrase,                           /* True if within "..." */
85153   Query *pQuery                           /* Append results here */
85154 ){
85155   const sqlite3_tokenizer_module *pModule = pTokenizer->pModule;
85156   sqlite3_tokenizer_cursor *pCursor;
85157   int firstIndex = pQuery->nTerms;
85158   int iCol;
85159   int nTerm = 1;
85160   
85161   int rc = pModule->xOpen(pTokenizer, pSegment, nSegment, &pCursor);
85162   if( rc!=SQLITE_OK ) return rc;
85163   pCursor->pTokenizer = pTokenizer;
85164
85165   while( 1 ){
85166     const char *pToken;
85167     int nToken, iBegin, iEnd, iPos;
85168
85169     rc = pModule->xNext(pCursor,
85170                         &pToken, &nToken,
85171                         &iBegin, &iEnd, &iPos);
85172     if( rc!=SQLITE_OK ) break;
85173     if( !inPhrase &&
85174         pSegment[iEnd]==':' &&
85175          (iCol = checkColumnSpecifier(pQuery->pFts, pToken, nToken))>=0 ){
85176       pQuery->nextColumn = iCol;
85177       continue;
85178     }
85179     if( !inPhrase && pQuery->nTerms>0 && nToken==2 
85180      && pSegment[iBegin+0]=='O'
85181      && pSegment[iBegin+1]=='R' 
85182     ){
85183       pQuery->nextIsOr = 1;
85184       continue;
85185     }
85186     if( !inPhrase && pQuery->nTerms>0 && !pQuery->nextIsOr && nToken==4 
85187       && pSegment[iBegin+0]=='N' 
85188       && pSegment[iBegin+1]=='E' 
85189       && pSegment[iBegin+2]=='A' 
85190       && pSegment[iBegin+3]=='R' 
85191     ){
85192       QueryTerm *pTerm = &pQuery->pTerms[pQuery->nTerms-1];
85193       if( (iBegin+6)<nSegment 
85194        && pSegment[iBegin+4] == '/'
85195        && pSegment[iBegin+5]>='0' && pSegment[iBegin+5]<='9'
85196       ){
85197         pTerm->nNear = (pSegment[iBegin+5] - '0');
85198         nToken += 2;
85199         if( pSegment[iBegin+6]>='0' && pSegment[iBegin+6]<=9 ){
85200           pTerm->nNear = pTerm->nNear * 10 + (pSegment[iBegin+6] - '0');
85201           iEnd++;
85202         }
85203         pModule->xNext(pCursor, &pToken, &nToken, &iBegin, &iEnd, &iPos);
85204       } else {
85205         pTerm->nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
85206       }
85207       pTerm->nNear++;
85208       continue;
85209     }
85210
85211     queryAdd(pQuery, pToken, nToken);
85212     if( !inPhrase && iBegin>0 && pSegment[iBegin-1]=='-' ){
85213       pQuery->pTerms[pQuery->nTerms-1].isNot = 1;
85214     }
85215     if( iEnd<nSegment && pSegment[iEnd]=='*' ){
85216       pQuery->pTerms[pQuery->nTerms-1].isPrefix = 1;
85217     }
85218     pQuery->pTerms[pQuery->nTerms-1].iPhrase = nTerm;
85219     if( inPhrase ){
85220       nTerm++;
85221     }
85222   }
85223
85224   if( inPhrase && pQuery->nTerms>firstIndex ){
85225     pQuery->pTerms[firstIndex].nPhrase = pQuery->nTerms - firstIndex - 1;
85226   }
85227
85228   return pModule->xClose(pCursor);
85229 }
85230
85231 /* Parse a query string, yielding a Query object pQuery.
85232 **
85233 ** The calling function will need to queryClear() to clean up
85234 ** the dynamically allocated memory held by pQuery.
85235 */
85236 static int parseQuery(
85237   fulltext_vtab *v,        /* The fulltext index */
85238   const char *zInput,      /* Input text of the query string */
85239   int nInput,              /* Size of the input text */
85240   int dfltColumn,          /* Default column of the index to match against */
85241   Query *pQuery            /* Write the parse results here. */
85242 ){
85243   int iInput, inPhrase = 0;
85244   int ii;
85245   QueryTerm *aTerm;
85246
85247   if( zInput==0 ) nInput = 0;
85248   if( nInput<0 ) nInput = strlen(zInput);
85249   pQuery->nTerms = 0;
85250   pQuery->pTerms = NULL;
85251   pQuery->nextIsOr = 0;
85252   pQuery->nextColumn = dfltColumn;
85253   pQuery->dfltColumn = dfltColumn;
85254   pQuery->pFts = v;
85255
85256   for(iInput=0; iInput<nInput; ++iInput){
85257     int i;
85258     for(i=iInput; i<nInput && zInput[i]!='"'; ++i){}
85259     if( i>iInput ){
85260       tokenizeSegment(v->pTokenizer, zInput+iInput, i-iInput, inPhrase,
85261                        pQuery);
85262     }
85263     iInput = i;
85264     if( i<nInput ){
85265       assert( zInput[i]=='"' );
85266       inPhrase = !inPhrase;
85267     }
85268   }
85269
85270   if( inPhrase ){
85271     /* unmatched quote */
85272     queryClear(pQuery);
85273     return SQLITE_ERROR;
85274   }
85275
85276   /* Modify the values of the QueryTerm.nPhrase variables to account for
85277   ** the NEAR operator. For the purposes of QueryTerm.nPhrase, phrases
85278   ** and tokens connected by the NEAR operator are handled as a single
85279   ** phrase. See comments above the QueryTerm structure for details.
85280   */
85281   aTerm = pQuery->pTerms;
85282   for(ii=0; ii<pQuery->nTerms; ii++){
85283     if( aTerm[ii].nNear || aTerm[ii].nPhrase ){
85284       while (aTerm[ii+aTerm[ii].nPhrase].nNear) {
85285         aTerm[ii].nPhrase += (1 + aTerm[ii+aTerm[ii].nPhrase+1].nPhrase);
85286       }
85287     }
85288   }
85289
85290   return SQLITE_OK;
85291 }
85292
85293 /* TODO(shess) Refactor the code to remove this forward decl. */
85294 static int flushPendingTerms(fulltext_vtab *v);
85295
85296 /* Perform a full-text query using the search expression in
85297 ** zInput[0..nInput-1].  Return a list of matching documents
85298 ** in pResult.
85299 **
85300 ** Queries must match column iColumn.  Or if iColumn>=nColumn
85301 ** they are allowed to match against any column.
85302 */
85303 static int fulltextQuery(
85304   fulltext_vtab *v,      /* The full text index */
85305   int iColumn,           /* Match against this column by default */
85306   const char *zInput,    /* The query string */
85307   int nInput,            /* Number of bytes in zInput[] */
85308   DataBuffer *pResult,   /* Write the result doclist here */
85309   Query *pQuery          /* Put parsed query string here */
85310 ){
85311   int i, iNext, rc;
85312   DataBuffer left, right, or, new;
85313   int nNot = 0;
85314   QueryTerm *aTerm;
85315
85316   /* TODO(shess) Instead of flushing pendingTerms, we could query for
85317   ** the relevant term and merge the doclist into what we receive from
85318   ** the database.  Wait and see if this is a common issue, first.
85319   **
85320   ** A good reason not to flush is to not generate update-related
85321   ** error codes from here.
85322   */
85323
85324   /* Flush any buffered updates before executing the query. */
85325   rc = flushPendingTerms(v);
85326   if( rc!=SQLITE_OK ) return rc;
85327
85328   /* TODO(shess) I think that the queryClear() calls below are not
85329   ** necessary, because fulltextClose() already clears the query.
85330   */
85331   rc = parseQuery(v, zInput, nInput, iColumn, pQuery);
85332   if( rc!=SQLITE_OK ) return rc;
85333
85334   /* Empty or NULL queries return no results. */
85335   if( pQuery->nTerms==0 ){
85336     dataBufferInit(pResult, 0);
85337     return SQLITE_OK;
85338   }
85339
85340   /* Merge AND terms. */
85341   /* TODO(shess) I think we can early-exit if( i>nNot && left.nData==0 ). */
85342   aTerm = pQuery->pTerms;
85343   for(i = 0; i<pQuery->nTerms; i=iNext){
85344     if( aTerm[i].isNot ){
85345       /* Handle all NOT terms in a separate pass */
85346       nNot++;
85347       iNext = i + aTerm[i].nPhrase+1;
85348       continue;
85349     }
85350     iNext = i + aTerm[i].nPhrase + 1;
85351     rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right);
85352     if( rc ){
85353       if( i!=nNot ) dataBufferDestroy(&left);
85354       queryClear(pQuery);
85355       return rc;
85356     }
85357     while( iNext<pQuery->nTerms && aTerm[iNext].isOr ){
85358       rc = docListOfTerm(v, aTerm[iNext].iColumn, &aTerm[iNext], &or);
85359       iNext += aTerm[iNext].nPhrase + 1;
85360       if( rc ){
85361         if( i!=nNot ) dataBufferDestroy(&left);
85362         dataBufferDestroy(&right);
85363         queryClear(pQuery);
85364         return rc;
85365       }
85366       dataBufferInit(&new, 0);
85367       docListOrMerge(right.pData, right.nData, or.pData, or.nData, &new);
85368       dataBufferDestroy(&right);
85369       dataBufferDestroy(&or);
85370       right = new;
85371     }
85372     if( i==nNot ){           /* first term processed. */
85373       left = right;
85374     }else{
85375       dataBufferInit(&new, 0);
85376       docListAndMerge(left.pData, left.nData, right.pData, right.nData, &new);
85377       dataBufferDestroy(&right);
85378       dataBufferDestroy(&left);
85379       left = new;
85380     }
85381   }
85382
85383   if( nNot==pQuery->nTerms ){
85384     /* We do not yet know how to handle a query of only NOT terms */
85385     return SQLITE_ERROR;
85386   }
85387
85388   /* Do the EXCEPT terms */
85389   for(i=0; i<pQuery->nTerms;  i += aTerm[i].nPhrase + 1){
85390     if( !aTerm[i].isNot ) continue;
85391     rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right);
85392     if( rc ){
85393       queryClear(pQuery);
85394       dataBufferDestroy(&left);
85395       return rc;
85396     }
85397     dataBufferInit(&new, 0);
85398     docListExceptMerge(left.pData, left.nData, right.pData, right.nData, &new);
85399     dataBufferDestroy(&right);
85400     dataBufferDestroy(&left);
85401     left = new;
85402   }
85403
85404   *pResult = left;
85405   return rc;
85406 }
85407
85408 /*
85409 ** This is the xFilter interface for the virtual table.  See
85410 ** the virtual table xFilter method documentation for additional
85411 ** information.
85412 **
85413 ** If idxNum==QUERY_GENERIC then do a full table scan against
85414 ** the %_content table.
85415 **
85416 ** If idxNum==QUERY_DOCID then do a docid lookup for a single entry
85417 ** in the %_content table.
85418 **
85419 ** If idxNum>=QUERY_FULLTEXT then use the full text index.  The
85420 ** column on the left-hand side of the MATCH operator is column
85421 ** number idxNum-QUERY_FULLTEXT, 0 indexed.  argv[0] is the right-hand
85422 ** side of the MATCH operator.
85423 */
85424 /* TODO(shess) Upgrade the cursor initialization and destruction to
85425 ** account for fulltextFilter() being called multiple times on the
85426 ** same cursor.  The current solution is very fragile.  Apply fix to
85427 ** fts3 as appropriate.
85428 */
85429 static int fulltextFilter(
85430   sqlite3_vtab_cursor *pCursor,     /* The cursor used for this query */
85431   int idxNum, const char *idxStr,   /* Which indexing scheme to use */
85432   int argc, sqlite3_value **argv    /* Arguments for the indexing scheme */
85433 ){
85434   fulltext_cursor *c = (fulltext_cursor *) pCursor;
85435   fulltext_vtab *v = cursor_vtab(c);
85436   int rc;
85437   StringBuffer sb;
85438
85439   FTSTRACE(("FTS3 Filter %p\n",pCursor));
85440
85441   initStringBuffer(&sb);
85442   append(&sb, "SELECT docid, ");
85443   appendList(&sb, v->nColumn, v->azContentColumn);
85444   append(&sb, " FROM %_content");
85445   if( idxNum!=QUERY_GENERIC ) append(&sb, " WHERE docid = ?");
85446   sqlite3_finalize(c->pStmt);
85447   rc = sql_prepare(v->db, v->zDb, v->zName, &c->pStmt, stringBufferData(&sb));
85448   stringBufferDestroy(&sb);
85449   if( rc!=SQLITE_OK ) return rc;
85450
85451   c->iCursorType = idxNum;
85452   switch( idxNum ){
85453     case QUERY_GENERIC:
85454       break;
85455
85456     case QUERY_DOCID:
85457       rc = sqlite3_bind_int64(c->pStmt, 1, sqlite3_value_int64(argv[0]));
85458       if( rc!=SQLITE_OK ) return rc;
85459       break;
85460
85461     default:   /* full-text search */
85462     {
85463       const char *zQuery = (const char *)sqlite3_value_text(argv[0]);
85464       assert( idxNum<=QUERY_FULLTEXT+v->nColumn);
85465       assert( argc==1 );
85466       queryClear(&c->q);
85467       if( c->result.nData!=0 ){
85468         /* This case happens if the same cursor is used repeatedly. */
85469         dlrDestroy(&c->reader);
85470         dataBufferReset(&c->result);
85471       }else{
85472         dataBufferInit(&c->result, 0);
85473       }
85474       rc = fulltextQuery(v, idxNum-QUERY_FULLTEXT, zQuery, -1, &c->result, &c->q);
85475       if( rc!=SQLITE_OK ) return rc;
85476       if( c->result.nData!=0 ){
85477         dlrInit(&c->reader, DL_DOCIDS, c->result.pData, c->result.nData);
85478       }
85479       break;
85480     }
85481   }
85482
85483   return fulltextNext(pCursor);
85484 }
85485
85486 /* This is the xEof method of the virtual table.  The SQLite core
85487 ** calls this routine to find out if it has reached the end of
85488 ** a query's results set.
85489 */
85490 static int fulltextEof(sqlite3_vtab_cursor *pCursor){
85491   fulltext_cursor *c = (fulltext_cursor *) pCursor;
85492   return c->eof;
85493 }
85494
85495 /* This is the xColumn method of the virtual table.  The SQLite
85496 ** core calls this method during a query when it needs the value
85497 ** of a column from the virtual table.  This method needs to use
85498 ** one of the sqlite3_result_*() routines to store the requested
85499 ** value back in the pContext.
85500 */
85501 static int fulltextColumn(sqlite3_vtab_cursor *pCursor,
85502                           sqlite3_context *pContext, int idxCol){
85503   fulltext_cursor *c = (fulltext_cursor *) pCursor;
85504   fulltext_vtab *v = cursor_vtab(c);
85505
85506   if( idxCol<v->nColumn ){
85507     sqlite3_value *pVal = sqlite3_column_value(c->pStmt, idxCol+1);
85508     sqlite3_result_value(pContext, pVal);
85509   }else if( idxCol==v->nColumn ){
85510     /* The extra column whose name is the same as the table.
85511     ** Return a blob which is a pointer to the cursor
85512     */
85513     sqlite3_result_blob(pContext, &c, sizeof(c), SQLITE_TRANSIENT);
85514   }else if( idxCol==v->nColumn+1 ){
85515     /* The docid column, which is an alias for rowid. */
85516     sqlite3_value *pVal = sqlite3_column_value(c->pStmt, 0);
85517     sqlite3_result_value(pContext, pVal);
85518   }
85519   return SQLITE_OK;
85520 }
85521
85522 /* This is the xRowid method.  The SQLite core calls this routine to
85523 ** retrieve the rowid for the current row of the result set.  fts3
85524 ** exposes %_content.docid as the rowid for the virtual table.  The
85525 ** rowid should be written to *pRowid.
85526 */
85527 static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
85528   fulltext_cursor *c = (fulltext_cursor *) pCursor;
85529
85530   *pRowid = sqlite3_column_int64(c->pStmt, 0);
85531   return SQLITE_OK;
85532 }
85533
85534 /* Add all terms in [zText] to pendingTerms table.  If [iColumn] > 0,
85535 ** we also store positions and offsets in the hash table using that
85536 ** column number.
85537 */
85538 static int buildTerms(fulltext_vtab *v, sqlite_int64 iDocid,
85539                       const char *zText, int iColumn){
85540   sqlite3_tokenizer *pTokenizer = v->pTokenizer;
85541   sqlite3_tokenizer_cursor *pCursor;
85542   const char *pToken;
85543   int nTokenBytes;
85544   int iStartOffset, iEndOffset, iPosition;
85545   int rc;
85546
85547   rc = pTokenizer->pModule->xOpen(pTokenizer, zText, -1, &pCursor);
85548   if( rc!=SQLITE_OK ) return rc;
85549
85550   pCursor->pTokenizer = pTokenizer;
85551   while( SQLITE_OK==(rc=pTokenizer->pModule->xNext(pCursor,
85552                                                    &pToken, &nTokenBytes,
85553                                                    &iStartOffset, &iEndOffset,
85554                                                    &iPosition)) ){
85555     DLCollector *p;
85556     int nData;                   /* Size of doclist before our update. */
85557
85558     /* Positions can't be negative; we use -1 as a terminator
85559      * internally.  Token can't be NULL or empty. */
85560     if( iPosition<0 || pToken == NULL || nTokenBytes == 0 ){
85561       rc = SQLITE_ERROR;
85562       break;
85563     }
85564
85565     p = fts3HashFind(&v->pendingTerms, pToken, nTokenBytes);
85566     if( p==NULL ){
85567       nData = 0;
85568       p = dlcNew(iDocid, DL_DEFAULT);
85569       fts3HashInsert(&v->pendingTerms, pToken, nTokenBytes, p);
85570
85571       /* Overhead for our hash table entry, the key, and the value. */
85572       v->nPendingData += sizeof(struct fts3HashElem)+sizeof(*p)+nTokenBytes;
85573     }else{
85574       nData = p->b.nData;
85575       if( p->dlw.iPrevDocid!=iDocid ) dlcNext(p, iDocid);
85576     }
85577     if( iColumn>=0 ){
85578       dlcAddPos(p, iColumn, iPosition, iStartOffset, iEndOffset);
85579     }
85580
85581     /* Accumulate data added by dlcNew or dlcNext, and dlcAddPos. */
85582     v->nPendingData += p->b.nData-nData;
85583   }
85584
85585   /* TODO(shess) Check return?  Should this be able to cause errors at
85586   ** this point?  Actually, same question about sqlite3_finalize(),
85587   ** though one could argue that failure there means that the data is
85588   ** not durable.  *ponder*
85589   */
85590   pTokenizer->pModule->xClose(pCursor);
85591   if( SQLITE_DONE == rc ) return SQLITE_OK;
85592   return rc;
85593 }
85594
85595 /* Add doclists for all terms in [pValues] to pendingTerms table. */
85596 static int insertTerms(fulltext_vtab *v, sqlite_int64 iDocid,
85597                        sqlite3_value **pValues){
85598   int i;
85599   for(i = 0; i < v->nColumn ; ++i){
85600     char *zText = (char*)sqlite3_value_text(pValues[i]);
85601     int rc = buildTerms(v, iDocid, zText, i);
85602     if( rc!=SQLITE_OK ) return rc;
85603   }
85604   return SQLITE_OK;
85605 }
85606
85607 /* Add empty doclists for all terms in the given row's content to
85608 ** pendingTerms.
85609 */
85610 static int deleteTerms(fulltext_vtab *v, sqlite_int64 iDocid){
85611   const char **pValues;
85612   int i, rc;
85613
85614   /* TODO(shess) Should we allow such tables at all? */
85615   if( DL_DEFAULT==DL_DOCIDS ) return SQLITE_ERROR;
85616
85617   rc = content_select(v, iDocid, &pValues);
85618   if( rc!=SQLITE_OK ) return rc;
85619
85620   for(i = 0 ; i < v->nColumn; ++i) {
85621     rc = buildTerms(v, iDocid, pValues[i], -1);
85622     if( rc!=SQLITE_OK ) break;
85623   }
85624
85625   freeStringArray(v->nColumn, pValues);
85626   return SQLITE_OK;
85627 }
85628
85629 /* TODO(shess) Refactor the code to remove this forward decl. */
85630 static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid);
85631
85632 /* Insert a row into the %_content table; set *piDocid to be the ID of the
85633 ** new row.  Add doclists for terms to pendingTerms.
85634 */
85635 static int index_insert(fulltext_vtab *v, sqlite3_value *pRequestDocid,
85636                         sqlite3_value **pValues, sqlite_int64 *piDocid){
85637   int rc;
85638
85639   rc = content_insert(v, pRequestDocid, pValues);  /* execute an SQL INSERT */
85640   if( rc!=SQLITE_OK ) return rc;
85641
85642   /* docid column is an alias for rowid. */
85643   *piDocid = sqlite3_last_insert_rowid(v->db);
85644   rc = initPendingTerms(v, *piDocid);
85645   if( rc!=SQLITE_OK ) return rc;
85646
85647   return insertTerms(v, *piDocid, pValues);
85648 }
85649
85650 /* Delete a row from the %_content table; add empty doclists for terms
85651 ** to pendingTerms.
85652 */
85653 static int index_delete(fulltext_vtab *v, sqlite_int64 iRow){
85654   int rc = initPendingTerms(v, iRow);
85655   if( rc!=SQLITE_OK ) return rc;
85656
85657   rc = deleteTerms(v, iRow);
85658   if( rc!=SQLITE_OK ) return rc;
85659
85660   return content_delete(v, iRow);  /* execute an SQL DELETE */
85661 }
85662
85663 /* Update a row in the %_content table; add delete doclists to
85664 ** pendingTerms for old terms not in the new data, add insert doclists
85665 ** to pendingTerms for terms in the new data.
85666 */
85667 static int index_update(fulltext_vtab *v, sqlite_int64 iRow,
85668                         sqlite3_value **pValues){
85669   int rc = initPendingTerms(v, iRow);
85670   if( rc!=SQLITE_OK ) return rc;
85671
85672   /* Generate an empty doclist for each term that previously appeared in this
85673    * row. */
85674   rc = deleteTerms(v, iRow);
85675   if( rc!=SQLITE_OK ) return rc;
85676
85677   rc = content_update(v, pValues, iRow);  /* execute an SQL UPDATE */
85678   if( rc!=SQLITE_OK ) return rc;
85679
85680   /* Now add positions for terms which appear in the updated row. */
85681   return insertTerms(v, iRow, pValues);
85682 }
85683
85684 /*******************************************************************/
85685 /* InteriorWriter is used to collect terms and block references into
85686 ** interior nodes in %_segments.  See commentary at top of file for
85687 ** format.
85688 */
85689
85690 /* How large interior nodes can grow. */
85691 #define INTERIOR_MAX 2048
85692
85693 /* Minimum number of terms per interior node (except the root). This
85694 ** prevents large terms from making the tree too skinny - must be >0
85695 ** so that the tree always makes progress.  Note that the min tree
85696 ** fanout will be INTERIOR_MIN_TERMS+1.
85697 */
85698 #define INTERIOR_MIN_TERMS 7
85699 #if INTERIOR_MIN_TERMS<1
85700 # error INTERIOR_MIN_TERMS must be greater than 0.
85701 #endif
85702
85703 /* ROOT_MAX controls how much data is stored inline in the segment
85704 ** directory.
85705 */
85706 /* TODO(shess) Push ROOT_MAX down to whoever is writing things.  It's
85707 ** only here so that interiorWriterRootInfo() and leafWriterRootInfo()
85708 ** can both see it, but if the caller passed it in, we wouldn't even
85709 ** need a define.
85710 */
85711 #define ROOT_MAX 1024
85712 #if ROOT_MAX<VARINT_MAX*2
85713 # error ROOT_MAX must have enough space for a header.
85714 #endif
85715
85716 /* InteriorBlock stores a linked-list of interior blocks while a lower
85717 ** layer is being constructed.
85718 */
85719 typedef struct InteriorBlock {
85720   DataBuffer term;           /* Leftmost term in block's subtree. */
85721   DataBuffer data;           /* Accumulated data for the block. */
85722   struct InteriorBlock *next;
85723 } InteriorBlock;
85724
85725 static InteriorBlock *interiorBlockNew(int iHeight, sqlite_int64 iChildBlock,
85726                                        const char *pTerm, int nTerm){
85727   InteriorBlock *block = sqlite3_malloc(sizeof(InteriorBlock));
85728   char c[VARINT_MAX+VARINT_MAX];
85729   int n;
85730
85731   if( block ){
85732     memset(block, 0, sizeof(*block));
85733     dataBufferInit(&block->term, 0);
85734     dataBufferReplace(&block->term, pTerm, nTerm);
85735
85736     n = fts3PutVarint(c, iHeight);
85737     n += fts3PutVarint(c+n, iChildBlock);
85738     dataBufferInit(&block->data, INTERIOR_MAX);
85739     dataBufferReplace(&block->data, c, n);
85740   }
85741   return block;
85742 }
85743
85744 #ifndef NDEBUG
85745 /* Verify that the data is readable as an interior node. */
85746 static void interiorBlockValidate(InteriorBlock *pBlock){
85747   const char *pData = pBlock->data.pData;
85748   int nData = pBlock->data.nData;
85749   int n, iDummy;
85750   sqlite_int64 iBlockid;
85751
85752   assert( nData>0 );
85753   assert( pData!=0 );
85754   assert( pData+nData>pData );
85755
85756   /* Must lead with height of node as a varint(n), n>0 */
85757   n = fts3GetVarint32(pData, &iDummy);
85758   assert( n>0 );
85759   assert( iDummy>0 );
85760   assert( n<nData );
85761   pData += n;
85762   nData -= n;
85763
85764   /* Must contain iBlockid. */
85765   n = fts3GetVarint(pData, &iBlockid);
85766   assert( n>0 );
85767   assert( n<=nData );
85768   pData += n;
85769   nData -= n;
85770
85771   /* Zero or more terms of positive length */
85772   if( nData!=0 ){
85773     /* First term is not delta-encoded. */
85774     n = fts3GetVarint32(pData, &iDummy);
85775     assert( n>0 );
85776     assert( iDummy>0 );
85777     assert( n+iDummy>0);
85778     assert( n+iDummy<=nData );
85779     pData += n+iDummy;
85780     nData -= n+iDummy;
85781
85782     /* Following terms delta-encoded. */
85783     while( nData!=0 ){
85784       /* Length of shared prefix. */
85785       n = fts3GetVarint32(pData, &iDummy);
85786       assert( n>0 );
85787       assert( iDummy>=0 );
85788       assert( n<nData );
85789       pData += n;
85790       nData -= n;
85791
85792       /* Length and data of distinct suffix. */
85793       n = fts3GetVarint32(pData, &iDummy);
85794       assert( n>0 );
85795       assert( iDummy>0 );
85796       assert( n+iDummy>0);
85797       assert( n+iDummy<=nData );
85798       pData += n+iDummy;
85799       nData -= n+iDummy;
85800     }
85801   }
85802 }
85803 #define ASSERT_VALID_INTERIOR_BLOCK(x) interiorBlockValidate(x)
85804 #else
85805 #define ASSERT_VALID_INTERIOR_BLOCK(x) assert( 1 )
85806 #endif
85807
85808 typedef struct InteriorWriter {
85809   int iHeight;                   /* from 0 at leaves. */
85810   InteriorBlock *first, *last;
85811   struct InteriorWriter *parentWriter;
85812
85813   DataBuffer term;               /* Last term written to block "last". */
85814   sqlite_int64 iOpeningChildBlock; /* First child block in block "last". */
85815 #ifndef NDEBUG
85816   sqlite_int64 iLastChildBlock;  /* for consistency checks. */
85817 #endif
85818 } InteriorWriter;
85819
85820 /* Initialize an interior node where pTerm[nTerm] marks the leftmost
85821 ** term in the tree.  iChildBlock is the leftmost child block at the
85822 ** next level down the tree.
85823 */
85824 static void interiorWriterInit(int iHeight, const char *pTerm, int nTerm,
85825                                sqlite_int64 iChildBlock,
85826                                InteriorWriter *pWriter){
85827   InteriorBlock *block;
85828   assert( iHeight>0 );
85829   CLEAR(pWriter);
85830
85831   pWriter->iHeight = iHeight;
85832   pWriter->iOpeningChildBlock = iChildBlock;
85833 #ifndef NDEBUG
85834   pWriter->iLastChildBlock = iChildBlock;
85835 #endif
85836   block = interiorBlockNew(iHeight, iChildBlock, pTerm, nTerm);
85837   pWriter->last = pWriter->first = block;
85838   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
85839   dataBufferInit(&pWriter->term, 0);
85840 }
85841
85842 /* Append the child node rooted at iChildBlock to the interior node,
85843 ** with pTerm[nTerm] as the leftmost term in iChildBlock's subtree.
85844 */
85845 static void interiorWriterAppend(InteriorWriter *pWriter,
85846                                  const char *pTerm, int nTerm,
85847                                  sqlite_int64 iChildBlock){
85848   char c[VARINT_MAX+VARINT_MAX];
85849   int n, nPrefix = 0;
85850
85851   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
85852
85853   /* The first term written into an interior node is actually
85854   ** associated with the second child added (the first child was added
85855   ** in interiorWriterInit, or in the if clause at the bottom of this
85856   ** function).  That term gets encoded straight up, with nPrefix left
85857   ** at 0.
85858   */
85859   if( pWriter->term.nData==0 ){
85860     n = fts3PutVarint(c, nTerm);
85861   }else{
85862     while( nPrefix<pWriter->term.nData &&
85863            pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
85864       nPrefix++;
85865     }
85866
85867     n = fts3PutVarint(c, nPrefix);
85868     n += fts3PutVarint(c+n, nTerm-nPrefix);
85869   }
85870
85871 #ifndef NDEBUG
85872   pWriter->iLastChildBlock++;
85873 #endif
85874   assert( pWriter->iLastChildBlock==iChildBlock );
85875
85876   /* Overflow to a new block if the new term makes the current block
85877   ** too big, and the current block already has enough terms.
85878   */
85879   if( pWriter->last->data.nData+n+nTerm-nPrefix>INTERIOR_MAX &&
85880       iChildBlock-pWriter->iOpeningChildBlock>INTERIOR_MIN_TERMS ){
85881     pWriter->last->next = interiorBlockNew(pWriter->iHeight, iChildBlock,
85882                                            pTerm, nTerm);
85883     pWriter->last = pWriter->last->next;
85884     pWriter->iOpeningChildBlock = iChildBlock;
85885     dataBufferReset(&pWriter->term);
85886   }else{
85887     dataBufferAppend2(&pWriter->last->data, c, n,
85888                       pTerm+nPrefix, nTerm-nPrefix);
85889     dataBufferReplace(&pWriter->term, pTerm, nTerm);
85890   }
85891   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
85892 }
85893
85894 /* Free the space used by pWriter, including the linked-list of
85895 ** InteriorBlocks, and parentWriter, if present.
85896 */
85897 static int interiorWriterDestroy(InteriorWriter *pWriter){
85898   InteriorBlock *block = pWriter->first;
85899
85900   while( block!=NULL ){
85901     InteriorBlock *b = block;
85902     block = block->next;
85903     dataBufferDestroy(&b->term);
85904     dataBufferDestroy(&b->data);
85905     sqlite3_free(b);
85906   }
85907   if( pWriter->parentWriter!=NULL ){
85908     interiorWriterDestroy(pWriter->parentWriter);
85909     sqlite3_free(pWriter->parentWriter);
85910   }
85911   dataBufferDestroy(&pWriter->term);
85912   SCRAMBLE(pWriter);
85913   return SQLITE_OK;
85914 }
85915
85916 /* If pWriter can fit entirely in ROOT_MAX, return it as the root info
85917 ** directly, leaving *piEndBlockid unchanged.  Otherwise, flush
85918 ** pWriter to %_segments, building a new layer of interior nodes, and
85919 ** recursively ask for their root into.
85920 */
85921 static int interiorWriterRootInfo(fulltext_vtab *v, InteriorWriter *pWriter,
85922                                   char **ppRootInfo, int *pnRootInfo,
85923                                   sqlite_int64 *piEndBlockid){
85924   InteriorBlock *block = pWriter->first;
85925   sqlite_int64 iBlockid = 0;
85926   int rc;
85927
85928   /* If we can fit the segment inline */
85929   if( block==pWriter->last && block->data.nData<ROOT_MAX ){
85930     *ppRootInfo = block->data.pData;
85931     *pnRootInfo = block->data.nData;
85932     return SQLITE_OK;
85933   }
85934
85935   /* Flush the first block to %_segments, and create a new level of
85936   ** interior node.
85937   */
85938   ASSERT_VALID_INTERIOR_BLOCK(block);
85939   rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
85940   if( rc!=SQLITE_OK ) return rc;
85941   *piEndBlockid = iBlockid;
85942
85943   pWriter->parentWriter = sqlite3_malloc(sizeof(*pWriter->parentWriter));
85944   interiorWriterInit(pWriter->iHeight+1,
85945                      block->term.pData, block->term.nData,
85946                      iBlockid, pWriter->parentWriter);
85947
85948   /* Flush additional blocks and append to the higher interior
85949   ** node.
85950   */
85951   for(block=block->next; block!=NULL; block=block->next){
85952     ASSERT_VALID_INTERIOR_BLOCK(block);
85953     rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
85954     if( rc!=SQLITE_OK ) return rc;
85955     *piEndBlockid = iBlockid;
85956
85957     interiorWriterAppend(pWriter->parentWriter,
85958                          block->term.pData, block->term.nData, iBlockid);
85959   }
85960
85961   /* Parent node gets the chance to be the root. */
85962   return interiorWriterRootInfo(v, pWriter->parentWriter,
85963                                 ppRootInfo, pnRootInfo, piEndBlockid);
85964 }
85965
85966 /****************************************************************/
85967 /* InteriorReader is used to read off the data from an interior node
85968 ** (see comment at top of file for the format).
85969 */
85970 typedef struct InteriorReader {
85971   const char *pData;
85972   int nData;
85973
85974   DataBuffer term;          /* previous term, for decoding term delta. */
85975
85976   sqlite_int64 iBlockid;
85977 } InteriorReader;
85978
85979 static void interiorReaderDestroy(InteriorReader *pReader){
85980   dataBufferDestroy(&pReader->term);
85981   SCRAMBLE(pReader);
85982 }
85983
85984 /* TODO(shess) The assertions are great, but what if we're in NDEBUG
85985 ** and the blob is empty or otherwise contains suspect data?
85986 */
85987 static void interiorReaderInit(const char *pData, int nData,
85988                                InteriorReader *pReader){
85989   int n, nTerm;
85990
85991   /* Require at least the leading flag byte */
85992   assert( nData>0 );
85993   assert( pData[0]!='\0' );
85994
85995   CLEAR(pReader);
85996
85997   /* Decode the base blockid, and set the cursor to the first term. */
85998   n = fts3GetVarint(pData+1, &pReader->iBlockid);
85999   assert( 1+n<=nData );
86000   pReader->pData = pData+1+n;
86001   pReader->nData = nData-(1+n);
86002
86003   /* A single-child interior node (such as when a leaf node was too
86004   ** large for the segment directory) won't have any terms.
86005   ** Otherwise, decode the first term.
86006   */
86007   if( pReader->nData==0 ){
86008     dataBufferInit(&pReader->term, 0);
86009   }else{
86010     n = fts3GetVarint32(pReader->pData, &nTerm);
86011     dataBufferInit(&pReader->term, nTerm);
86012     dataBufferReplace(&pReader->term, pReader->pData+n, nTerm);
86013     assert( n+nTerm<=pReader->nData );
86014     pReader->pData += n+nTerm;
86015     pReader->nData -= n+nTerm;
86016   }
86017 }
86018
86019 static int interiorReaderAtEnd(InteriorReader *pReader){
86020   return pReader->term.nData==0;
86021 }
86022
86023 static sqlite_int64 interiorReaderCurrentBlockid(InteriorReader *pReader){
86024   return pReader->iBlockid;
86025 }
86026
86027 static int interiorReaderTermBytes(InteriorReader *pReader){
86028   assert( !interiorReaderAtEnd(pReader) );
86029   return pReader->term.nData;
86030 }
86031 static const char *interiorReaderTerm(InteriorReader *pReader){
86032   assert( !interiorReaderAtEnd(pReader) );
86033   return pReader->term.pData;
86034 }
86035
86036 /* Step forward to the next term in the node. */
86037 static void interiorReaderStep(InteriorReader *pReader){
86038   assert( !interiorReaderAtEnd(pReader) );
86039
86040   /* If the last term has been read, signal eof, else construct the
86041   ** next term.
86042   */
86043   if( pReader->nData==0 ){
86044     dataBufferReset(&pReader->term);
86045   }else{
86046     int n, nPrefix, nSuffix;
86047
86048     n = fts3GetVarint32(pReader->pData, &nPrefix);
86049     n += fts3GetVarint32(pReader->pData+n, &nSuffix);
86050
86051     /* Truncate the current term and append suffix data. */
86052     pReader->term.nData = nPrefix;
86053     dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
86054
86055     assert( n+nSuffix<=pReader->nData );
86056     pReader->pData += n+nSuffix;
86057     pReader->nData -= n+nSuffix;
86058   }
86059   pReader->iBlockid++;
86060 }
86061
86062 /* Compare the current term to pTerm[nTerm], returning strcmp-style
86063 ** results.  If isPrefix, equality means equal through nTerm bytes.
86064 */
86065 static int interiorReaderTermCmp(InteriorReader *pReader,
86066                                  const char *pTerm, int nTerm, int isPrefix){
86067   const char *pReaderTerm = interiorReaderTerm(pReader);
86068   int nReaderTerm = interiorReaderTermBytes(pReader);
86069   int c, n = nReaderTerm<nTerm ? nReaderTerm : nTerm;
86070
86071   if( n==0 ){
86072     if( nReaderTerm>0 ) return -1;
86073     if( nTerm>0 ) return 1;
86074     return 0;
86075   }
86076
86077   c = memcmp(pReaderTerm, pTerm, n);
86078   if( c!=0 ) return c;
86079   if( isPrefix && n==nTerm ) return 0;
86080   return nReaderTerm - nTerm;
86081 }
86082
86083 /****************************************************************/
86084 /* LeafWriter is used to collect terms and associated doclist data
86085 ** into leaf blocks in %_segments (see top of file for format info).
86086 ** Expected usage is:
86087 **
86088 ** LeafWriter writer;
86089 ** leafWriterInit(0, 0, &writer);
86090 ** while( sorted_terms_left_to_process ){
86091 **   // data is doclist data for that term.
86092 **   rc = leafWriterStep(v, &writer, pTerm, nTerm, pData, nData);
86093 **   if( rc!=SQLITE_OK ) goto err;
86094 ** }
86095 ** rc = leafWriterFinalize(v, &writer);
86096 **err:
86097 ** leafWriterDestroy(&writer);
86098 ** return rc;
86099 **
86100 ** leafWriterStep() may write a collected leaf out to %_segments.
86101 ** leafWriterFinalize() finishes writing any buffered data and stores
86102 ** a root node in %_segdir.  leafWriterDestroy() frees all buffers and
86103 ** InteriorWriters allocated as part of writing this segment.
86104 **
86105 ** TODO(shess) Document leafWriterStepMerge().
86106 */
86107
86108 /* Put terms with data this big in their own block. */
86109 #define STANDALONE_MIN 1024
86110
86111 /* Keep leaf blocks below this size. */
86112 #define LEAF_MAX 2048
86113
86114 typedef struct LeafWriter {
86115   int iLevel;
86116   int idx;
86117   sqlite_int64 iStartBlockid;     /* needed to create the root info */
86118   sqlite_int64 iEndBlockid;       /* when we're done writing. */
86119
86120   DataBuffer term;                /* previous encoded term */
86121   DataBuffer data;                /* encoding buffer */
86122
86123   /* bytes of first term in the current node which distinguishes that
86124   ** term from the last term of the previous node.
86125   */
86126   int nTermDistinct;
86127
86128   InteriorWriter parentWriter;    /* if we overflow */
86129   int has_parent;
86130 } LeafWriter;
86131
86132 static void leafWriterInit(int iLevel, int idx, LeafWriter *pWriter){
86133   CLEAR(pWriter);
86134   pWriter->iLevel = iLevel;
86135   pWriter->idx = idx;
86136
86137   dataBufferInit(&pWriter->term, 32);
86138
86139   /* Start out with a reasonably sized block, though it can grow. */
86140   dataBufferInit(&pWriter->data, LEAF_MAX);
86141 }
86142
86143 #ifndef NDEBUG
86144 /* Verify that the data is readable as a leaf node. */
86145 static void leafNodeValidate(const char *pData, int nData){
86146   int n, iDummy;
86147
86148   if( nData==0 ) return;
86149   assert( nData>0 );
86150   assert( pData!=0 );
86151   assert( pData+nData>pData );
86152
86153   /* Must lead with a varint(0) */
86154   n = fts3GetVarint32(pData, &iDummy);
86155   assert( iDummy==0 );
86156   assert( n>0 );
86157   assert( n<nData );
86158   pData += n;
86159   nData -= n;
86160
86161   /* Leading term length and data must fit in buffer. */
86162   n = fts3GetVarint32(pData, &iDummy);
86163   assert( n>0 );
86164   assert( iDummy>0 );
86165   assert( n+iDummy>0 );
86166   assert( n+iDummy<nData );
86167   pData += n+iDummy;
86168   nData -= n+iDummy;
86169
86170   /* Leading term's doclist length and data must fit. */
86171   n = fts3GetVarint32(pData, &iDummy);
86172   assert( n>0 );
86173   assert( iDummy>0 );
86174   assert( n+iDummy>0 );
86175   assert( n+iDummy<=nData );
86176   ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
86177   pData += n+iDummy;
86178   nData -= n+iDummy;
86179
86180   /* Verify that trailing terms and doclists also are readable. */
86181   while( nData!=0 ){
86182     n = fts3GetVarint32(pData, &iDummy);
86183     assert( n>0 );
86184     assert( iDummy>=0 );
86185     assert( n<nData );
86186     pData += n;
86187     nData -= n;
86188     n = fts3GetVarint32(pData, &iDummy);
86189     assert( n>0 );
86190     assert( iDummy>0 );
86191     assert( n+iDummy>0 );
86192     assert( n+iDummy<nData );
86193     pData += n+iDummy;
86194     nData -= n+iDummy;
86195
86196     n = fts3GetVarint32(pData, &iDummy);
86197     assert( n>0 );
86198     assert( iDummy>0 );
86199     assert( n+iDummy>0 );
86200     assert( n+iDummy<=nData );
86201     ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
86202     pData += n+iDummy;
86203     nData -= n+iDummy;
86204   }
86205 }
86206 #define ASSERT_VALID_LEAF_NODE(p, n) leafNodeValidate(p, n)
86207 #else
86208 #define ASSERT_VALID_LEAF_NODE(p, n) assert( 1 )
86209 #endif
86210
86211 /* Flush the current leaf node to %_segments, and adding the resulting
86212 ** blockid and the starting term to the interior node which will
86213 ** contain it.
86214 */
86215 static int leafWriterInternalFlush(fulltext_vtab *v, LeafWriter *pWriter,
86216                                    int iData, int nData){
86217   sqlite_int64 iBlockid = 0;
86218   const char *pStartingTerm;
86219   int nStartingTerm, rc, n;
86220
86221   /* Must have the leading varint(0) flag, plus at least some
86222   ** valid-looking data.
86223   */
86224   assert( nData>2 );
86225   assert( iData>=0 );
86226   assert( iData+nData<=pWriter->data.nData );
86227   ASSERT_VALID_LEAF_NODE(pWriter->data.pData+iData, nData);
86228
86229   rc = block_insert(v, pWriter->data.pData+iData, nData, &iBlockid);
86230   if( rc!=SQLITE_OK ) return rc;
86231   assert( iBlockid!=0 );
86232
86233   /* Reconstruct the first term in the leaf for purposes of building
86234   ** the interior node.
86235   */
86236   n = fts3GetVarint32(pWriter->data.pData+iData+1, &nStartingTerm);
86237   pStartingTerm = pWriter->data.pData+iData+1+n;
86238   assert( pWriter->data.nData>iData+1+n+nStartingTerm );
86239   assert( pWriter->nTermDistinct>0 );
86240   assert( pWriter->nTermDistinct<=nStartingTerm );
86241   nStartingTerm = pWriter->nTermDistinct;
86242
86243   if( pWriter->has_parent ){
86244     interiorWriterAppend(&pWriter->parentWriter,
86245                          pStartingTerm, nStartingTerm, iBlockid);
86246   }else{
86247     interiorWriterInit(1, pStartingTerm, nStartingTerm, iBlockid,
86248                        &pWriter->parentWriter);
86249     pWriter->has_parent = 1;
86250   }
86251
86252   /* Track the span of this segment's leaf nodes. */
86253   if( pWriter->iEndBlockid==0 ){
86254     pWriter->iEndBlockid = pWriter->iStartBlockid = iBlockid;
86255   }else{
86256     pWriter->iEndBlockid++;
86257     assert( iBlockid==pWriter->iEndBlockid );
86258   }
86259
86260   return SQLITE_OK;
86261 }
86262 static int leafWriterFlush(fulltext_vtab *v, LeafWriter *pWriter){
86263   int rc = leafWriterInternalFlush(v, pWriter, 0, pWriter->data.nData);
86264   if( rc!=SQLITE_OK ) return rc;
86265
86266   /* Re-initialize the output buffer. */
86267   dataBufferReset(&pWriter->data);
86268
86269   return SQLITE_OK;
86270 }
86271
86272 /* Fetch the root info for the segment.  If the entire leaf fits
86273 ** within ROOT_MAX, then it will be returned directly, otherwise it
86274 ** will be flushed and the root info will be returned from the
86275 ** interior node.  *piEndBlockid is set to the blockid of the last
86276 ** interior or leaf node written to disk (0 if none are written at
86277 ** all).
86278 */
86279 static int leafWriterRootInfo(fulltext_vtab *v, LeafWriter *pWriter,
86280                               char **ppRootInfo, int *pnRootInfo,
86281                               sqlite_int64 *piEndBlockid){
86282   /* we can fit the segment entirely inline */
86283   if( !pWriter->has_parent && pWriter->data.nData<ROOT_MAX ){
86284     *ppRootInfo = pWriter->data.pData;
86285     *pnRootInfo = pWriter->data.nData;
86286     *piEndBlockid = 0;
86287     return SQLITE_OK;
86288   }
86289
86290   /* Flush remaining leaf data. */
86291   if( pWriter->data.nData>0 ){
86292     int rc = leafWriterFlush(v, pWriter);
86293     if( rc!=SQLITE_OK ) return rc;
86294   }
86295
86296   /* We must have flushed a leaf at some point. */
86297   assert( pWriter->has_parent );
86298
86299   /* Tenatively set the end leaf blockid as the end blockid.  If the
86300   ** interior node can be returned inline, this will be the final
86301   ** blockid, otherwise it will be overwritten by
86302   ** interiorWriterRootInfo().
86303   */
86304   *piEndBlockid = pWriter->iEndBlockid;
86305
86306   return interiorWriterRootInfo(v, &pWriter->parentWriter,
86307                                 ppRootInfo, pnRootInfo, piEndBlockid);
86308 }
86309
86310 /* Collect the rootInfo data and store it into the segment directory.
86311 ** This has the effect of flushing the segment's leaf data to
86312 ** %_segments, and also flushing any interior nodes to %_segments.
86313 */
86314 static int leafWriterFinalize(fulltext_vtab *v, LeafWriter *pWriter){
86315   sqlite_int64 iEndBlockid;
86316   char *pRootInfo;
86317   int rc, nRootInfo;
86318
86319   rc = leafWriterRootInfo(v, pWriter, &pRootInfo, &nRootInfo, &iEndBlockid);
86320   if( rc!=SQLITE_OK ) return rc;
86321
86322   /* Don't bother storing an entirely empty segment. */
86323   if( iEndBlockid==0 && nRootInfo==0 ) return SQLITE_OK;
86324
86325   return segdir_set(v, pWriter->iLevel, pWriter->idx,
86326                     pWriter->iStartBlockid, pWriter->iEndBlockid,
86327                     iEndBlockid, pRootInfo, nRootInfo);
86328 }
86329
86330 static void leafWriterDestroy(LeafWriter *pWriter){
86331   if( pWriter->has_parent ) interiorWriterDestroy(&pWriter->parentWriter);
86332   dataBufferDestroy(&pWriter->term);
86333   dataBufferDestroy(&pWriter->data);
86334 }
86335
86336 /* Encode a term into the leafWriter, delta-encoding as appropriate.
86337 ** Returns the length of the new term which distinguishes it from the
86338 ** previous term, which can be used to set nTermDistinct when a node
86339 ** boundary is crossed.
86340 */
86341 static int leafWriterEncodeTerm(LeafWriter *pWriter,
86342                                 const char *pTerm, int nTerm){
86343   char c[VARINT_MAX+VARINT_MAX];
86344   int n, nPrefix = 0;
86345
86346   assert( nTerm>0 );
86347   while( nPrefix<pWriter->term.nData &&
86348          pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
86349     nPrefix++;
86350     /* Failing this implies that the terms weren't in order. */
86351     assert( nPrefix<nTerm );
86352   }
86353
86354   if( pWriter->data.nData==0 ){
86355     /* Encode the node header and leading term as:
86356     **  varint(0)
86357     **  varint(nTerm)
86358     **  char pTerm[nTerm]
86359     */
86360     n = fts3PutVarint(c, '\0');
86361     n += fts3PutVarint(c+n, nTerm);
86362     dataBufferAppend2(&pWriter->data, c, n, pTerm, nTerm);
86363   }else{
86364     /* Delta-encode the term as:
86365     **  varint(nPrefix)
86366     **  varint(nSuffix)
86367     **  char pTermSuffix[nSuffix]
86368     */
86369     n = fts3PutVarint(c, nPrefix);
86370     n += fts3PutVarint(c+n, nTerm-nPrefix);
86371     dataBufferAppend2(&pWriter->data, c, n, pTerm+nPrefix, nTerm-nPrefix);
86372   }
86373   dataBufferReplace(&pWriter->term, pTerm, nTerm);
86374
86375   return nPrefix+1;
86376 }
86377
86378 /* Used to avoid a memmove when a large amount of doclist data is in
86379 ** the buffer.  This constructs a node and term header before
86380 ** iDoclistData and flushes the resulting complete node using
86381 ** leafWriterInternalFlush().
86382 */
86383 static int leafWriterInlineFlush(fulltext_vtab *v, LeafWriter *pWriter,
86384                                  const char *pTerm, int nTerm,
86385                                  int iDoclistData){
86386   char c[VARINT_MAX+VARINT_MAX];
86387   int iData, n = fts3PutVarint(c, 0);
86388   n += fts3PutVarint(c+n, nTerm);
86389
86390   /* There should always be room for the header.  Even if pTerm shared
86391   ** a substantial prefix with the previous term, the entire prefix
86392   ** could be constructed from earlier data in the doclist, so there
86393   ** should be room.
86394   */
86395   assert( iDoclistData>=n+nTerm );
86396
86397   iData = iDoclistData-(n+nTerm);
86398   memcpy(pWriter->data.pData+iData, c, n);
86399   memcpy(pWriter->data.pData+iData+n, pTerm, nTerm);
86400
86401   return leafWriterInternalFlush(v, pWriter, iData, pWriter->data.nData-iData);
86402 }
86403
86404 /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
86405 ** %_segments.
86406 */
86407 static int leafWriterStepMerge(fulltext_vtab *v, LeafWriter *pWriter,
86408                                const char *pTerm, int nTerm,
86409                                DLReader *pReaders, int nReaders){
86410   char c[VARINT_MAX+VARINT_MAX];
86411   int iTermData = pWriter->data.nData, iDoclistData;
86412   int i, nData, n, nActualData, nActual, rc, nTermDistinct;
86413
86414   ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
86415   nTermDistinct = leafWriterEncodeTerm(pWriter, pTerm, nTerm);
86416
86417   /* Remember nTermDistinct if opening a new node. */
86418   if( iTermData==0 ) pWriter->nTermDistinct = nTermDistinct;
86419
86420   iDoclistData = pWriter->data.nData;
86421
86422   /* Estimate the length of the merged doclist so we can leave space
86423   ** to encode it.
86424   */
86425   for(i=0, nData=0; i<nReaders; i++){
86426     nData += dlrAllDataBytes(&pReaders[i]);
86427   }
86428   n = fts3PutVarint(c, nData);
86429   dataBufferAppend(&pWriter->data, c, n);
86430
86431   docListMerge(&pWriter->data, pReaders, nReaders);
86432   ASSERT_VALID_DOCLIST(DL_DEFAULT,
86433                        pWriter->data.pData+iDoclistData+n,
86434                        pWriter->data.nData-iDoclistData-n, NULL);
86435
86436   /* The actual amount of doclist data at this point could be smaller
86437   ** than the length we encoded.  Additionally, the space required to
86438   ** encode this length could be smaller.  For small doclists, this is
86439   ** not a big deal, we can just use memmove() to adjust things.
86440   */
86441   nActualData = pWriter->data.nData-(iDoclistData+n);
86442   nActual = fts3PutVarint(c, nActualData);
86443   assert( nActualData<=nData );
86444   assert( nActual<=n );
86445
86446   /* If the new doclist is big enough for force a standalone leaf
86447   ** node, we can immediately flush it inline without doing the
86448   ** memmove().
86449   */
86450   /* TODO(shess) This test matches leafWriterStep(), which does this
86451   ** test before it knows the cost to varint-encode the term and
86452   ** doclist lengths.  At some point, change to
86453   ** pWriter->data.nData-iTermData>STANDALONE_MIN.
86454   */
86455   if( nTerm+nActualData>STANDALONE_MIN ){
86456     /* Push leaf node from before this term. */
86457     if( iTermData>0 ){
86458       rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
86459       if( rc!=SQLITE_OK ) return rc;
86460
86461       pWriter->nTermDistinct = nTermDistinct;
86462     }
86463
86464     /* Fix the encoded doclist length. */
86465     iDoclistData += n - nActual;
86466     memcpy(pWriter->data.pData+iDoclistData, c, nActual);
86467
86468     /* Push the standalone leaf node. */
86469     rc = leafWriterInlineFlush(v, pWriter, pTerm, nTerm, iDoclistData);
86470     if( rc!=SQLITE_OK ) return rc;
86471
86472     /* Leave the node empty. */
86473     dataBufferReset(&pWriter->data);
86474
86475     return rc;
86476   }
86477
86478   /* At this point, we know that the doclist was small, so do the
86479   ** memmove if indicated.
86480   */
86481   if( nActual<n ){
86482     memmove(pWriter->data.pData+iDoclistData+nActual,
86483             pWriter->data.pData+iDoclistData+n,
86484             pWriter->data.nData-(iDoclistData+n));
86485     pWriter->data.nData -= n-nActual;
86486   }
86487
86488   /* Replace written length with actual length. */
86489   memcpy(pWriter->data.pData+iDoclistData, c, nActual);
86490
86491   /* If the node is too large, break things up. */
86492   /* TODO(shess) This test matches leafWriterStep(), which does this
86493   ** test before it knows the cost to varint-encode the term and
86494   ** doclist lengths.  At some point, change to
86495   ** pWriter->data.nData>LEAF_MAX.
86496   */
86497   if( iTermData+nTerm+nActualData>LEAF_MAX ){
86498     /* Flush out the leading data as a node */
86499     rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
86500     if( rc!=SQLITE_OK ) return rc;
86501
86502     pWriter->nTermDistinct = nTermDistinct;
86503
86504     /* Rebuild header using the current term */
86505     n = fts3PutVarint(pWriter->data.pData, 0);
86506     n += fts3PutVarint(pWriter->data.pData+n, nTerm);
86507     memcpy(pWriter->data.pData+n, pTerm, nTerm);
86508     n += nTerm;
86509
86510     /* There should always be room, because the previous encoding
86511     ** included all data necessary to construct the term.
86512     */
86513     assert( n<iDoclistData );
86514     /* So long as STANDALONE_MIN is half or less of LEAF_MAX, the
86515     ** following memcpy() is safe (as opposed to needing a memmove).
86516     */
86517     assert( 2*STANDALONE_MIN<=LEAF_MAX );
86518     assert( n+pWriter->data.nData-iDoclistData<iDoclistData );
86519     memcpy(pWriter->data.pData+n,
86520            pWriter->data.pData+iDoclistData,
86521            pWriter->data.nData-iDoclistData);
86522     pWriter->data.nData -= iDoclistData-n;
86523   }
86524   ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
86525
86526   return SQLITE_OK;
86527 }
86528
86529 /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
86530 ** %_segments.
86531 */
86532 /* TODO(shess) Revise writeZeroSegment() so that doclists are
86533 ** constructed directly in pWriter->data.
86534 */
86535 static int leafWriterStep(fulltext_vtab *v, LeafWriter *pWriter,
86536                           const char *pTerm, int nTerm,
86537                           const char *pData, int nData){
86538   int rc;
86539   DLReader reader;
86540
86541   dlrInit(&reader, DL_DEFAULT, pData, nData);
86542   rc = leafWriterStepMerge(v, pWriter, pTerm, nTerm, &reader, 1);
86543   dlrDestroy(&reader);
86544
86545   return rc;
86546 }
86547
86548
86549 /****************************************************************/
86550 /* LeafReader is used to iterate over an individual leaf node. */
86551 typedef struct LeafReader {
86552   DataBuffer term;          /* copy of current term. */
86553
86554   const char *pData;        /* data for current term. */
86555   int nData;
86556 } LeafReader;
86557
86558 static void leafReaderDestroy(LeafReader *pReader){
86559   dataBufferDestroy(&pReader->term);
86560   SCRAMBLE(pReader);
86561 }
86562
86563 static int leafReaderAtEnd(LeafReader *pReader){
86564   return pReader->nData<=0;
86565 }
86566
86567 /* Access the current term. */
86568 static int leafReaderTermBytes(LeafReader *pReader){
86569   return pReader->term.nData;
86570 }
86571 static const char *leafReaderTerm(LeafReader *pReader){
86572   assert( pReader->term.nData>0 );
86573   return pReader->term.pData;
86574 }
86575
86576 /* Access the doclist data for the current term. */
86577 static int leafReaderDataBytes(LeafReader *pReader){
86578   int nData;
86579   assert( pReader->term.nData>0 );
86580   fts3GetVarint32(pReader->pData, &nData);
86581   return nData;
86582 }
86583 static const char *leafReaderData(LeafReader *pReader){
86584   int n, nData;
86585   assert( pReader->term.nData>0 );
86586   n = fts3GetVarint32(pReader->pData, &nData);
86587   return pReader->pData+n;
86588 }
86589
86590 static void leafReaderInit(const char *pData, int nData,
86591                            LeafReader *pReader){
86592   int nTerm, n;
86593
86594   assert( nData>0 );
86595   assert( pData[0]=='\0' );
86596
86597   CLEAR(pReader);
86598
86599   /* Read the first term, skipping the header byte. */
86600   n = fts3GetVarint32(pData+1, &nTerm);
86601   dataBufferInit(&pReader->term, nTerm);
86602   dataBufferReplace(&pReader->term, pData+1+n, nTerm);
86603
86604   /* Position after the first term. */
86605   assert( 1+n+nTerm<nData );
86606   pReader->pData = pData+1+n+nTerm;
86607   pReader->nData = nData-1-n-nTerm;
86608 }
86609
86610 /* Step the reader forward to the next term. */
86611 static void leafReaderStep(LeafReader *pReader){
86612   int n, nData, nPrefix, nSuffix;
86613   assert( !leafReaderAtEnd(pReader) );
86614
86615   /* Skip previous entry's data block. */
86616   n = fts3GetVarint32(pReader->pData, &nData);
86617   assert( n+nData<=pReader->nData );
86618   pReader->pData += n+nData;
86619   pReader->nData -= n+nData;
86620
86621   if( !leafReaderAtEnd(pReader) ){
86622     /* Construct the new term using a prefix from the old term plus a
86623     ** suffix from the leaf data.
86624     */
86625     n = fts3GetVarint32(pReader->pData, &nPrefix);
86626     n += fts3GetVarint32(pReader->pData+n, &nSuffix);
86627     assert( n+nSuffix<pReader->nData );
86628     pReader->term.nData = nPrefix;
86629     dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
86630
86631     pReader->pData += n+nSuffix;
86632     pReader->nData -= n+nSuffix;
86633   }
86634 }
86635
86636 /* strcmp-style comparison of pReader's current term against pTerm.
86637 ** If isPrefix, equality means equal through nTerm bytes.
86638 */
86639 static int leafReaderTermCmp(LeafReader *pReader,
86640                              const char *pTerm, int nTerm, int isPrefix){
86641   int c, n = pReader->term.nData<nTerm ? pReader->term.nData : nTerm;
86642   if( n==0 ){
86643     if( pReader->term.nData>0 ) return -1;
86644     if(nTerm>0 ) return 1;
86645     return 0;
86646   }
86647
86648   c = memcmp(pReader->term.pData, pTerm, n);
86649   if( c!=0 ) return c;
86650   if( isPrefix && n==nTerm ) return 0;
86651   return pReader->term.nData - nTerm;
86652 }
86653
86654
86655 /****************************************************************/
86656 /* LeavesReader wraps LeafReader to allow iterating over the entire
86657 ** leaf layer of the tree.
86658 */
86659 typedef struct LeavesReader {
86660   int idx;                  /* Index within the segment. */
86661
86662   sqlite3_stmt *pStmt;      /* Statement we're streaming leaves from. */
86663   int eof;                  /* we've seen SQLITE_DONE from pStmt. */
86664
86665   LeafReader leafReader;    /* reader for the current leaf. */
86666   DataBuffer rootData;      /* root data for inline. */
86667 } LeavesReader;
86668
86669 /* Access the current term. */
86670 static int leavesReaderTermBytes(LeavesReader *pReader){
86671   assert( !pReader->eof );
86672   return leafReaderTermBytes(&pReader->leafReader);
86673 }
86674 static const char *leavesReaderTerm(LeavesReader *pReader){
86675   assert( !pReader->eof );
86676   return leafReaderTerm(&pReader->leafReader);
86677 }
86678
86679 /* Access the doclist data for the current term. */
86680 static int leavesReaderDataBytes(LeavesReader *pReader){
86681   assert( !pReader->eof );
86682   return leafReaderDataBytes(&pReader->leafReader);
86683 }
86684 static const char *leavesReaderData(LeavesReader *pReader){
86685   assert( !pReader->eof );
86686   return leafReaderData(&pReader->leafReader);
86687 }
86688
86689 static int leavesReaderAtEnd(LeavesReader *pReader){
86690   return pReader->eof;
86691 }
86692
86693 /* loadSegmentLeaves() may not read all the way to SQLITE_DONE, thus
86694 ** leaving the statement handle open, which locks the table.
86695 */
86696 /* TODO(shess) This "solution" is not satisfactory.  Really, there
86697 ** should be check-in function for all statement handles which
86698 ** arranges to call sqlite3_reset().  This most likely will require
86699 ** modification to control flow all over the place, though, so for now
86700 ** just punt.
86701 **
86702 ** Note the the current system assumes that segment merges will run to
86703 ** completion, which is why this particular probably hasn't arisen in
86704 ** this case.  Probably a brittle assumption.
86705 */
86706 static int leavesReaderReset(LeavesReader *pReader){
86707   return sqlite3_reset(pReader->pStmt);
86708 }
86709
86710 static void leavesReaderDestroy(LeavesReader *pReader){
86711   leafReaderDestroy(&pReader->leafReader);
86712   dataBufferDestroy(&pReader->rootData);
86713   SCRAMBLE(pReader);
86714 }
86715
86716 /* Initialize pReader with the given root data (if iStartBlockid==0
86717 ** the leaf data was entirely contained in the root), or from the
86718 ** stream of blocks between iStartBlockid and iEndBlockid, inclusive.
86719 */
86720 static int leavesReaderInit(fulltext_vtab *v,
86721                             int idx,
86722                             sqlite_int64 iStartBlockid,
86723                             sqlite_int64 iEndBlockid,
86724                             const char *pRootData, int nRootData,
86725                             LeavesReader *pReader){
86726   CLEAR(pReader);
86727   pReader->idx = idx;
86728
86729   dataBufferInit(&pReader->rootData, 0);
86730   if( iStartBlockid==0 ){
86731     /* Entire leaf level fit in root data. */
86732     dataBufferReplace(&pReader->rootData, pRootData, nRootData);
86733     leafReaderInit(pReader->rootData.pData, pReader->rootData.nData,
86734                    &pReader->leafReader);
86735   }else{
86736     sqlite3_stmt *s;
86737     int rc = sql_get_leaf_statement(v, idx, &s);
86738     if( rc!=SQLITE_OK ) return rc;
86739
86740     rc = sqlite3_bind_int64(s, 1, iStartBlockid);
86741     if( rc!=SQLITE_OK ) return rc;
86742
86743     rc = sqlite3_bind_int64(s, 2, iEndBlockid);
86744     if( rc!=SQLITE_OK ) return rc;
86745
86746     rc = sqlite3_step(s);
86747     if( rc==SQLITE_DONE ){
86748       pReader->eof = 1;
86749       return SQLITE_OK;
86750     }
86751     if( rc!=SQLITE_ROW ) return rc;
86752
86753     pReader->pStmt = s;
86754     leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
86755                    sqlite3_column_bytes(pReader->pStmt, 0),
86756                    &pReader->leafReader);
86757   }
86758   return SQLITE_OK;
86759 }
86760
86761 /* Step the current leaf forward to the next term.  If we reach the
86762 ** end of the current leaf, step forward to the next leaf block.
86763 */
86764 static int leavesReaderStep(fulltext_vtab *v, LeavesReader *pReader){
86765   assert( !leavesReaderAtEnd(pReader) );
86766   leafReaderStep(&pReader->leafReader);
86767
86768   if( leafReaderAtEnd(&pReader->leafReader) ){
86769     int rc;
86770     if( pReader->rootData.pData ){
86771       pReader->eof = 1;
86772       return SQLITE_OK;
86773     }
86774     rc = sqlite3_step(pReader->pStmt);
86775     if( rc!=SQLITE_ROW ){
86776       pReader->eof = 1;
86777       return rc==SQLITE_DONE ? SQLITE_OK : rc;
86778     }
86779     leafReaderDestroy(&pReader->leafReader);
86780     leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
86781                    sqlite3_column_bytes(pReader->pStmt, 0),
86782                    &pReader->leafReader);
86783   }
86784   return SQLITE_OK;
86785 }
86786
86787 /* Order LeavesReaders by their term, ignoring idx.  Readers at eof
86788 ** always sort to the end.
86789 */
86790 static int leavesReaderTermCmp(LeavesReader *lr1, LeavesReader *lr2){
86791   if( leavesReaderAtEnd(lr1) ){
86792     if( leavesReaderAtEnd(lr2) ) return 0;
86793     return 1;
86794   }
86795   if( leavesReaderAtEnd(lr2) ) return -1;
86796
86797   return leafReaderTermCmp(&lr1->leafReader,
86798                            leavesReaderTerm(lr2), leavesReaderTermBytes(lr2),
86799                            0);
86800 }
86801
86802 /* Similar to leavesReaderTermCmp(), with additional ordering by idx
86803 ** so that older segments sort before newer segments.
86804 */
86805 static int leavesReaderCmp(LeavesReader *lr1, LeavesReader *lr2){
86806   int c = leavesReaderTermCmp(lr1, lr2);
86807   if( c!=0 ) return c;
86808   return lr1->idx-lr2->idx;
86809 }
86810
86811 /* Assume that pLr[1]..pLr[nLr] are sorted.  Bubble pLr[0] into its
86812 ** sorted position.
86813 */
86814 static void leavesReaderReorder(LeavesReader *pLr, int nLr){
86815   while( nLr>1 && leavesReaderCmp(pLr, pLr+1)>0 ){
86816     LeavesReader tmp = pLr[0];
86817     pLr[0] = pLr[1];
86818     pLr[1] = tmp;
86819     nLr--;
86820     pLr++;
86821   }
86822 }
86823
86824 /* Initializes pReaders with the segments from level iLevel, returning
86825 ** the number of segments in *piReaders.  Leaves pReaders in sorted
86826 ** order.
86827 */
86828 static int leavesReadersInit(fulltext_vtab *v, int iLevel,
86829                              LeavesReader *pReaders, int *piReaders){
86830   sqlite3_stmt *s;
86831   int i, rc = sql_get_statement(v, SEGDIR_SELECT_STMT, &s);
86832   if( rc!=SQLITE_OK ) return rc;
86833
86834   rc = sqlite3_bind_int(s, 1, iLevel);
86835   if( rc!=SQLITE_OK ) return rc;
86836
86837   i = 0;
86838   while( (rc = sqlite3_step(s))==SQLITE_ROW ){
86839     sqlite_int64 iStart = sqlite3_column_int64(s, 0);
86840     sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
86841     const char *pRootData = sqlite3_column_blob(s, 2);
86842     int nRootData = sqlite3_column_bytes(s, 2);
86843
86844     assert( i<MERGE_COUNT );
86845     rc = leavesReaderInit(v, i, iStart, iEnd, pRootData, nRootData,
86846                           &pReaders[i]);
86847     if( rc!=SQLITE_OK ) break;
86848
86849     i++;
86850   }
86851   if( rc!=SQLITE_DONE ){
86852     while( i-->0 ){
86853       leavesReaderDestroy(&pReaders[i]);
86854     }
86855     return rc;
86856   }
86857
86858   *piReaders = i;
86859
86860   /* Leave our results sorted by term, then age. */
86861   while( i-- ){
86862     leavesReaderReorder(pReaders+i, *piReaders-i);
86863   }
86864   return SQLITE_OK;
86865 }
86866
86867 /* Merge doclists from pReaders[nReaders] into a single doclist, which
86868 ** is written to pWriter.  Assumes pReaders is ordered oldest to
86869 ** newest.
86870 */
86871 /* TODO(shess) Consider putting this inline in segmentMerge(). */
86872 static int leavesReadersMerge(fulltext_vtab *v,
86873                               LeavesReader *pReaders, int nReaders,
86874                               LeafWriter *pWriter){
86875   DLReader dlReaders[MERGE_COUNT];
86876   const char *pTerm = leavesReaderTerm(pReaders);
86877   int i, nTerm = leavesReaderTermBytes(pReaders);
86878
86879   assert( nReaders<=MERGE_COUNT );
86880
86881   for(i=0; i<nReaders; i++){
86882     dlrInit(&dlReaders[i], DL_DEFAULT,
86883             leavesReaderData(pReaders+i),
86884             leavesReaderDataBytes(pReaders+i));
86885   }
86886
86887   return leafWriterStepMerge(v, pWriter, pTerm, nTerm, dlReaders, nReaders);
86888 }
86889
86890 /* Forward ref due to mutual recursion with segdirNextIndex(). */
86891 static int segmentMerge(fulltext_vtab *v, int iLevel);
86892
86893 /* Put the next available index at iLevel into *pidx.  If iLevel
86894 ** already has MERGE_COUNT segments, they are merged to a higher
86895 ** level to make room.
86896 */
86897 static int segdirNextIndex(fulltext_vtab *v, int iLevel, int *pidx){
86898   int rc = segdir_max_index(v, iLevel, pidx);
86899   if( rc==SQLITE_DONE ){              /* No segments at iLevel. */
86900     *pidx = 0;
86901   }else if( rc==SQLITE_ROW ){
86902     if( *pidx==(MERGE_COUNT-1) ){
86903       rc = segmentMerge(v, iLevel);
86904       if( rc!=SQLITE_OK ) return rc;
86905       *pidx = 0;
86906     }else{
86907       (*pidx)++;
86908     }
86909   }else{
86910     return rc;
86911   }
86912   return SQLITE_OK;
86913 }
86914
86915 /* Merge MERGE_COUNT segments at iLevel into a new segment at
86916 ** iLevel+1.  If iLevel+1 is already full of segments, those will be
86917 ** merged to make room.
86918 */
86919 static int segmentMerge(fulltext_vtab *v, int iLevel){
86920   LeafWriter writer;
86921   LeavesReader lrs[MERGE_COUNT];
86922   int i, rc, idx = 0;
86923
86924   /* Determine the next available segment index at the next level,
86925   ** merging as necessary.
86926   */
86927   rc = segdirNextIndex(v, iLevel+1, &idx);
86928   if( rc!=SQLITE_OK ) return rc;
86929
86930   /* TODO(shess) This assumes that we'll always see exactly
86931   ** MERGE_COUNT segments to merge at a given level.  That will be
86932   ** broken if we allow the developer to request preemptive or
86933   ** deferred merging.
86934   */
86935   memset(&lrs, '\0', sizeof(lrs));
86936   rc = leavesReadersInit(v, iLevel, lrs, &i);
86937   if( rc!=SQLITE_OK ) return rc;
86938   assert( i==MERGE_COUNT );
86939
86940   leafWriterInit(iLevel+1, idx, &writer);
86941
86942   /* Since leavesReaderReorder() pushes readers at eof to the end,
86943   ** when the first reader is empty, all will be empty.
86944   */
86945   while( !leavesReaderAtEnd(lrs) ){
86946     /* Figure out how many readers share their next term. */
86947     for(i=1; i<MERGE_COUNT && !leavesReaderAtEnd(lrs+i); i++){
86948       if( 0!=leavesReaderTermCmp(lrs, lrs+i) ) break;
86949     }
86950
86951     rc = leavesReadersMerge(v, lrs, i, &writer);
86952     if( rc!=SQLITE_OK ) goto err;
86953
86954     /* Step forward those that were merged. */
86955     while( i-->0 ){
86956       rc = leavesReaderStep(v, lrs+i);
86957       if( rc!=SQLITE_OK ) goto err;
86958
86959       /* Reorder by term, then by age. */
86960       leavesReaderReorder(lrs+i, MERGE_COUNT-i);
86961     }
86962   }
86963
86964   for(i=0; i<MERGE_COUNT; i++){
86965     leavesReaderDestroy(&lrs[i]);
86966   }
86967
86968   rc = leafWriterFinalize(v, &writer);
86969   leafWriterDestroy(&writer);
86970   if( rc!=SQLITE_OK ) return rc;
86971
86972   /* Delete the merged segment data. */
86973   return segdir_delete(v, iLevel);
86974
86975  err:
86976   for(i=0; i<MERGE_COUNT; i++){
86977     leavesReaderDestroy(&lrs[i]);
86978   }
86979   leafWriterDestroy(&writer);
86980   return rc;
86981 }
86982
86983 /* Accumulate the union of *acc and *pData into *acc. */
86984 static void docListAccumulateUnion(DataBuffer *acc,
86985                                    const char *pData, int nData) {
86986   DataBuffer tmp = *acc;
86987   dataBufferInit(acc, tmp.nData+nData);
86988   docListUnion(tmp.pData, tmp.nData, pData, nData, acc);
86989   dataBufferDestroy(&tmp);
86990 }
86991
86992 /* TODO(shess) It might be interesting to explore different merge
86993 ** strategies, here.  For instance, since this is a sorted merge, we
86994 ** could easily merge many doclists in parallel.  With some
86995 ** comprehension of the storage format, we could merge all of the
86996 ** doclists within a leaf node directly from the leaf node's storage.
86997 ** It may be worthwhile to merge smaller doclists before larger
86998 ** doclists, since they can be traversed more quickly - but the
86999 ** results may have less overlap, making them more expensive in a
87000 ** different way.
87001 */
87002
87003 /* Scan pReader for pTerm/nTerm, and merge the term's doclist over
87004 ** *out (any doclists with duplicate docids overwrite those in *out).
87005 ** Internal function for loadSegmentLeaf().
87006 */
87007 static int loadSegmentLeavesInt(fulltext_vtab *v, LeavesReader *pReader,
87008                                 const char *pTerm, int nTerm, int isPrefix,
87009                                 DataBuffer *out){
87010   /* doclist data is accumulated into pBuffers similar to how one does
87011   ** increment in binary arithmetic.  If index 0 is empty, the data is
87012   ** stored there.  If there is data there, it is merged and the
87013   ** results carried into position 1, with further merge-and-carry
87014   ** until an empty position is found.
87015   */
87016   DataBuffer *pBuffers = NULL;
87017   int nBuffers = 0, nMaxBuffers = 0, rc;
87018
87019   assert( nTerm>0 );
87020
87021   for(rc=SQLITE_OK; rc==SQLITE_OK && !leavesReaderAtEnd(pReader);
87022       rc=leavesReaderStep(v, pReader)){
87023     /* TODO(shess) Really want leavesReaderTermCmp(), but that name is
87024     ** already taken to compare the terms of two LeavesReaders.  Think
87025     ** on a better name.  [Meanwhile, break encapsulation rather than
87026     ** use a confusing name.]
87027     */
87028     int c = leafReaderTermCmp(&pReader->leafReader, pTerm, nTerm, isPrefix);
87029     if( c>0 ) break;      /* Past any possible matches. */
87030     if( c==0 ){
87031       const char *pData = leavesReaderData(pReader);
87032       int iBuffer, nData = leavesReaderDataBytes(pReader);
87033
87034       /* Find the first empty buffer. */
87035       for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
87036         if( 0==pBuffers[iBuffer].nData ) break;
87037       }
87038
87039       /* Out of buffers, add an empty one. */
87040       if( iBuffer==nBuffers ){
87041         if( nBuffers==nMaxBuffers ){
87042           DataBuffer *p;
87043           nMaxBuffers += 20;
87044
87045           /* Manual realloc so we can handle NULL appropriately. */
87046           p = sqlite3_malloc(nMaxBuffers*sizeof(*pBuffers));
87047           if( p==NULL ){
87048             rc = SQLITE_NOMEM;
87049             break;
87050           }
87051
87052           if( nBuffers>0 ){
87053             assert(pBuffers!=NULL);
87054             memcpy(p, pBuffers, nBuffers*sizeof(*pBuffers));
87055             sqlite3_free(pBuffers);
87056           }
87057           pBuffers = p;
87058         }
87059         dataBufferInit(&(pBuffers[nBuffers]), 0);
87060         nBuffers++;
87061       }
87062
87063       /* At this point, must have an empty at iBuffer. */
87064       assert(iBuffer<nBuffers && pBuffers[iBuffer].nData==0);
87065
87066       /* If empty was first buffer, no need for merge logic. */
87067       if( iBuffer==0 ){
87068         dataBufferReplace(&(pBuffers[0]), pData, nData);
87069       }else{
87070         /* pAcc is the empty buffer the merged data will end up in. */
87071         DataBuffer *pAcc = &(pBuffers[iBuffer]);
87072         DataBuffer *p = &(pBuffers[0]);
87073
87074         /* Handle position 0 specially to avoid need to prime pAcc
87075         ** with pData/nData.
87076         */
87077         dataBufferSwap(p, pAcc);
87078         docListAccumulateUnion(pAcc, pData, nData);
87079
87080         /* Accumulate remaining doclists into pAcc. */
87081         for(++p; p<pAcc; ++p){
87082           docListAccumulateUnion(pAcc, p->pData, p->nData);
87083
87084           /* dataBufferReset() could allow a large doclist to blow up
87085           ** our memory requirements.
87086           */
87087           if( p->nCapacity<1024 ){
87088             dataBufferReset(p);
87089           }else{
87090             dataBufferDestroy(p);
87091             dataBufferInit(p, 0);
87092           }
87093         }
87094       }
87095     }
87096   }
87097
87098   /* Union all the doclists together into *out. */
87099   /* TODO(shess) What if *out is big?  Sigh. */
87100   if( rc==SQLITE_OK && nBuffers>0 ){
87101     int iBuffer;
87102     for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
87103       if( pBuffers[iBuffer].nData>0 ){
87104         if( out->nData==0 ){
87105           dataBufferSwap(out, &(pBuffers[iBuffer]));
87106         }else{
87107           docListAccumulateUnion(out, pBuffers[iBuffer].pData,
87108                                  pBuffers[iBuffer].nData);
87109         }
87110       }
87111     }
87112   }
87113
87114   while( nBuffers-- ){
87115     dataBufferDestroy(&(pBuffers[nBuffers]));
87116   }
87117   if( pBuffers!=NULL ) sqlite3_free(pBuffers);
87118
87119   return rc;
87120 }
87121
87122 /* Call loadSegmentLeavesInt() with pData/nData as input. */
87123 static int loadSegmentLeaf(fulltext_vtab *v, const char *pData, int nData,
87124                            const char *pTerm, int nTerm, int isPrefix,
87125                            DataBuffer *out){
87126   LeavesReader reader;
87127   int rc;
87128
87129   assert( nData>1 );
87130   assert( *pData=='\0' );
87131   rc = leavesReaderInit(v, 0, 0, 0, pData, nData, &reader);
87132   if( rc!=SQLITE_OK ) return rc;
87133
87134   rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
87135   leavesReaderReset(&reader);
87136   leavesReaderDestroy(&reader);
87137   return rc;
87138 }
87139
87140 /* Call loadSegmentLeavesInt() with the leaf nodes from iStartLeaf to
87141 ** iEndLeaf (inclusive) as input, and merge the resulting doclist into
87142 ** out.
87143 */
87144 static int loadSegmentLeaves(fulltext_vtab *v,
87145                              sqlite_int64 iStartLeaf, sqlite_int64 iEndLeaf,
87146                              const char *pTerm, int nTerm, int isPrefix,
87147                              DataBuffer *out){
87148   int rc;
87149   LeavesReader reader;
87150
87151   assert( iStartLeaf<=iEndLeaf );
87152   rc = leavesReaderInit(v, 0, iStartLeaf, iEndLeaf, NULL, 0, &reader);
87153   if( rc!=SQLITE_OK ) return rc;
87154
87155   rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
87156   leavesReaderReset(&reader);
87157   leavesReaderDestroy(&reader);
87158   return rc;
87159 }
87160
87161 /* Taking pData/nData as an interior node, find the sequence of child
87162 ** nodes which could include pTerm/nTerm/isPrefix.  Note that the
87163 ** interior node terms logically come between the blocks, so there is
87164 ** one more blockid than there are terms (that block contains terms >=
87165 ** the last interior-node term).
87166 */
87167 /* TODO(shess) The calling code may already know that the end child is
87168 ** not worth calculating, because the end may be in a later sibling
87169 ** node.  Consider whether breaking symmetry is worthwhile.  I suspect
87170 ** it is not worthwhile.
87171 */
87172 static void getChildrenContaining(const char *pData, int nData,
87173                                   const char *pTerm, int nTerm, int isPrefix,
87174                                   sqlite_int64 *piStartChild,
87175                                   sqlite_int64 *piEndChild){
87176   InteriorReader reader;
87177
87178   assert( nData>1 );
87179   assert( *pData!='\0' );
87180   interiorReaderInit(pData, nData, &reader);
87181
87182   /* Scan for the first child which could contain pTerm/nTerm. */
87183   while( !interiorReaderAtEnd(&reader) ){
87184     if( interiorReaderTermCmp(&reader, pTerm, nTerm, 0)>0 ) break;
87185     interiorReaderStep(&reader);
87186   }
87187   *piStartChild = interiorReaderCurrentBlockid(&reader);
87188
87189   /* Keep scanning to find a term greater than our term, using prefix
87190   ** comparison if indicated.  If isPrefix is false, this will be the
87191   ** same blockid as the starting block.
87192   */
87193   while( !interiorReaderAtEnd(&reader) ){
87194     if( interiorReaderTermCmp(&reader, pTerm, nTerm, isPrefix)>0 ) break;
87195     interiorReaderStep(&reader);
87196   }
87197   *piEndChild = interiorReaderCurrentBlockid(&reader);
87198
87199   interiorReaderDestroy(&reader);
87200
87201   /* Children must ascend, and if !prefix, both must be the same. */
87202   assert( *piEndChild>=*piStartChild );
87203   assert( isPrefix || *piStartChild==*piEndChild );
87204 }
87205
87206 /* Read block at iBlockid and pass it with other params to
87207 ** getChildrenContaining().
87208 */
87209 static int loadAndGetChildrenContaining(
87210   fulltext_vtab *v,
87211   sqlite_int64 iBlockid,
87212   const char *pTerm, int nTerm, int isPrefix,
87213   sqlite_int64 *piStartChild, sqlite_int64 *piEndChild
87214 ){
87215   sqlite3_stmt *s = NULL;
87216   int rc;
87217
87218   assert( iBlockid!=0 );
87219   assert( pTerm!=NULL );
87220   assert( nTerm!=0 );        /* TODO(shess) Why not allow this? */
87221   assert( piStartChild!=NULL );
87222   assert( piEndChild!=NULL );
87223
87224   rc = sql_get_statement(v, BLOCK_SELECT_STMT, &s);
87225   if( rc!=SQLITE_OK ) return rc;
87226
87227   rc = sqlite3_bind_int64(s, 1, iBlockid);
87228   if( rc!=SQLITE_OK ) return rc;
87229
87230   rc = sqlite3_step(s);
87231   if( rc==SQLITE_DONE ) return SQLITE_ERROR;
87232   if( rc!=SQLITE_ROW ) return rc;
87233
87234   getChildrenContaining(sqlite3_column_blob(s, 0), sqlite3_column_bytes(s, 0),
87235                         pTerm, nTerm, isPrefix, piStartChild, piEndChild);
87236
87237   /* We expect only one row.  We must execute another sqlite3_step()
87238    * to complete the iteration; otherwise the table will remain
87239    * locked. */
87240   rc = sqlite3_step(s);
87241   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
87242   if( rc!=SQLITE_DONE ) return rc;
87243
87244   return SQLITE_OK;
87245 }
87246
87247 /* Traverse the tree represented by pData[nData] looking for
87248 ** pTerm[nTerm], placing its doclist into *out.  This is internal to
87249 ** loadSegment() to make error-handling cleaner.
87250 */
87251 static int loadSegmentInt(fulltext_vtab *v, const char *pData, int nData,
87252                           sqlite_int64 iLeavesEnd,
87253                           const char *pTerm, int nTerm, int isPrefix,
87254                           DataBuffer *out){
87255   /* Special case where root is a leaf. */
87256   if( *pData=='\0' ){
87257     return loadSegmentLeaf(v, pData, nData, pTerm, nTerm, isPrefix, out);
87258   }else{
87259     int rc;
87260     sqlite_int64 iStartChild, iEndChild;
87261
87262     /* Process pData as an interior node, then loop down the tree
87263     ** until we find the set of leaf nodes to scan for the term.
87264     */
87265     getChildrenContaining(pData, nData, pTerm, nTerm, isPrefix,
87266                           &iStartChild, &iEndChild);
87267     while( iStartChild>iLeavesEnd ){
87268       sqlite_int64 iNextStart, iNextEnd;
87269       rc = loadAndGetChildrenContaining(v, iStartChild, pTerm, nTerm, isPrefix,
87270                                         &iNextStart, &iNextEnd);
87271       if( rc!=SQLITE_OK ) return rc;
87272
87273       /* If we've branched, follow the end branch, too. */
87274       if( iStartChild!=iEndChild ){
87275         sqlite_int64 iDummy;
87276         rc = loadAndGetChildrenContaining(v, iEndChild, pTerm, nTerm, isPrefix,
87277                                           &iDummy, &iNextEnd);
87278         if( rc!=SQLITE_OK ) return rc;
87279       }
87280
87281       assert( iNextStart<=iNextEnd );
87282       iStartChild = iNextStart;
87283       iEndChild = iNextEnd;
87284     }
87285     assert( iStartChild<=iLeavesEnd );
87286     assert( iEndChild<=iLeavesEnd );
87287
87288     /* Scan through the leaf segments for doclists. */
87289     return loadSegmentLeaves(v, iStartChild, iEndChild,
87290                              pTerm, nTerm, isPrefix, out);
87291   }
87292 }
87293
87294 /* Call loadSegmentInt() to collect the doclist for pTerm/nTerm, then
87295 ** merge its doclist over *out (any duplicate doclists read from the
87296 ** segment rooted at pData will overwrite those in *out).
87297 */
87298 /* TODO(shess) Consider changing this to determine the depth of the
87299 ** leaves using either the first characters of interior nodes (when
87300 ** ==1, we're one level above the leaves), or the first character of
87301 ** the root (which will describe the height of the tree directly).
87302 ** Either feels somewhat tricky to me.
87303 */
87304 /* TODO(shess) The current merge is likely to be slow for large
87305 ** doclists (though it should process from newest/smallest to
87306 ** oldest/largest, so it may not be that bad).  It might be useful to
87307 ** modify things to allow for N-way merging.  This could either be
87308 ** within a segment, with pairwise merges across segments, or across
87309 ** all segments at once.
87310 */
87311 static int loadSegment(fulltext_vtab *v, const char *pData, int nData,
87312                        sqlite_int64 iLeavesEnd,
87313                        const char *pTerm, int nTerm, int isPrefix,
87314                        DataBuffer *out){
87315   DataBuffer result;
87316   int rc;
87317
87318   assert( nData>1 );
87319
87320   /* This code should never be called with buffered updates. */
87321   assert( v->nPendingData<0 );
87322
87323   dataBufferInit(&result, 0);
87324   rc = loadSegmentInt(v, pData, nData, iLeavesEnd,
87325                       pTerm, nTerm, isPrefix, &result);
87326   if( rc==SQLITE_OK && result.nData>0 ){
87327     if( out->nData==0 ){
87328       DataBuffer tmp = *out;
87329       *out = result;
87330       result = tmp;
87331     }else{
87332       DataBuffer merged;
87333       DLReader readers[2];
87334
87335       dlrInit(&readers[0], DL_DEFAULT, out->pData, out->nData);
87336       dlrInit(&readers[1], DL_DEFAULT, result.pData, result.nData);
87337       dataBufferInit(&merged, out->nData+result.nData);
87338       docListMerge(&merged, readers, 2);
87339       dataBufferDestroy(out);
87340       *out = merged;
87341       dlrDestroy(&readers[0]);
87342       dlrDestroy(&readers[1]);
87343     }
87344   }
87345   dataBufferDestroy(&result);
87346   return rc;
87347 }
87348
87349 /* Scan the database and merge together the posting lists for the term
87350 ** into *out.
87351 */
87352 static int termSelect(fulltext_vtab *v, int iColumn,
87353                       const char *pTerm, int nTerm, int isPrefix,
87354                       DocListType iType, DataBuffer *out){
87355   DataBuffer doclist;
87356   sqlite3_stmt *s;
87357   int rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
87358   if( rc!=SQLITE_OK ) return rc;
87359
87360   /* This code should never be called with buffered updates. */
87361   assert( v->nPendingData<0 );
87362
87363   dataBufferInit(&doclist, 0);
87364
87365   /* Traverse the segments from oldest to newest so that newer doclist
87366   ** elements for given docids overwrite older elements.
87367   */
87368   while( (rc = sqlite3_step(s))==SQLITE_ROW ){
87369     const char *pData = sqlite3_column_blob(s, 0);
87370     const int nData = sqlite3_column_bytes(s, 0);
87371     const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
87372     rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, isPrefix,
87373                      &doclist);
87374     if( rc!=SQLITE_OK ) goto err;
87375   }
87376   if( rc==SQLITE_DONE ){
87377     if( doclist.nData!=0 ){
87378       /* TODO(shess) The old term_select_all() code applied the column
87379       ** restrict as we merged segments, leading to smaller buffers.
87380       ** This is probably worthwhile to bring back, once the new storage
87381       ** system is checked in.
87382       */
87383       if( iColumn==v->nColumn) iColumn = -1;
87384       docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
87385                   iColumn, iType, out);
87386     }
87387     rc = SQLITE_OK;
87388   }
87389
87390  err:
87391   dataBufferDestroy(&doclist);
87392   return rc;
87393 }
87394
87395 /****************************************************************/
87396 /* Used to hold hashtable data for sorting. */
87397 typedef struct TermData {
87398   const char *pTerm;
87399   int nTerm;
87400   DLCollector *pCollector;
87401 } TermData;
87402
87403 /* Orders TermData elements in strcmp fashion ( <0 for less-than, 0
87404 ** for equal, >0 for greater-than).
87405 */
87406 static int termDataCmp(const void *av, const void *bv){
87407   const TermData *a = (const TermData *)av;
87408   const TermData *b = (const TermData *)bv;
87409   int n = a->nTerm<b->nTerm ? a->nTerm : b->nTerm;
87410   int c = memcmp(a->pTerm, b->pTerm, n);
87411   if( c!=0 ) return c;
87412   return a->nTerm-b->nTerm;
87413 }
87414
87415 /* Order pTerms data by term, then write a new level 0 segment using
87416 ** LeafWriter.
87417 */
87418 static int writeZeroSegment(fulltext_vtab *v, fts3Hash *pTerms){
87419   fts3HashElem *e;
87420   int idx, rc, i, n;
87421   TermData *pData;
87422   LeafWriter writer;
87423   DataBuffer dl;
87424
87425   /* Determine the next index at level 0, merging as necessary. */
87426   rc = segdirNextIndex(v, 0, &idx);
87427   if( rc!=SQLITE_OK ) return rc;
87428
87429   n = fts3HashCount(pTerms);
87430   pData = sqlite3_malloc(n*sizeof(TermData));
87431
87432   for(i = 0, e = fts3HashFirst(pTerms); e; i++, e = fts3HashNext(e)){
87433     assert( i<n );
87434     pData[i].pTerm = fts3HashKey(e);
87435     pData[i].nTerm = fts3HashKeysize(e);
87436     pData[i].pCollector = fts3HashData(e);
87437   }
87438   assert( i==n );
87439
87440   /* TODO(shess) Should we allow user-defined collation sequences,
87441   ** here?  I think we only need that once we support prefix searches.
87442   */
87443   if( n>1 ) qsort(pData, n, sizeof(*pData), termDataCmp);
87444
87445   /* TODO(shess) Refactor so that we can write directly to the segment
87446   ** DataBuffer, as happens for segment merges.
87447   */
87448   leafWriterInit(0, idx, &writer);
87449   dataBufferInit(&dl, 0);
87450   for(i=0; i<n; i++){
87451     dataBufferReset(&dl);
87452     dlcAddDoclist(pData[i].pCollector, &dl);
87453     rc = leafWriterStep(v, &writer,
87454                         pData[i].pTerm, pData[i].nTerm, dl.pData, dl.nData);
87455     if( rc!=SQLITE_OK ) goto err;
87456   }
87457   rc = leafWriterFinalize(v, &writer);
87458
87459  err:
87460   dataBufferDestroy(&dl);
87461   sqlite3_free(pData);
87462   leafWriterDestroy(&writer);
87463   return rc;
87464 }
87465
87466 /* If pendingTerms has data, free it. */
87467 static int clearPendingTerms(fulltext_vtab *v){
87468   if( v->nPendingData>=0 ){
87469     fts3HashElem *e;
87470     for(e=fts3HashFirst(&v->pendingTerms); e; e=fts3HashNext(e)){
87471       dlcDelete(fts3HashData(e));
87472     }
87473     fts3HashClear(&v->pendingTerms);
87474     v->nPendingData = -1;
87475   }
87476   return SQLITE_OK;
87477 }
87478
87479 /* If pendingTerms has data, flush it to a level-zero segment, and
87480 ** free it.
87481 */
87482 static int flushPendingTerms(fulltext_vtab *v){
87483   if( v->nPendingData>=0 ){
87484     int rc = writeZeroSegment(v, &v->pendingTerms);
87485     if( rc==SQLITE_OK ) clearPendingTerms(v);
87486     return rc;
87487   }
87488   return SQLITE_OK;
87489 }
87490
87491 /* If pendingTerms is "too big", or docid is out of order, flush it.
87492 ** Regardless, be certain that pendingTerms is initialized for use.
87493 */
87494 static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid){
87495   /* TODO(shess) Explore whether partially flushing the buffer on
87496   ** forced-flush would provide better performance.  I suspect that if
87497   ** we ordered the doclists by size and flushed the largest until the
87498   ** buffer was half empty, that would let the less frequent terms
87499   ** generate longer doclists.
87500   */
87501   if( iDocid<=v->iPrevDocid || v->nPendingData>kPendingThreshold ){
87502     int rc = flushPendingTerms(v);
87503     if( rc!=SQLITE_OK ) return rc;
87504   }
87505   if( v->nPendingData<0 ){
87506     fts3HashInit(&v->pendingTerms, FTS3_HASH_STRING, 1);
87507     v->nPendingData = 0;
87508   }
87509   v->iPrevDocid = iDocid;
87510   return SQLITE_OK;
87511 }
87512
87513 /* This function implements the xUpdate callback; it is the top-level entry
87514  * point for inserting, deleting or updating a row in a full-text table. */
87515 static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg,
87516                           sqlite_int64 *pRowid){
87517   fulltext_vtab *v = (fulltext_vtab *) pVtab;
87518   int rc;
87519
87520   FTSTRACE(("FTS3 Update %p\n", pVtab));
87521
87522   if( nArg<2 ){
87523     rc = index_delete(v, sqlite3_value_int64(ppArg[0]));
87524   } else if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){
87525     /* An update:
87526      * ppArg[0] = old rowid
87527      * ppArg[1] = new rowid
87528      * ppArg[2..2+v->nColumn-1] = values
87529      * ppArg[2+v->nColumn] = value for magic column (we ignore this)
87530      * ppArg[2+v->nColumn+1] = value for docid
87531      */
87532     sqlite_int64 rowid = sqlite3_value_int64(ppArg[0]);
87533     if( sqlite3_value_type(ppArg[1]) != SQLITE_INTEGER ||
87534         sqlite3_value_int64(ppArg[1]) != rowid ){
87535       rc = SQLITE_ERROR;  /* we don't allow changing the rowid */
87536     }else if( sqlite3_value_type(ppArg[2+v->nColumn+1]) != SQLITE_INTEGER ||
87537               sqlite3_value_int64(ppArg[2+v->nColumn+1]) != rowid ){
87538       rc = SQLITE_ERROR;  /* we don't allow changing the docid */
87539     }else{
87540       assert( nArg==2+v->nColumn+2);
87541       rc = index_update(v, rowid, &ppArg[2]);
87542     }
87543   } else {
87544     /* An insert:
87545      * ppArg[1] = requested rowid
87546      * ppArg[2..2+v->nColumn-1] = values
87547      * ppArg[2+v->nColumn] = value for magic column (we ignore this)
87548      * ppArg[2+v->nColumn+1] = value for docid
87549      */
87550     sqlite3_value *pRequestDocid = ppArg[2+v->nColumn+1];
87551     assert( nArg==2+v->nColumn+2);
87552     if( SQLITE_NULL != sqlite3_value_type(pRequestDocid) &&
87553         SQLITE_NULL != sqlite3_value_type(ppArg[1]) ){
87554       /* TODO(shess) Consider allowing this to work if the values are
87555       ** identical.  I'm inclined to discourage that usage, though,
87556       ** given that both rowid and docid are special columns.  Better
87557       ** would be to define one or the other as the default winner,
87558       ** but should it be fts3-centric (docid) or SQLite-centric
87559       ** (rowid)?
87560       */
87561       rc = SQLITE_ERROR;
87562     }else{
87563       if( SQLITE_NULL == sqlite3_value_type(pRequestDocid) ){
87564         pRequestDocid = ppArg[1];
87565       }
87566       rc = index_insert(v, pRequestDocid, &ppArg[2], pRowid);
87567     }
87568   }
87569
87570   return rc;
87571 }
87572
87573 static int fulltextSync(sqlite3_vtab *pVtab){
87574   FTSTRACE(("FTS3 xSync()\n"));
87575   return flushPendingTerms((fulltext_vtab *)pVtab);
87576 }
87577
87578 static int fulltextBegin(sqlite3_vtab *pVtab){
87579   fulltext_vtab *v = (fulltext_vtab *) pVtab;
87580   FTSTRACE(("FTS3 xBegin()\n"));
87581
87582   /* Any buffered updates should have been cleared by the previous
87583   ** transaction.
87584   */
87585   assert( v->nPendingData<0 );
87586   return clearPendingTerms(v);
87587 }
87588
87589 static int fulltextCommit(sqlite3_vtab *pVtab){
87590   fulltext_vtab *v = (fulltext_vtab *) pVtab;
87591   FTSTRACE(("FTS3 xCommit()\n"));
87592
87593   /* Buffered updates should have been cleared by fulltextSync(). */
87594   assert( v->nPendingData<0 );
87595   return clearPendingTerms(v);
87596 }
87597
87598 static int fulltextRollback(sqlite3_vtab *pVtab){
87599   FTSTRACE(("FTS3 xRollback()\n"));
87600   return clearPendingTerms((fulltext_vtab *)pVtab);
87601 }
87602
87603 /*
87604 ** Implementation of the snippet() function for FTS3
87605 */
87606 static void snippetFunc(
87607   sqlite3_context *pContext,
87608   int argc,
87609   sqlite3_value **argv
87610 ){
87611   fulltext_cursor *pCursor;
87612   if( argc<1 ) return;
87613   if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
87614       sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
87615     sqlite3_result_error(pContext, "illegal first argument to html_snippet",-1);
87616   }else{
87617     const char *zStart = "<b>";
87618     const char *zEnd = "</b>";
87619     const char *zEllipsis = "<b>...</b>";
87620     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
87621     if( argc>=2 ){
87622       zStart = (const char*)sqlite3_value_text(argv[1]);
87623       if( argc>=3 ){
87624         zEnd = (const char*)sqlite3_value_text(argv[2]);
87625         if( argc>=4 ){
87626           zEllipsis = (const char*)sqlite3_value_text(argv[3]);
87627         }
87628       }
87629     }
87630     snippetAllOffsets(pCursor);
87631     snippetText(pCursor, zStart, zEnd, zEllipsis);
87632     sqlite3_result_text(pContext, pCursor->snippet.zSnippet,
87633                         pCursor->snippet.nSnippet, SQLITE_STATIC);
87634   }
87635 }
87636
87637 /*
87638 ** Implementation of the offsets() function for FTS3
87639 */
87640 static void snippetOffsetsFunc(
87641   sqlite3_context *pContext,
87642   int argc,
87643   sqlite3_value **argv
87644 ){
87645   fulltext_cursor *pCursor;
87646   if( argc<1 ) return;
87647   if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
87648       sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
87649     sqlite3_result_error(pContext, "illegal first argument to offsets",-1);
87650   }else{
87651     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
87652     snippetAllOffsets(pCursor);
87653     snippetOffsetText(&pCursor->snippet);
87654     sqlite3_result_text(pContext,
87655                         pCursor->snippet.zOffset, pCursor->snippet.nOffset,
87656                         SQLITE_STATIC);
87657   }
87658 }
87659
87660 /*
87661 ** This routine implements the xFindFunction method for the FTS3
87662 ** virtual table.
87663 */
87664 static int fulltextFindFunction(
87665   sqlite3_vtab *pVtab,
87666   int nArg,
87667   const char *zName,
87668   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
87669   void **ppArg
87670 ){
87671   if( strcmp(zName,"snippet")==0 ){
87672     *pxFunc = snippetFunc;
87673     return 1;
87674   }else if( strcmp(zName,"offsets")==0 ){
87675     *pxFunc = snippetOffsetsFunc;
87676     return 1;
87677   }
87678   return 0;
87679 }
87680
87681 /*
87682 ** Rename an fts3 table.
87683 */
87684 static int fulltextRename(
87685   sqlite3_vtab *pVtab,
87686   const char *zName
87687 ){
87688   fulltext_vtab *p = (fulltext_vtab *)pVtab;
87689   int rc = SQLITE_NOMEM;
87690   char *zSql = sqlite3_mprintf(
87691     "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';"
87692     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';"
87693     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';"
87694     , p->zDb, p->zName, zName 
87695     , p->zDb, p->zName, zName 
87696     , p->zDb, p->zName, zName
87697   );
87698   if( zSql ){
87699     rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
87700     sqlite3_free(zSql);
87701   }
87702   return rc;
87703 }
87704
87705 static const sqlite3_module fts3Module = {
87706   /* iVersion      */ 0,
87707   /* xCreate       */ fulltextCreate,
87708   /* xConnect      */ fulltextConnect,
87709   /* xBestIndex    */ fulltextBestIndex,
87710   /* xDisconnect   */ fulltextDisconnect,
87711   /* xDestroy      */ fulltextDestroy,
87712   /* xOpen         */ fulltextOpen,
87713   /* xClose        */ fulltextClose,
87714   /* xFilter       */ fulltextFilter,
87715   /* xNext         */ fulltextNext,
87716   /* xEof          */ fulltextEof,
87717   /* xColumn       */ fulltextColumn,
87718   /* xRowid        */ fulltextRowid,
87719   /* xUpdate       */ fulltextUpdate,
87720   /* xBegin        */ fulltextBegin,
87721   /* xSync         */ fulltextSync,
87722   /* xCommit       */ fulltextCommit,
87723   /* xRollback     */ fulltextRollback,
87724   /* xFindFunction */ fulltextFindFunction,
87725   /* xRename */       fulltextRename,
87726 };
87727
87728 static void hashDestroy(void *p){
87729   fts3Hash *pHash = (fts3Hash *)p;
87730   sqlite3Fts3HashClear(pHash);
87731   sqlite3_free(pHash);
87732 }
87733
87734 /*
87735 ** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
87736 ** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
87737 ** two forward declarations are for functions declared in these files
87738 ** used to retrieve the respective implementations.
87739 **
87740 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
87741 ** to by the argument to point a the "simple" tokenizer implementation.
87742 ** Function ...PorterTokenizerModule() sets *pModule to point to the
87743 ** porter tokenizer/stemmer implementation.
87744 */
87745 void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
87746 void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
87747 void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
87748
87749 int sqlite3Fts3InitHashTable(sqlite3 *, fts3Hash *, const char *);
87750
87751 /*
87752 ** Initialise the fts3 extension. If this extension is built as part
87753 ** of the sqlite library, then this function is called directly by
87754 ** SQLite. If fts3 is built as a dynamically loadable extension, this
87755 ** function is called by the sqlite3_extension_init() entry point.
87756 */
87757 int sqlite3Fts3Init(sqlite3 *db){
87758   int rc = SQLITE_OK;
87759   fts3Hash *pHash = 0;
87760   const sqlite3_tokenizer_module *pSimple = 0;
87761   const sqlite3_tokenizer_module *pPorter = 0;
87762   const sqlite3_tokenizer_module *pIcu = 0;
87763
87764   sqlite3Fts3SimpleTokenizerModule(&pSimple);
87765   sqlite3Fts3PorterTokenizerModule(&pPorter);
87766 #ifdef SQLITE_ENABLE_ICU
87767   sqlite3Fts3IcuTokenizerModule(&pIcu);
87768 #endif
87769
87770   /* Allocate and initialise the hash-table used to store tokenizers. */
87771   pHash = sqlite3_malloc(sizeof(fts3Hash));
87772   if( !pHash ){
87773     rc = SQLITE_NOMEM;
87774   }else{
87775     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
87776   }
87777
87778   /* Load the built-in tokenizers into the hash table */
87779   if( rc==SQLITE_OK ){
87780     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
87781      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
87782      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
87783     ){
87784       rc = SQLITE_NOMEM;
87785     }
87786   }
87787
87788   /* Create the virtual table wrapper around the hash-table and overload 
87789   ** the two scalar functions. If this is successful, register the
87790   ** module with sqlite.
87791   */
87792   if( SQLITE_OK==rc 
87793    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
87794    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
87795    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", -1))
87796   ){
87797     return sqlite3_create_module_v2(
87798         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
87799     );
87800   }
87801
87802   /* An error has occured. Delete the hash table and return the error code. */
87803   assert( rc!=SQLITE_OK );
87804   if( pHash ){
87805     sqlite3Fts3HashClear(pHash);
87806     sqlite3_free(pHash);
87807   }
87808   return rc;
87809 }
87810
87811 #if !SQLITE_CORE
87812 int sqlite3_extension_init(
87813   sqlite3 *db, 
87814   char **pzErrMsg,
87815   const sqlite3_api_routines *pApi
87816 ){
87817   SQLITE_EXTENSION_INIT2(pApi)
87818   return sqlite3Fts3Init(db);
87819 }
87820 #endif
87821
87822 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
87823
87824 /************** End of fts3.c ************************************************/
87825 /************** Begin file fts3_hash.c ***************************************/
87826 /*
87827 ** 2001 September 22
87828 **
87829 ** The author disclaims copyright to this source code.  In place of
87830 ** a legal notice, here is a blessing:
87831 **
87832 **    May you do good and not evil.
87833 **    May you find forgiveness for yourself and forgive others.
87834 **    May you share freely, never taking more than you give.
87835 **
87836 *************************************************************************
87837 ** This is the implementation of generic hash-tables used in SQLite.
87838 ** We've modified it slightly to serve as a standalone hash table
87839 ** implementation for the full-text indexing module.
87840 */
87841
87842 /*
87843 ** The code in this file is only compiled if:
87844 **
87845 **     * The FTS3 module is being built as an extension
87846 **       (in which case SQLITE_CORE is not defined), or
87847 **
87848 **     * The FTS3 module is being built into the core of
87849 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
87850 */
87851 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
87852
87853
87854 /************** Include sqlite3.h in the middle of fts3_hash.c ***************/
87855 /************** Begin file sqlite3.h *****************************************/
87856 /*
87857 ** 2001 September 15
87858 **
87859 ** The author disclaims copyright to this source code.  In place of
87860 ** a legal notice, here is a blessing:
87861 **
87862 **    May you do good and not evil.
87863 **    May you find forgiveness for yourself and forgive others.
87864 **    May you share freely, never taking more than you give.
87865 **
87866 *************************************************************************
87867 ** This header file defines the interface that the SQLite library
87868 ** presents to client programs.  If a C-function, structure, datatype,
87869 ** or constant definition does not appear in this file, then it is
87870 ** not a published API of SQLite, is subject to change without
87871 ** notice, and should not be referenced by programs that use SQLite.
87872 **
87873 ** Some of the definitions that are in this file are marked as
87874 ** "experimental".  Experimental interfaces are normally new
87875 ** features recently added to SQLite.  We do not anticipate changes 
87876 ** to experimental interfaces but reserve to make minor changes if
87877 ** experience from use "in the wild" suggest such changes are prudent.
87878 **
87879 ** The official C-language API documentation for SQLite is derived
87880 ** from comments in this file.  This file is the authoritative source
87881 ** on how SQLite interfaces are suppose to operate.
87882 **
87883 ** The name of this file under configuration management is "sqlite.h.in".
87884 ** The makefile makes some minor changes to this file (such as inserting
87885 ** the version number) and changes its name to "sqlite3.h" as
87886 ** part of the build process.
87887 **
87888 ** @(#) $Id: sqlite.h.in,v 1.278 2007/12/13 21:54:11 drh Exp $
87889 */
87890 #ifndef _SQLITE3_H_
87891 #define _SQLITE3_H_
87892
87893 /*
87894 ** Make sure we can call this stuff from C++.
87895 */
87896 #if 0
87897 extern "C" {
87898 #endif
87899
87900
87901 /*
87902 ** Add the ability to override 'extern'
87903 */
87904 #ifndef SQLITE_EXTERN
87905 # define SQLITE_EXTERN extern
87906 #endif
87907
87908 /*
87909 ** Make sure these symbols where not defined by some previous header
87910 ** file.
87911 */
87912 #ifdef SQLITE_VERSION
87913 # undef SQLITE_VERSION
87914 #endif
87915 #ifdef SQLITE_VERSION_NUMBER
87916 # undef SQLITE_VERSION_NUMBER
87917 #endif
87918
87919 /*
87920 ** CAPI3REF: Compile-Time Library Version Numbers {F10010}
87921 **
87922 ** {F10011} The #define in the sqlite3.h header file named
87923 ** SQLITE_VERSION resolves to a string literal that identifies
87924 ** the version of the SQLite library in the format "X.Y.Z", where
87925 ** X is the major version number, Y is the minor version number and Z
87926 ** is the release number.  The X.Y.Z might be followed by "alpha" or "beta".
87927 ** {END} For example "3.1.1beta".
87928 **
87929 ** The X value is always 3 in SQLite.  The X value only changes when
87930 ** backwards compatibility is broken and we intend to never break
87931 ** backwards compatibility.  The Y value only changes when
87932 ** there are major feature enhancements that are forwards compatible
87933 ** but not backwards compatible.  The Z value is incremented with
87934 ** each release but resets back to 0 when Y is incremented.
87935 **
87936 ** {F10014} The SQLITE_VERSION_NUMBER #define resolves to an integer
87937 ** with the value  (X*1000000 + Y*1000 + Z) where X, Y, and Z are as
87938 ** with SQLITE_VERSION. {END} For example, for version "3.1.1beta", 
87939 ** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using 
87940 ** version 3.1.1 or greater at compile time, programs may use the test 
87941 ** (SQLITE_VERSION_NUMBER>=3001001).
87942 **
87943 ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
87944 */
87945 #define SQLITE_VERSION         "3.5.4"
87946 #define SQLITE_VERSION_NUMBER 3005004
87947
87948 /*
87949 ** CAPI3REF: Run-Time Library Version Numbers {F10020}
87950 **
87951 ** {F10021} The sqlite3_libversion_number() interface returns an integer
87952 ** equal to [SQLITE_VERSION_NUMBER].  {END} The value returned
87953 ** by this routine should only be different from the header values
87954 ** if the application is compiled using an sqlite3.h header from a
87955 ** different version of SQLite than library.  Cautious programmers might
87956 ** include a check in their application to verify that 
87957 ** sqlite3_libversion_number() always returns the value 
87958 ** [SQLITE_VERSION_NUMBER].
87959 **
87960 ** {F10022} The sqlite3_version[] string constant contains the text of the
87961 ** [SQLITE_VERSION] string. {F10023} The sqlite3_libversion() function returns
87962 ** a pointer to the sqlite3_version[] string constant. {END} The 
87963 ** sqlite3_libversion() function
87964 ** is provided for DLL users who can only access functions and not
87965 ** constants within the DLL.
87966 */
87967 SQLITE_EXTERN const char sqlite3_version[];
87968 const char *sqlite3_libversion(void);
87969 int sqlite3_libversion_number(void);
87970
87971 /*
87972 ** CAPI3REF: Test To See If The Library Is Threadsafe {F10100}
87973 **
87974 ** {F10101} The sqlite3_threadsafe() routine returns nonzero
87975 ** if SQLite was compiled with its mutexes enabled or zero if
87976 ** SQLite was compiled with mutexes disabled. {END}  If this
87977 ** routine returns false, then it is not safe for simultaneously
87978 ** running threads to both invoke SQLite interfaces.
87979 **
87980 ** Really all this routine does is return true if SQLite was
87981 ** compiled with the -DSQLITE_THREADSAFE=1 option and false if
87982 ** compiled with -DSQLITE_THREADSAFE=0.  If SQLite uses an
87983 ** application-defined mutex subsystem, malloc subsystem, collating
87984 ** sequence, VFS, SQL function, progress callback, commit hook,
87985 ** extension, or other accessories and these add-ons are not
87986 ** threadsafe, then clearly the combination will not be threadsafe
87987 ** either.  Hence, this routine never reports that the library
87988 ** is guaranteed to be threadsafe, only when it is guaranteed not
87989 ** to be.
87990 */
87991 int sqlite3_threadsafe(void);
87992
87993 /*
87994 ** CAPI3REF: Database Connection Handle {F12000}
87995 **
87996 ** Each open SQLite database is represented by pointer to an instance of the
87997 ** opaque structure named "sqlite3".  It is useful to think of an sqlite3
87998 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
87999 ** [sqlite3_open_v2()] interfaces are its constructors
88000 ** and [sqlite3_close()] is its destructor.  There are many other interfaces
88001 ** (such as [sqlite3_prepare_v2()], [sqlite3_create_function()], and
88002 ** [sqlite3_busy_timeout()] to name but three) that are methods on this
88003 ** object.
88004 */
88005 typedef struct sqlite3 sqlite3;
88006
88007
88008 /*
88009 ** CAPI3REF: 64-Bit Integer Types {F10200}
88010 **
88011 ** Because there is no cross-platform way to specify such types
88012 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
88013 ** {F10201} The sqlite_int64 and sqlite3_int64 types specify a
88014 ** 64-bit signed integer. {F10202} The sqlite_uint64 and
88015 ** sqlite3_uint64 types specify a 64-bit unsigned integer. {END}
88016 **
88017 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type
88018 ** definitions.  The sqlite_int64 and sqlite_uint64 types are
88019 ** supported for backwards compatibility only.
88020 */
88021 #ifdef SQLITE_INT64_TYPE
88022   typedef SQLITE_INT64_TYPE sqlite_int64;
88023   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
88024 #elif defined(_MSC_VER) || defined(__BORLANDC__)
88025   typedef __int64 sqlite_int64;
88026   typedef unsigned __int64 sqlite_uint64;
88027 #else
88028   typedef long long int sqlite_int64;
88029   typedef unsigned long long int sqlite_uint64;
88030 #endif
88031 typedef sqlite_int64 sqlite3_int64;
88032 typedef sqlite_uint64 sqlite3_uint64;
88033
88034 /*
88035 ** If compiling for a processor that lacks floating point support,
88036 ** substitute integer for floating-point
88037 */
88038 #ifdef SQLITE_OMIT_FLOATING_POINT
88039 # define double sqlite3_int64
88040 #endif
88041
88042 /*
88043 ** CAPI3REF: Closing A Database Connection {F12010}
88044 **
88045 ** {F12011} The sqlite3_close() interfaces destroys an [sqlite3] object
88046 ** allocated by a prior call to [sqlite3_open()], [sqlite3_open16()], or
88047 ** [sqlite3_open_v2()]. {F12012} Sqlite3_close() releases all
88048 ** memory used by the connection and closes all open files. {END}.
88049 **
88050 ** {F12013} If the database connection contains
88051 ** [sqlite3_stmt | prepared statements] that have not been finalized
88052 ** by [sqlite3_finalize()], then sqlite3_close() returns SQLITE_BUSY
88053 ** and leaves the connection open.  {F12014} Giving sqlite3_close()
88054 ** a NULL pointer is a harmless no-op. {END}
88055 **
88056 ** {U12015} Passing this routine a database connection that has already been
88057 ** closed results in undefined behavior. {U12016} If other interfaces that
88058 ** reference the same database connection are pending (either in the
88059 ** same thread or in different threads) when this routine is called,
88060 ** then the behavior is undefined and is almost certainly undesirable.
88061 */
88062 int sqlite3_close(sqlite3 *);
88063
88064 /*
88065 ** The type for a callback function.
88066 ** This is legacy and deprecated.  It is included for historical
88067 ** compatibility and is not documented.
88068 */
88069 typedef int (*sqlite3_callback)(void*,int,char**, char**);
88070
88071 /*
88072 ** CAPI3REF: One-Step Query Execution Interface {F12100}
88073 **
88074 ** {F12101} The sqlite3_exec() interface evaluates zero or more 
88075 ** UTF-8 encoded, semicolon-separated SQL statements in the zero-terminated
88076 ** string of its second argument.  {F12102} The SQL
88077 ** statements are evaluated in the context of the database connection
88078 ** specified by in the first argument.
88079 ** {F12103} SQL statements are prepared one by one using
88080 ** [sqlite3_prepare()] or the equivalent, evaluated
88081 ** using one or more calls to [sqlite3_step()], then destroyed
88082 ** using [sqlite3_finalize()]. {F12104} The return value of
88083 ** sqlite3_exec() is SQLITE_OK if all SQL statement run
88084 ** successfully.
88085 **
88086 ** {F12105} If one or more of the SQL statements handed to
88087 ** sqlite3_exec() are queries, then
88088 ** the callback function specified by the 3rd parameter is
88089 ** invoked once for each row of the query result. {F12106}
88090 ** If the callback returns a non-zero value then the query
88091 ** is aborted, all subsequent SQL statements
88092 ** are skipped and the sqlite3_exec() function returns the [SQLITE_ABORT].
88093 **
88094 ** {F12107} The 4th parameter to sqlite3_exec() is an arbitrary pointer
88095 ** that is passed through to the callback function as its first parameter.
88096 **
88097 ** {F12108} The 2nd parameter to the callback function is the number of
88098 ** columns in the query result.  {F12109} The 3rd parameter to the callback
88099 ** is an array of pointers to strings holding the values for each column
88100 ** as extracted using [sqlite3_column_text()].  NULL values in the result
88101 ** set result in a NULL pointer.  All other value are in their UTF-8
88102 ** string representation. {F12117}
88103 ** The 4th parameter to the callback is an array of strings
88104 ** obtained using [sqlite3_column_name()] and holding
88105 ** the names of each column, also in UTF-8.
88106 **
88107 ** {F12110} The callback function may be NULL, even for queries.  A NULL
88108 ** callback is not an error.  It just means that no callback
88109 ** will be invoked. 
88110 **
88111 ** {F12112} If an error occurs while parsing or evaluating the SQL
88112 ** then an appropriate error message is written into memory obtained
88113 ** from [sqlite3_malloc()] and *errmsg is made to point to that message
88114 ** assuming errmsg is not NULL.  
88115 ** {U12113} The calling function is responsible for freeing the memory
88116 ** using [sqlite3_free()].
88117 ** {F12116} If [sqlite3_malloc()] fails while attempting to generate
88118 ** the error message, *errmsg is set to NULL.
88119 ** {F12114} If errmsg is NULL then no attempt is made to generate an
88120 ** error message. <todo>Is the return code SQLITE_NOMEM or the original
88121 ** error code?</todo> <todo>What happens if there are multiple errors?
88122 ** Do we get code for the first error, or is the choice of reported
88123 ** error arbitrary?</todo>
88124 **
88125 ** {F12115} The return value is is SQLITE_OK if there are no errors and
88126 ** some other [SQLITE_OK | return code] if there is an error.  
88127 ** The particular return value depends on the type of error.  {END}
88128 */
88129 int sqlite3_exec(
88130   sqlite3*,                                  /* An open database */
88131   const char *sql,                           /* SQL to be evaluted */
88132   int (*callback)(void*,int,char**,char**),  /* Callback function */
88133   void *,                                    /* 1st argument to callback */
88134   char **errmsg                              /* Error msg written here */
88135 );
88136
88137 /*
88138 ** CAPI3REF: Result Codes {F10210}
88139 ** KEYWORDS: SQLITE_OK
88140 **
88141 ** Many SQLite functions return an integer result code from the set shown
88142 ** above in order to indicates success or failure.
88143 **
88144 ** {F10211} The result codes shown here are the only ones returned 
88145 ** by SQLite in its default configuration. {F10212} However, the
88146 ** [sqlite3_extended_result_codes()] API can be used to set a database
88147 ** connectoin to return more detailed result codes. {END}
88148 **
88149 ** See also: [SQLITE_IOERR_READ | extended result codes]
88150 **
88151 */
88152 #define SQLITE_OK           0   /* Successful result */
88153 /* beginning-of-error-codes */
88154 #define SQLITE_ERROR        1   /* SQL error or missing database */
88155 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
88156 #define SQLITE_PERM         3   /* Access permission denied */
88157 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
88158 #define SQLITE_BUSY         5   /* The database file is locked */
88159 #define SQLITE_LOCKED       6   /* A table in the database is locked */
88160 #define SQLITE_NOMEM        7   /* A malloc() failed */
88161 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
88162 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
88163 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
88164 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
88165 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
88166 #define SQLITE_FULL        13   /* Insertion failed because database is full */
88167 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
88168 #define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
88169 #define SQLITE_EMPTY       16   /* Database is empty */
88170 #define SQLITE_SCHEMA      17   /* The database schema changed */
88171 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
88172 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
88173 #define SQLITE_MISMATCH    20   /* Data type mismatch */
88174 #define SQLITE_MISUSE      21   /* Library used incorrectly */
88175 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
88176 #define SQLITE_AUTH        23   /* Authorization denied */
88177 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
88178 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
88179 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
88180 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
88181 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
88182 /* end-of-error-codes */
88183
88184 /*
88185 ** CAPI3REF: Extended Result Codes {F10220}
88186 **
88187 ** In its default configuration, SQLite API routines return one of 26 integer
88188 ** [SQLITE_OK | result codes].  However, experience has shown that
88189 ** many of these result codes are too course-grained.  They do not provide as
88190 ** much information about problems as programmers might like.  In an effort to
88191 ** address this, newer versions of SQLite (version 3.3.8 and later) include
88192 ** support for additional result codes that provide more detailed information
88193 ** about errors. {F10221} The extended result codes are enabled or disabled
88194 ** for each database connection using the [sqlite3_extended_result_codes()]
88195 ** API. {END}
88196 ** 
88197 ** Some of the available extended result codes are listed above.
88198 ** We expect the number of extended result codes will be expand
88199 ** over time.  {U10422} Software that uses extended result codes should expect
88200 ** to see new result codes in future releases of SQLite. {END}
88201 ** 
88202 ** {F10223} The symbolic name for an extended result code always contains
88203 ** a related primary result code as a prefix. {F10224} Primary result
88204 ** codes contain a single "_" character.  {F10225} Extended result codes
88205 ** contain two or more "_" characters. {F10226} The numeric value of an
88206 ** extended result code can be converted to its
88207 ** corresponding primary result code by masking off the lower 8 bytes. {END}
88208 **
88209 ** The SQLITE_OK result code will never be extended.  It will always
88210 ** be exactly zero.
88211 */
88212 #define SQLITE_IOERR_READ          (SQLITE_IOERR | (1<<8))
88213 #define SQLITE_IOERR_SHORT_READ    (SQLITE_IOERR | (2<<8))
88214 #define SQLITE_IOERR_WRITE         (SQLITE_IOERR | (3<<8))
88215 #define SQLITE_IOERR_FSYNC         (SQLITE_IOERR | (4<<8))
88216 #define SQLITE_IOERR_DIR_FSYNC     (SQLITE_IOERR | (5<<8))
88217 #define SQLITE_IOERR_TRUNCATE      (SQLITE_IOERR | (6<<8))
88218 #define SQLITE_IOERR_FSTAT         (SQLITE_IOERR | (7<<8))
88219 #define SQLITE_IOERR_UNLOCK        (SQLITE_IOERR | (8<<8))
88220 #define SQLITE_IOERR_RDLOCK        (SQLITE_IOERR | (9<<8))
88221 #define SQLITE_IOERR_DELETE        (SQLITE_IOERR | (10<<8))
88222 #define SQLITE_IOERR_BLOCKED       (SQLITE_IOERR | (11<<8))
88223 #define SQLITE_IOERR_NOMEM         (SQLITE_IOERR | (12<<8))
88224
88225 /*
88226 ** CAPI3REF: Flags For File Open Operations {F10230}
88227 **
88228 ** {F10231} Some combination of the these bit values are used as the
88229 ** third argument to the [sqlite3_open_v2()] interface and
88230 ** as fourth argument to the xOpen method of the
88231 ** [sqlite3_vfs] object.
88232 */
88233 #define SQLITE_OPEN_READONLY         0x00000001
88234 #define SQLITE_OPEN_READWRITE        0x00000002
88235 #define SQLITE_OPEN_CREATE           0x00000004
88236 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008
88237 #define SQLITE_OPEN_EXCLUSIVE        0x00000010
88238 #define SQLITE_OPEN_MAIN_DB          0x00000100
88239 #define SQLITE_OPEN_TEMP_DB          0x00000200
88240 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400
88241 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800
88242 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000
88243 #define SQLITE_OPEN_SUBJOURNAL       0x00002000
88244 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000
88245
88246 /*
88247 ** CAPI3REF: Device Characteristics {F10240}
88248 **
88249 ** {F10241} The xDeviceCapabilities method of the [sqlite3_io_methods]
88250 ** object returns an integer which is a vector of the these
88251 ** bit values expressing I/O characteristics of the mass storage
88252 ** device that holds the file that the [sqlite3_io_methods]
88253 ** refers to. {END}
88254 **
88255 ** {F10242} The SQLITE_IOCAP_ATOMIC property means that all writes of
88256 ** any size are atomic.  {F10243} The SQLITE_IOCAP_ATOMICnnn values
88257 ** mean that writes of blocks that are nnn bytes in size and
88258 ** are aligned to an address which is an integer multiple of
88259 ** nnn are atomic.  {F10244} The SQLITE_IOCAP_SAFE_APPEND value means
88260 ** that when data is appended to a file, the data is appended
88261 ** first then the size of the file is extended, never the other
88262 ** way around.  {F10245} The SQLITE_IOCAP_SEQUENTIAL property means that
88263 ** information is written to disk in the same order as calls
88264 ** to xWrite().
88265 */
88266 #define SQLITE_IOCAP_ATOMIC          0x00000001
88267 #define SQLITE_IOCAP_ATOMIC512       0x00000002
88268 #define SQLITE_IOCAP_ATOMIC1K        0x00000004
88269 #define SQLITE_IOCAP_ATOMIC2K        0x00000008
88270 #define SQLITE_IOCAP_ATOMIC4K        0x00000010
88271 #define SQLITE_IOCAP_ATOMIC8K        0x00000020
88272 #define SQLITE_IOCAP_ATOMIC16K       0x00000040
88273 #define SQLITE_IOCAP_ATOMIC32K       0x00000080
88274 #define SQLITE_IOCAP_ATOMIC64K       0x00000100
88275 #define SQLITE_IOCAP_SAFE_APPEND     0x00000200
88276 #define SQLITE_IOCAP_SEQUENTIAL      0x00000400
88277
88278 /*
88279 ** CAPI3REF: File Locking Levels {F10250}
88280 **
88281 ** {F10251} SQLite uses one of the following integer values as the second
88282 ** argument to calls it makes to the xLock() and xUnlock() methods
88283 ** of an [sqlite3_io_methods] object. {END}
88284 */
88285 #define SQLITE_LOCK_NONE          0
88286 #define SQLITE_LOCK_SHARED        1
88287 #define SQLITE_LOCK_RESERVED      2
88288 #define SQLITE_LOCK_PENDING       3
88289 #define SQLITE_LOCK_EXCLUSIVE     4
88290
88291 /*
88292 ** CAPI3REF: Synchronization Type Flags {F10260}
88293 **
88294 ** {F10261} When SQLite invokes the xSync() method of an
88295 ** [sqlite3_io_methods] object it uses a combination of the
88296 ** these integer values as the second argument.
88297 **
88298 ** {F10262} When the SQLITE_SYNC_DATAONLY flag is used, it means that the
88299 ** sync operation only needs to flush data to mass storage.  Inode
88300 ** information need not be flushed. {F10263} The SQLITE_SYNC_NORMAL means 
88301 ** to use normal fsync() semantics. {F10264} The SQLITE_SYNC_FULL flag means 
88302 ** to use Mac OS-X style fullsync instead of fsync().
88303 */
88304 #define SQLITE_SYNC_NORMAL        0x00002
88305 #define SQLITE_SYNC_FULL          0x00003
88306 #define SQLITE_SYNC_DATAONLY      0x00010
88307
88308
88309 /*
88310 ** CAPI3REF: OS Interface Open File Handle {F11110}
88311 **
88312 ** An [sqlite3_file] object represents an open file in the OS
88313 ** interface layer.  Individual OS interface implementations will
88314 ** want to subclass this object by appending additional fields
88315 ** for their own use.  The pMethods entry is a pointer to an
88316 ** [sqlite3_io_methods] object that defines methods for performing
88317 ** I/O operations on the open file.
88318 */
88319 typedef struct sqlite3_file sqlite3_file;
88320 struct sqlite3_file {
88321   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
88322 };
88323
88324 /*
88325 ** CAPI3REF: OS Interface File Virtual Methods Object {F11120}
88326 **
88327 ** Every file opened by the [sqlite3_vfs] xOpen method contains a pointer to
88328 ** an instance of the this object.  This object defines the
88329 ** methods used to perform various operations against the open file.
88330 **
88331 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
88332 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
88333 *  The second choice is an
88334 ** OS-X style fullsync.  The SQLITE_SYNC_DATA flag may be ORed in to
88335 ** indicate that only the data of the file and not its inode needs to be
88336 ** synced.
88337 ** 
88338 ** The integer values to xLock() and xUnlock() are one of
88339 ** <ul>
88340 ** <li> [SQLITE_LOCK_NONE],
88341 ** <li> [SQLITE_LOCK_SHARED],
88342 ** <li> [SQLITE_LOCK_RESERVED],
88343 ** <li> [SQLITE_LOCK_PENDING], or
88344 ** <li> [SQLITE_LOCK_EXCLUSIVE].
88345 ** </ul>
88346 ** xLock() increases the lock. xUnlock() decreases the lock.  
88347 ** The xCheckReservedLock() method looks
88348 ** to see if any database connection, either in this
88349 ** process or in some other process, is holding an RESERVED,
88350 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
88351 ** if such a lock exists and false if not.
88352 ** 
88353 ** The xFileControl() method is a generic interface that allows custom
88354 ** VFS implementations to directly control an open file using the
88355 ** [sqlite3_file_control()] interface.  The second "op" argument
88356 ** is an integer opcode.   The third
88357 ** argument is a generic pointer which is intended to be a pointer
88358 ** to a structure that may contain arguments or space in which to
88359 ** write return values.  Potential uses for xFileControl() might be
88360 ** functions to enable blocking locks with timeouts, to change the
88361 ** locking strategy (for example to use dot-file locks), to inquire
88362 ** about the status of a lock, or to break stale locks.  The SQLite
88363 ** core reserves opcodes less than 100 for its own use. 
88364 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
88365 ** Applications that define a custom xFileControl method should use opcodes 
88366 ** greater than 100 to avoid conflicts.
88367 **
88368 ** The xSectorSize() method returns the sector size of the
88369 ** device that underlies the file.  The sector size is the
88370 ** minimum write that can be performed without disturbing
88371 ** other bytes in the file.  The xDeviceCharacteristics()
88372 ** method returns a bit vector describing behaviors of the
88373 ** underlying device:
88374 **
88375 ** <ul>
88376 ** <li> [SQLITE_IOCAP_ATOMIC]
88377 ** <li> [SQLITE_IOCAP_ATOMIC512]
88378 ** <li> [SQLITE_IOCAP_ATOMIC1K]
88379 ** <li> [SQLITE_IOCAP_ATOMIC2K]
88380 ** <li> [SQLITE_IOCAP_ATOMIC4K]
88381 ** <li> [SQLITE_IOCAP_ATOMIC8K]
88382 ** <li> [SQLITE_IOCAP_ATOMIC16K]
88383 ** <li> [SQLITE_IOCAP_ATOMIC32K]
88384 ** <li> [SQLITE_IOCAP_ATOMIC64K]
88385 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
88386 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
88387 ** </ul>
88388 **
88389 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
88390 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
88391 ** mean that writes of blocks that are nnn bytes in size and
88392 ** are aligned to an address which is an integer multiple of
88393 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
88394 ** that when data is appended to a file, the data is appended
88395 ** first then the size of the file is extended, never the other
88396 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
88397 ** information is written to disk in the same order as calls
88398 ** to xWrite().
88399 */
88400 typedef struct sqlite3_io_methods sqlite3_io_methods;
88401 struct sqlite3_io_methods {
88402   int iVersion;
88403   int (*xClose)(sqlite3_file*);
88404   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
88405   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
88406   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
88407   int (*xSync)(sqlite3_file*, int flags);
88408   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
88409   int (*xLock)(sqlite3_file*, int);
88410   int (*xUnlock)(sqlite3_file*, int);
88411   int (*xCheckReservedLock)(sqlite3_file*);
88412   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
88413   int (*xSectorSize)(sqlite3_file*);
88414   int (*xDeviceCharacteristics)(sqlite3_file*);
88415   /* Additional methods may be added in future releases */
88416 };
88417
88418 /*
88419 ** CAPI3REF: Standard File Control Opcodes {F11310}
88420 **
88421 ** These integer constants are opcodes for the xFileControl method
88422 ** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()]
88423 ** interface.
88424 **
88425 ** {F11311} The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
88426 ** opcode cases the xFileControl method to write the current state of
88427 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
88428 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
88429 ** into an integer that the pArg argument points to. {F11312} This capability
88430 ** is used during testing and only needs to be supported when SQLITE_TEST
88431 ** is defined.
88432 */
88433 #define SQLITE_FCNTL_LOCKSTATE        1
88434
88435 /*
88436 ** CAPI3REF: Mutex Handle {F17110}
88437 **
88438 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
88439 ** abstract type for a mutex object.  {F17111} The SQLite core never looks
88440 ** at the internal representation of an [sqlite3_mutex]. {END} It only
88441 ** deals with pointers to the [sqlite3_mutex] object.
88442 **
88443 ** Mutexes are created using [sqlite3_mutex_alloc()].
88444 */
88445 typedef struct sqlite3_mutex sqlite3_mutex;
88446
88447 /*
88448 ** CAPI3REF: OS Interface Object {F11140}
88449 **
88450 ** An instance of this object defines the interface between the
88451 ** SQLite core and the underlying operating system.  The "vfs"
88452 ** in the name of the object stands for "virtual file system".
88453 **
88454 ** The iVersion field is initially 1 but may be larger for future
88455 ** versions of SQLite.  Additional fields may be appended to this
88456 ** object when the iVersion value is increased.
88457 **
88458 ** The szOsFile field is the size of the subclassed [sqlite3_file]
88459 ** structure used by this VFS.  mxPathname is the maximum length of
88460 ** a pathname in this VFS.
88461 **
88462 ** Registered vfs modules are kept on a linked list formed by
88463 ** the pNext pointer.  The [sqlite3_vfs_register()]
88464 ** and [sqlite3_vfs_unregister()] interfaces manage this list
88465 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
88466 ** searches the list.
88467 **
88468 ** The pNext field is the only fields in the sqlite3_vfs 
88469 ** structure that SQLite will ever modify.  SQLite will only access
88470 ** or modify this field while holding a particular static mutex.
88471 ** The application should never modify anything within the sqlite3_vfs
88472 ** object once the object has been registered.
88473 **
88474 ** The zName field holds the name of the VFS module.  The name must
88475 ** be unique across all VFS modules.
88476 **
88477 ** {F11141} SQLite will guarantee that the zFilename string passed to
88478 ** xOpen() is a full pathname as generated by xFullPathname() and
88479 ** that the string will be valid and unchanged until xClose() is
88480 ** called.  {END} So the [sqlite3_file] can store a pointer to the
88481 ** filename if it needs to remember the filename for some reason.
88482 **
88483 ** {F11142} The flags argument to xOpen() includes all bits set in
88484 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
88485 ** or [sqlite3_open16()] is used, then flags includes at least
88486 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END}
88487 ** If xOpen() opens a file read-only then it sets *pOutFlags to
88488 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be
88489 ** set.
88490 ** 
88491 ** {F11143} SQLite will also add one of the following flags to the xOpen()
88492 ** call, depending on the object being opened:
88493 ** 
88494 ** <ul>
88495 ** <li>  [SQLITE_OPEN_MAIN_DB]
88496 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
88497 ** <li>  [SQLITE_OPEN_TEMP_DB]
88498 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
88499 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
88500 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
88501 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
88502 ** </ul> {END}
88503 **
88504 ** The file I/O implementation can use the object type flags to
88505 ** changes the way it deals with files.  For example, an application
88506 ** that does not care about crash recovery or rollback, might make
88507 ** the open of a journal file a no-op.  Writes to this journal are
88508 ** also a no-op.  Any attempt to read the journal return SQLITE_IOERR.
88509 ** Or the implementation might recognize the a database file will
88510 ** be doing page-aligned sector reads and writes in a random order
88511 ** and set up its I/O subsystem accordingly.
88512 ** 
88513 ** {F11144} SQLite might also add one of the following flags to the xOpen
88514 ** method:
88515 ** 
88516 ** <ul>
88517 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
88518 ** <li> [SQLITE_OPEN_EXCLUSIVE]
88519 ** </ul>
88520 ** 
88521 ** {F11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
88522 ** deleted when it is closed.  {F11146} The [SQLITE_OPEN_DELETEONCLOSE]
88523 ** will be set for TEMP  databases, journals and for subjournals. 
88524 ** {F11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened
88525 ** for exclusive access.  This flag is set for all files except
88526 ** for the main database file. {END}
88527 ** 
88528 ** {F11148} At least szOsFile bytes of memory is allocated by SQLite 
88529 ** to hold the  [sqlite3_file] structure passed as the third 
88530 ** argument to xOpen.  {END}  The xOpen method does not have to
88531 ** allocate the structure; it should just fill it in.
88532 ** 
88533 ** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] 
88534 ** to test for the existance of a file,
88535 ** or [SQLITE_ACCESS_READWRITE] to test to see
88536 ** if a file is readable and writable, or [SQLITE_ACCESS_READ]
88537 ** to test to see if a file is at least readable.  {END} The file can be a 
88538 ** directory.
88539 ** 
88540 ** {F11150} SQLite will always allocate at least mxPathname+1 byte for
88541 ** the output buffers for xGetTempname and xFullPathname. {F11151} The exact
88542 ** size of the output buffer is also passed as a parameter to both 
88543 ** methods. {END} If the output buffer is not large enough, SQLITE_CANTOPEN
88544 ** should be returned. As this is handled as a fatal error by SQLite,
88545 ** vfs implementations should endeavor to prevent this by setting 
88546 ** mxPathname to a sufficiently large value.
88547 ** 
88548 ** The xRandomness(), xSleep(), and xCurrentTime() interfaces
88549 ** are not strictly a part of the filesystem, but they are
88550 ** included in the VFS structure for completeness.
88551 ** The xRandomness() function attempts to return nBytes bytes
88552 ** of good-quality randomness into zOut.  The return value is
88553 ** the actual number of bytes of randomness obtained.  The
88554 ** xSleep() method cause the calling thread to sleep for at
88555 ** least the number of microseconds given.  The xCurrentTime()
88556 ** method returns a Julian Day Number for the current date and
88557 ** time.
88558 */
88559 typedef struct sqlite3_vfs sqlite3_vfs;
88560 struct sqlite3_vfs {
88561   int iVersion;            /* Structure version number */
88562   int szOsFile;            /* Size of subclassed sqlite3_file */
88563   int mxPathname;          /* Maximum file pathname length */
88564   sqlite3_vfs *pNext;      /* Next registered VFS */
88565   const char *zName;       /* Name of this virtual file system */
88566   void *pAppData;          /* Pointer to application-specific data */
88567   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
88568                int flags, int *pOutFlags);
88569   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
88570   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags);
88571   int (*xGetTempname)(sqlite3_vfs*, int nOut, char *zOut);
88572   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
88573   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
88574   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
88575   void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol);
88576   void (*xDlClose)(sqlite3_vfs*, void*);
88577   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
88578   int (*xSleep)(sqlite3_vfs*, int microseconds);
88579   int (*xCurrentTime)(sqlite3_vfs*, double*);
88580   /* New fields may be appended in figure versions.  The iVersion
88581   ** value will increment whenever this happens. */
88582 };
88583
88584 /*
88585 ** CAPI3REF: Flags for the xAccess VFS method {F11190}
88586 **
88587 ** {F11191} These integer constants can be used as the third parameter to
88588 ** the xAccess method of an [sqlite3_vfs] object. {END}  They determine
88589 ** the kind of what kind of permissions the xAccess method is
88590 ** looking for.  {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method
88591 ** simply checks to see if the file exists. {F11193} With
88592 ** SQLITE_ACCESS_READWRITE, the xAccess method checks to see
88593 ** if the file is both readable and writable.  {F11194} With
88594 ** SQLITE_ACCESS_READ the xAccess method
88595 ** checks to see if the file is readable.
88596 */
88597 #define SQLITE_ACCESS_EXISTS    0
88598 #define SQLITE_ACCESS_READWRITE 1
88599 #define SQLITE_ACCESS_READ      2
88600
88601 /*
88602 ** CAPI3REF: Enable Or Disable Extended Result Codes {F12200}
88603 **
88604 ** {F12201} The sqlite3_extended_result_codes() routine enables or disables the
88605 ** [SQLITE_IOERR_READ | extended result codes] feature on a database
88606 ** connection if its 2nd parameter is
88607 ** non-zero or zero, respectively. {F12202}
88608 ** By default, SQLite API routines return one of only 26 integer
88609 ** [SQLITE_OK | result codes].  {F12203} When extended result codes
88610 ** are enabled by this routine, the repetoire of result codes can be
88611 ** much larger and can (hopefully) provide more detailed information
88612 ** about the cause of an error.
88613 **
88614 ** {F12204} The second argument is a boolean value that turns extended result
88615 ** codes on and off. {F12205} Extended result codes are off by default for
88616 ** backwards compatibility with older versions of SQLite.
88617 */
88618 int sqlite3_extended_result_codes(sqlite3*, int onoff);
88619
88620 /*
88621 ** CAPI3REF: Last Insert Rowid {F12220}
88622 **
88623 ** {F12221} Each entry in an SQLite table has a unique 64-bit signed
88624 ** integer key called the "rowid".  {F12222} The rowid is always available
88625 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
88626 ** names are not also used by explicitly declared columns. {F12223} If
88627 ** the table has a column of type INTEGER PRIMARY KEY then that column
88628 ** is another an alias for the rowid.
88629 **
88630 ** {F12224} This routine returns the rowid of the most recent
88631 ** successful INSERT into the database from the database connection
88632 ** shown in the first argument.  {F12225} If no successful inserts
88633 ** have ever occurred on this database connection, zero is returned.
88634 **
88635 ** {F12226} If an INSERT occurs within a trigger, then the rowid of the
88636 ** inserted row is returned by this routine as long as the trigger
88637 ** is running.  {F12227} But once the trigger terminates, the value returned
88638 ** by this routine reverts to the last value inserted before the
88639 ** trigger fired.
88640 **
88641 ** {F12228} An INSERT that fails due to a constraint violation is not a
88642 ** successful insert and does not change the value returned by this
88643 ** routine.  {F12229} Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
88644 ** and INSERT OR ABORT make no changes to the return value of this
88645 ** routine when their insertion fails.  {F12231} When INSERT OR REPLACE 
88646 ** encounters a constraint violation, it does not fail.  The
88647 ** INSERT continues to completion after deleting rows that caused
88648 ** the constraint problem so INSERT OR REPLACE will always change
88649 ** the return value of this interface. 
88650 **
88651 ** {UF12232} If another thread does a new insert on the same database connection
88652 ** while this routine is running and thus changes the last insert rowid,
88653 ** then the return value of this routine is undefined.
88654 */
88655 sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
88656
88657 /*
88658 ** CAPI3REF: Count The Number Of Rows Modified {F12240}
88659 **
88660 ** {F12241} This function returns the number of database rows that were changed
88661 ** or inserted or deleted by the most recently completed SQL statement
88662 ** on the connection specified by the first parameter. {F12242} Only
88663 ** changes that are directly specified by the INSERT, UPDATE, or
88664 ** DELETE statement are counted.  Auxiliary changes caused by
88665 ** triggers are not counted. {F12243} Use the [sqlite3_total_changes()] function
88666 ** to find the total number of changes including changes caused by triggers.
88667 **
88668 ** {F12244} Within the body of a trigger, the sqlite3_changes() interface
88669 ** can be called to find the number of
88670 ** changes in the most recently completed INSERT, UPDATE, or DELETE
88671 ** statement within the body of the same trigger.
88672 **
88673 ** {F12245} All changes are counted, even if they are later undone by a
88674 ** ROLLBACK or ABORT.  {F12246} Except, changes associated with creating and
88675 ** dropping tables are not counted.
88676 **
88677 ** {F12247} If a callback invokes [sqlite3_exec()] or [sqlite3_step()]
88678 ** recursively, then the changes in the inner, recursive call are
88679 ** counted together with the changes in the outer call.
88680 **
88681 ** {F12248} SQLite implements the command "DELETE FROM table" without
88682 ** a WHERE clause by dropping and recreating the table.  (This is much
88683 ** faster than going through and deleting individual elements from the
88684 ** table.)  Because of this optimization, the change count for 
88685 ** "DELETE FROM table" will be zero regardless of the number of elements
88686 ** that were originally in the table. {F12251} To get an accurate count
88687 ** of the number of rows deleted, use
88688 ** "DELETE FROM table WHERE 1" instead.
88689 **
88690 ** {UF12252} If another thread makes changes on the same database connection
88691 ** while this routine is running then the return value of this routine
88692 ** is undefined.
88693 */
88694 int sqlite3_changes(sqlite3*);
88695
88696 /*
88697 ** CAPI3REF: Total Number Of Rows Modified {F12260}
88698 ***
88699 ** {F12261} This function returns the number of database rows that have been
88700 ** modified by INSERT, UPDATE or DELETE statements since the database handle
88701 ** was opened. {F12262} The count includes UPDATE, INSERT and DELETE 
88702 ** statements executed as part of trigger programs.  {F12263} All changes
88703 ** are counted as soon as the statement that makes them is completed 
88704 ** (when the statement handle is passed to [sqlite3_reset()] or 
88705 ** [sqlite3_finalize()]). {END}
88706 **
88707 ** See also the [sqlite3_change()] interface.
88708 **
88709 ** {F12265} SQLite implements the command "DELETE FROM table" without
88710 ** a WHERE clause by dropping and recreating the table.  (This is much
88711 ** faster than going
88712 ** through and deleting individual elements form the table.)  Because of
88713 ** this optimization, the change count for "DELETE FROM table" will be
88714 ** zero regardless of the number of elements that were originally in the
88715 ** table. To get an accurate count of the number of rows deleted, use
88716 ** "DELETE FROM table WHERE 1" instead.
88717 **
88718 ** {U12264} If another thread makes changes on the same database connection
88719 ** while this routine is running then the return value of this routine
88720 ** is undefined. {END}
88721 */
88722 int sqlite3_total_changes(sqlite3*);
88723
88724 /*
88725 ** CAPI3REF: Interrupt A Long-Running Query {F12270}
88726 **
88727 ** {F12271} This function causes any pending database operation to abort and
88728 ** return at its earliest opportunity. {END} This routine is typically
88729 ** called in response to a user action such as pressing "Cancel"
88730 ** or Ctrl-C where the user wants a long query operation to halt
88731 ** immediately.
88732 **
88733 ** {F12272} It is safe to call this routine from a thread different from the
88734 ** thread that is currently running the database operation. {U12273} But it
88735 ** is not safe to call this routine with a database connection that
88736 ** is closed or might close before sqlite3_interrupt() returns.
88737 **
88738 ** If an SQL is very nearly finished at the time when sqlite3_interrupt()
88739 ** is called, then it might not have an opportunity to be interrupted.
88740 ** It might continue to completion.
88741 ** {F12274} The SQL operation that is interrupted will return
88742 ** [SQLITE_INTERRUPT].  {F12275} If the interrupted SQL operation is an
88743 ** INSERT, UPDATE, or DELETE that is inside an explicit transaction, 
88744 ** then the entire transaction will be rolled back automatically.
88745 ** {F12276} A call to sqlite3_interrupt() has no effect on SQL statements
88746 ** that are started after sqlite3_interrupt() returns.
88747 */
88748 void sqlite3_interrupt(sqlite3*);
88749
88750 /*
88751 ** CAPI3REF: Determine If An SQL Statement Is Complete {F10510}
88752 **
88753 ** These routines are useful for command-line input to determine if the
88754 ** currently entered text seems to form complete a SQL statement or
88755 ** if additional input is needed before sending the text into
88756 ** SQLite for parsing.  These routines return true if the input string
88757 ** appears to be a complete SQL statement.  A statement is judged to be
88758 ** complete if it ends with a semicolon and is not a fragment of a
88759 ** CREATE TRIGGER statement.  These routines do not parse the SQL and
88760 ** so will not detect syntactically incorrect SQL.
88761 **
88762 ** {F10511} These functions return true if the given input string 
88763 ** ends with a semicolon optionally followed by whitespace or
88764 ** comments. {F10512} For sqlite3_complete(),
88765 ** the parameter must be a zero-terminated UTF-8 string. {F10513} For
88766 ** sqlite3_complete16(), a zero-terminated machine byte order UTF-16 string
88767 ** is required.  {F10514} These routines return false if the terminal
88768 ** semicolon is within a comment, a string literal or a quoted identifier
88769 ** (in other words if the final semicolon is not really a separate token
88770 ** but part of a larger token) or if the final semicolon is
88771 ** in between the BEGIN and END keywords of a CREATE TRIGGER statement.
88772 ** {END}
88773 */
88774 int sqlite3_complete(const char *sql);
88775 int sqlite3_complete16(const void *sql);
88776
88777 /*
88778 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310}
88779 **
88780 ** {F12311} This routine identifies a callback function that might be
88781 ** invoked whenever an attempt is made to open a database table 
88782 ** that another thread or process has locked.
88783 ** {F12312} If the busy callback is NULL, then [SQLITE_BUSY]
88784 ** or [SQLITE_IOERR_BLOCKED]
88785 ** is returned immediately upon encountering the lock.
88786 ** {F12313} If the busy callback is not NULL, then the
88787 ** callback will be invoked with two arguments.  {F12314} The
88788 ** first argument to the handler is a copy of the void* pointer which
88789 ** is the third argument to this routine.  {F12315} The second argument to
88790 ** the handler is the number of times that the busy handler has
88791 ** been invoked for this locking event.  {F12316} If the
88792 ** busy callback returns 0, then no additional attempts are made to
88793 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
88794 ** {F12317} If the callback returns non-zero, then another attempt
88795 ** is made to open the database for reading and the cycle repeats.
88796 **
88797 ** The presence of a busy handler does not guarantee that
88798 ** it will be invoked when there is lock contention. {F12319}
88799 ** If SQLite determines that invoking the busy handler could result in
88800 ** a deadlock, it will go ahead and return [SQLITE_BUSY] or
88801 ** [SQLITE_IOERR_BLOCKED] instead of invoking the
88802 ** busy handler. {END}
88803 ** Consider a scenario where one process is holding a read lock that
88804 ** it is trying to promote to a reserved lock and
88805 ** a second process is holding a reserved lock that it is trying
88806 ** to promote to an exclusive lock.  The first process cannot proceed
88807 ** because it is blocked by the second and the second process cannot
88808 ** proceed because it is blocked by the first.  If both processes
88809 ** invoke the busy handlers, neither will make any progress.  Therefore,
88810 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
88811 ** will induce the first process to release its read lock and allow
88812 ** the second process to proceed.
88813 **
88814 ** {F12321} The default busy callback is NULL. {END}
88815 **
88816 ** {F12322} The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
88817 ** when SQLite is in the middle of a large transaction where all the
88818 ** changes will not fit into the in-memory cache.  {F12323} SQLite will
88819 ** already hold a RESERVED lock on the database file, but it needs
88820 ** to promote this lock to EXCLUSIVE so that it can spill cache
88821 ** pages into the database file without harm to concurrent
88822 ** readers.  {F12324} If it is unable to promote the lock, then the in-memory
88823 ** cache will be left in an inconsistent state and so the error
88824 ** code is promoted from the relatively benign [SQLITE_BUSY] to
88825 ** the more severe [SQLITE_IOERR_BLOCKED].  {F12325} This error code promotion
88826 ** forces an automatic rollback of the changes. {END} See the
88827 ** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError">
88828 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
88829 ** this is important.
88830 **      
88831 ** {F12326} Sqlite is re-entrant, so the busy handler may start a new
88832 ** query. {END} (It is not clear why anyone would every want to do this,
88833 ** but it is allowed, in theory.) {U12327} But the busy handler may not
88834 ** close the database.  Closing the database from a busy handler will delete 
88835 ** data structures out from under the executing query and will 
88836 ** probably result in a segmentation fault or other runtime error. {END}
88837 **
88838 ** {F12328} There can only be a single busy handler defined for each database
88839 ** connection.  Setting a new busy handler clears any previous one. 
88840 ** {F12329} Note that calling [sqlite3_busy_timeout()] will also set or clear
88841 ** the busy handler.
88842 **
88843 ** {F12331} When operating in [sqlite3_enable_shared_cache | shared cache mode],
88844 ** only a single busy handler can be defined for each database file.
88845 ** So if two database connections share a single cache, then changing
88846 ** the busy handler on one connection will also change the busy
88847 ** handler in the other connection.  {F12332} The busy handler is invoked
88848 ** in the thread that was running when the lock contention occurs.
88849 */
88850 int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
88851
88852 /*
88853 ** CAPI3REF: Set A Busy Timeout {F12340}
88854 **
88855 ** {F12341} This routine sets a [sqlite3_busy_handler | busy handler]
88856 ** that sleeps for a while when a
88857 ** table is locked.  {F12342} The handler will sleep multiple times until 
88858 ** at least "ms" milliseconds of sleeping have been done. {F12343} After
88859 ** "ms" milliseconds of sleeping, the handler returns 0 which
88860 ** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
88861 **
88862 ** {F12344} Calling this routine with an argument less than or equal to zero
88863 ** turns off all busy handlers.
88864 **
88865 ** {F12345} There can only be a single busy handler for a particular database
88866 ** connection.  If another busy handler was defined  
88867 ** (using [sqlite3_busy_handler()]) prior to calling
88868 ** this routine, that other busy handler is cleared.
88869 */
88870 int sqlite3_busy_timeout(sqlite3*, int ms);
88871
88872 /*
88873 ** CAPI3REF: Convenience Routines For Running Queries {F12370}
88874 **
88875 ** This next routine is a convenience wrapper around [sqlite3_exec()].
88876 ** {F12371} Instead of invoking a user-supplied callback for each row of the
88877 ** result, this routine remembers each row of the result in memory
88878 ** obtained from [sqlite3_malloc()], then returns all of the result after the
88879 ** query has finished. {F12372}
88880 **
88881 ** As an example, suppose the query result where this table:
88882 **
88883 ** <blockquote><pre>
88884 **        Name        | Age
88885 **        -----------------------
88886 **        Alice       | 43
88887 **        Bob         | 28
88888 **        Cindy       | 21
88889 ** </pre></blockquote>
88890 **
88891 ** If the 3rd argument were &azResult then after the function returns
88892 ** azResult will contain the following data:
88893 **
88894 ** <blockquote><pre>
88895 **        azResult&#91;0] = "Name";
88896 **        azResult&#91;1] = "Age";
88897 **        azResult&#91;2] = "Alice";
88898 **        azResult&#91;3] = "43";
88899 **        azResult&#91;4] = "Bob";
88900 **        azResult&#91;5] = "28";
88901 **        azResult&#91;6] = "Cindy";
88902 **        azResult&#91;7] = "21";
88903 ** </pre></blockquote>
88904 **
88905 ** Notice that there is an extra row of data containing the column
88906 ** headers.  But the *nrow return value is still 3.  *ncolumn is
88907 ** set to 2.  In general, the number of values inserted into azResult
88908 ** will be ((*nrow) + 1)*(*ncolumn).
88909 **
88910 ** {U12374} After the calling function has finished using the result, it should 
88911 ** pass the result data pointer to sqlite3_free_table() in order to 
88912 ** release the memory that was malloc-ed.  Because of the way the 
88913 ** [sqlite3_malloc()] happens, the calling function must not try to call 
88914 ** [sqlite3_free()] directly.  Only [sqlite3_free_table()] is able to release 
88915 ** the memory properly and safely. {END}
88916 **
88917 ** {F12373} The return value of this routine is the same as
88918 ** from [sqlite3_exec()].
88919 */
88920 int sqlite3_get_table(
88921   sqlite3*,              /* An open database */
88922   const char *sql,       /* SQL to be executed */
88923   char ***resultp,       /* Result written to a char *[]  that this points to */
88924   int *nrow,             /* Number of result rows written here */
88925   int *ncolumn,          /* Number of result columns written here */
88926   char **errmsg          /* Error msg written here */
88927 );
88928 void sqlite3_free_table(char **result);
88929
88930 /*
88931 ** CAPI3REF: Formatted String Printing Functions {F17400}
88932 **
88933 ** These routines are workalikes of the "printf()" family of functions
88934 ** from the standard C library.
88935 **
88936 ** {F17401} The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
88937 ** results into memory obtained from [sqlite3_malloc()].
88938 ** {U17402} The strings returned by these two routines should be
88939 ** released by [sqlite3_free()]. {F17403}  Both routines return a
88940 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
88941 ** memory to hold the resulting string.
88942 **
88943 ** {F17404} In sqlite3_snprintf() routine is similar to "snprintf()" from
88944 ** the standard C library.  The result is written into the
88945 ** buffer supplied as the second parameter whose size is given by
88946 ** the first parameter. {END} Note that the order of the
88947 ** first two parameters is reversed from snprintf().  This is an
88948 ** historical accident that cannot be fixed without breaking
88949 ** backwards compatibility.  {F17405} Note also that sqlite3_snprintf()
88950 ** returns a pointer to its buffer instead of the number of
88951 ** characters actually written into the buffer. {END} We admit that
88952 ** the number of characters written would be a more useful return
88953 ** value but we cannot change the implementation of sqlite3_snprintf()
88954 ** now without breaking compatibility.
88955 **
88956 ** {F17406} As long as the buffer size is greater than zero, sqlite3_snprintf()
88957 ** guarantees that the buffer is always zero-terminated. {F17407} The first
88958 ** parameter "n" is the total size of the buffer, including space for
88959 ** the zero terminator.  {END} So the longest string that can be completely
88960 ** written will be n-1 characters.
88961 **
88962 ** These routines all implement some additional formatting
88963 ** options that are useful for constructing SQL statements.
88964 ** All of the usual printf formatting options apply.  In addition, there
88965 ** is are "%q", "%Q", and "%z" options.
88966 **
88967 ** {F17410} The %q option works like %s in that it substitutes a null-terminated
88968 ** string from the argument list.  But %q also doubles every '\'' character.
88969 ** %q is designed for use inside a string literal. {END} By doubling each '\''
88970 ** character it escapes that character and allows it to be inserted into
88971 ** the string.
88972 **
88973 ** For example, so some string variable contains text as follows:
88974 **
88975 ** <blockquote><pre>
88976 **  char *zText = "It's a happy day!";
88977 ** </pre></blockquote>
88978 **
88979 ** One can use this text in an SQL statement as follows:
88980 **
88981 ** <blockquote><pre>
88982 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
88983 **  sqlite3_exec(db, zSQL, 0, 0, 0);
88984 **  sqlite3_free(zSQL);
88985 ** </pre></blockquote>
88986 **
88987 ** Because the %q format string is used, the '\'' character in zText
88988 ** is escaped and the SQL generated is as follows:
88989 **
88990 ** <blockquote><pre>
88991 **  INSERT INTO table1 VALUES('It''s a happy day!')
88992 ** </pre></blockquote>
88993 **
88994 ** This is correct.  Had we used %s instead of %q, the generated SQL
88995 ** would have looked like this:
88996 **
88997 ** <blockquote><pre>
88998 **  INSERT INTO table1 VALUES('It's a happy day!');
88999 ** </pre></blockquote>
89000 **
89001 ** This second example is an SQL syntax error.  As a general rule you
89002 ** should always use %q instead of %s when inserting text into a string 
89003 ** literal.
89004 **
89005 ** {F17411} The %Q option works like %q except it also adds single quotes around
89006 ** the outside of the total string.  Or if the parameter in the argument
89007 ** list is a NULL pointer, %Q substitutes the text "NULL" (without single
89008 ** quotes) in place of the %Q option. {END}  So, for example, one could say:
89009 **
89010 ** <blockquote><pre>
89011 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
89012 **  sqlite3_exec(db, zSQL, 0, 0, 0);
89013 **  sqlite3_free(zSQL);
89014 ** </pre></blockquote>
89015 **
89016 ** The code above will render a correct SQL statement in the zSQL
89017 ** variable even if the zText variable is a NULL pointer.
89018 **
89019 ** {F17412} The "%z" formatting option works exactly like "%s" with the
89020 ** addition that after the string has been read and copied into
89021 ** the result, [sqlite3_free()] is called on the input string. {END}
89022 */
89023 char *sqlite3_mprintf(const char*,...);
89024 char *sqlite3_vmprintf(const char*, va_list);
89025 char *sqlite3_snprintf(int,char*,const char*, ...);
89026
89027 /*
89028 ** CAPI3REF: Memory Allocation Subsystem {F17300}
89029 **
89030 ** {F17301} The SQLite core  uses these three routines for all of its own
89031 ** internal memory allocation needs. {END}  "Core" in the previous sentence
89032 ** does not include operating-system specific VFS implementation.  The
89033 ** windows VFS uses native malloc and free for some operations.
89034 **
89035 ** {F17302} The sqlite3_malloc() routine returns a pointer to a block
89036 ** of memory at least N bytes in length, where N is the parameter.
89037 ** {F17303} If sqlite3_malloc() is unable to obtain sufficient free
89038 ** memory, it returns a NULL pointer.  {F17304} If the parameter N to
89039 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
89040 ** a NULL pointer.
89041 **
89042 ** {F17305} Calling sqlite3_free() with a pointer previously returned
89043 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
89044 ** that it might be reused.  {F17306} The sqlite3_free() routine is
89045 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
89046 ** to sqlite3_free() is harmless.  {U17307} After being freed, memory
89047 ** should neither be read nor written.  Even reading previously freed
89048 ** memory might result in a segmentation fault or other severe error.
89049 ** {U17309} Memory corruption, a segmentation fault, or other severe error
89050 ** might result if sqlite3_free() is called with a non-NULL pointer that
89051 ** was not obtained from sqlite3_malloc() or sqlite3_free().
89052 **
89053 ** {F17310} The sqlite3_realloc() interface attempts to resize a
89054 ** prior memory allocation to be at least N bytes, where N is the
89055 ** second parameter.  The memory allocation to be resized is the first
89056 ** parameter.  {F17311} If the first parameter to sqlite3_realloc()
89057 ** is a NULL pointer then its behavior is identical to calling
89058 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
89059 ** {F17312} If the second parameter to sqlite3_realloc() is zero or
89060 ** negative then the behavior is exactly the same as calling
89061 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
89062 ** {F17313} Sqlite3_realloc() returns a pointer to a memory allocation
89063 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
89064 ** {F17314} If M is the size of the prior allocation, then min(N,M) bytes
89065 ** of the prior allocation are copied into the beginning of buffer returned
89066 ** by sqlite3_realloc() and the prior allocation is freed.
89067 ** {F17315} If sqlite3_realloc() returns NULL, then the prior allocation
89068 ** is not freed.
89069 **
89070 ** {F17316} The memory returned by sqlite3_malloc() and sqlite3_realloc()
89071 ** is always aligned to at least an 8 byte boundary. {END}
89072 **
89073 ** {F17381} The default implementation
89074 ** of the memory allocation subsystem uses the malloc(), realloc()
89075 ** and free() provided by the standard C library. {F17382} However, if 
89076 ** SQLite is compiled with the following C preprocessor macro
89077 **
89078 ** <blockquote> SQLITE_MEMORY_SIZE=<i>NNN</i> </blockquote>
89079 **
89080 ** where <i>NNN</i> is an integer, then SQLite create a static
89081 ** array of at least <i>NNN</i> bytes in size and use that array
89082 ** for all of its dynamic memory allocation needs. {END}  Additional
89083 ** memory allocator options may be added in future releases.
89084 **
89085 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
89086 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
89087 ** implementation of these routines to be omitted.  That capability
89088 ** is no longer provided.  Only built-in memory allocators can be
89089 ** used.
89090 **
89091 ** The windows OS interface layer calls
89092 ** the system malloc() and free() directly when converting
89093 ** filenames between the UTF-8 encoding used by SQLite
89094 ** and whatever filename encoding is used by the particular windows
89095 ** installation.  Memory allocation errors are detected, but
89096 ** they are reported back as [SQLITE_CANTOPEN] or
89097 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
89098 */
89099 void *sqlite3_malloc(int);
89100 void *sqlite3_realloc(void*, int);
89101 void sqlite3_free(void*);
89102
89103 /*
89104 ** CAPI3REF: Memory Allocator Statistics {F17370}
89105 **
89106 ** In addition to the basic three allocation routines 
89107 ** [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()],
89108 ** the memory allocation subsystem included with the SQLite
89109 ** sources provides the interfaces shown here.
89110 **
89111 ** {F17371} The sqlite3_memory_used() routine returns the
89112 ** number of bytes of memory currently outstanding (malloced but not freed).
89113 ** {F17372} The value returned by sqlite3_memory_used() includes
89114 ** any overhead added by SQLite, but not overhead added by the
89115 ** library malloc() that backs the sqlite3_malloc() implementation.
89116 ** {F17373} The sqlite3_memory_highwater() routines returns the
89117 ** maximum number of bytes that have been outstanding at any time
89118 ** since the highwater mark was last reset.
89119 ** {F17374} The byte count returned by sqlite3_memory_highwater()
89120 ** uses the same byte counting rules as sqlite3_memory_used(). {END}
89121 ** In other words, overhead added internally by SQLite is counted,
89122 ** but overhead from the underlying system malloc is not.
89123 ** {F17375} If the parameter to sqlite3_memory_highwater() is true,
89124 ** then the highwater mark is reset to the current value of
89125 ** sqlite3_memory_used() and the prior highwater mark (before the
89126 ** reset) is returned.  {F17376}  If the parameter to 
89127 ** sqlite3_memory_highwater() is zero, then the highwater mark is
89128 ** unchanged.
89129 */
89130 sqlite3_int64 sqlite3_memory_used(void);
89131 sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
89132
89133 /*
89134 ** CAPI3REF: Compile-Time Authorization Callbacks {F12500}
89135 **
89136 ** {F12501} This routine registers a authorizer callback with a particular
89137 ** database connection, supplied in the first argument. {F12502}
89138 ** The authorizer callback is invoked as SQL statements are being compiled
89139 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
89140 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  {F12503} At various
89141 ** points during the compilation process, as logic is being created
89142 ** to perform various actions, the authorizer callback is invoked to
89143 ** see if those actions are allowed.  The authorizer callback should
89144 ** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the
89145 ** specific action but allow the SQL statement to continue to be
89146 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
89147 ** rejected with an error.  {F12504} If the authorizer callback returns
89148 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
89149 ** then [sqlite3_prepare_v2()] or equivalent call that triggered
89150 ** the authorizer shall
89151 ** fail with an SQLITE_ERROR error code and an appropriate error message. {END}
89152 **
89153 ** When the callback returns [SQLITE_OK], that means the operation
89154 ** requested is ok.  {F12505} When the callback returns [SQLITE_DENY], the
89155 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
89156 ** authorizer shall fail
89157 ** with an SQLITE_ERROR error code and an error message explaining that
89158 ** access is denied. {F12506} If the authorizer code (the 2nd parameter
89159 ** to the authorizer callback is anything other than [SQLITE_READ], then
89160 ** a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. 
89161 ** If the authorizer code is [SQLITE_READ] and the callback returns
89162 ** [SQLITE_IGNORE] then the prepared statement is constructed to
89163 ** insert a NULL value in place of the table column that would have
89164 ** been read if [SQLITE_OK] had been returned. {END}
89165 **
89166 ** {F12510} The first parameter to the authorizer callback is a copy of
89167 ** the third parameter to the sqlite3_set_authorizer() interface.
89168 ** {F12511} The second parameter to the callback is an integer 
89169 ** [SQLITE_COPY | action code] that specifies the particular action
89170 ** to be authorized. {END} The available action codes are
89171 ** [SQLITE_COPY | documented separately].  {F12512} The third through sixth
89172 ** parameters to the callback are zero-terminated strings that contain 
89173 ** additional details about the action to be authorized. {END}
89174 **
89175 ** An authorizer is used when preparing SQL statements from an untrusted
89176 ** source, to ensure that the SQL statements do not try to access data
89177 ** that they are not allowed to see, or that they do not try to
89178 ** execute malicious statements that damage the database.  For
89179 ** example, an application may allow a user to enter arbitrary
89180 ** SQL queries for evaluation by a database.  But the application does
89181 ** not want the user to be able to make arbitrary changes to the
89182 ** database.  An authorizer could then be put in place while the
89183 ** user-entered SQL is being prepared that disallows everything
89184 ** except SELECT statements.  
89185 **
89186 ** {F12520} Only a single authorizer can be in place on a database connection
89187 ** at a time.  Each call to sqlite3_set_authorizer overrides the
89188 ** previous call. {F12521}  A NULL authorizer means that no authorization
89189 ** callback is invoked.  {F12522} The default authorizer is NULL. {END}
89190 **
89191 ** Note that the authorizer callback is invoked only during 
89192 ** [sqlite3_prepare()] or its variants.  {F12523} Authorization is not
89193 ** performed during statement evaluation in [sqlite3_step()]. {END}
89194 */
89195 int sqlite3_set_authorizer(
89196   sqlite3*,
89197   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
89198   void *pUserData
89199 );
89200
89201 /*
89202 ** CAPI3REF: Authorizer Return Codes {F12590}
89203 **
89204 ** The [sqlite3_set_authorizer | authorizer callback function] must
89205 ** return either [SQLITE_OK] or one of these two constants in order
89206 ** to signal SQLite whether or not the action is permitted.  See the
89207 ** [sqlite3_set_authorizer | authorizer documentation] for additional
89208 ** information.
89209 */
89210 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
89211 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
89212
89213 /*
89214 ** CAPI3REF: Authorizer Action Codes {F12550}
89215 **
89216 ** The [sqlite3_set_authorizer()] interface registers a callback function
89217 ** that is invoked to authorizer certain SQL statement actions.  {F12551} The
89218 ** second parameter to the callback is an integer code that specifies
89219 ** what action is being authorized.  These are the integer action codes that
89220 ** the authorizer callback may be passed. {END}
89221 **
89222 ** These action code values signify what kind of operation is to be 
89223 ** authorized.  {F12552} The 3rd and 4th parameters to the authorization
89224 ** callback function will be parameters or NULL depending on which of these
89225 ** codes is used as the second parameter. {F12553} The 5th parameter to the
89226 ** authorizer callback is the name of the database ("main", "temp", 
89227 ** etc.) if applicable. {F12554} The 6th parameter to the authorizer callback
89228 ** is the name of the inner-most trigger or view that is responsible for
89229 ** the access attempt or NULL if this access attempt is directly from 
89230 ** top-level SQL code.
89231 */
89232 /******************************************* 3rd ************ 4th ***********/
89233 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
89234 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
89235 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
89236 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
89237 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
89238 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
89239 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
89240 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
89241 #define SQLITE_DELETE                9   /* Table Name      NULL            */
89242 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
89243 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
89244 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
89245 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
89246 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
89247 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
89248 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
89249 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
89250 #define SQLITE_INSERT               18   /* Table Name      NULL            */
89251 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
89252 #define SQLITE_READ                 20   /* Table Name      Column Name     */
89253 #define SQLITE_SELECT               21   /* NULL            NULL            */
89254 #define SQLITE_TRANSACTION          22   /* NULL            NULL            */
89255 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
89256 #define SQLITE_ATTACH               24   /* Filename        NULL            */
89257 #define SQLITE_DETACH               25   /* Database Name   NULL            */
89258 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
89259 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
89260 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
89261 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
89262 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
89263 #define SQLITE_FUNCTION             31   /* Function Name   NULL            */
89264 #define SQLITE_COPY                  0   /* No longer used */
89265
89266 /*
89267 ** CAPI3REF: Tracing And Profiling Functions {F12280}
89268 **
89269 ** These routines register callback functions that can be used for
89270 ** tracing and profiling the execution of SQL statements.
89271 **
89272 ** {F12281} The callback function registered by sqlite3_trace() is invoked
89273 ** at the first [sqlite3_step()] for the evaluation of an SQL statement.
89274 ** {F12282} Only a single trace callback can be registered at a time.
89275 ** Each call to sqlite3_trace() overrides the previous.  {F12283} A
89276 ** NULL callback for sqlite3_trace() disables tracing.  {F12284} The
89277 ** first argument to the trace callback is a copy of the pointer which
89278 ** was the 3rd argument to sqlite3_trace.  {F12285} The second argument
89279 ** to the trace callback is a zero-terminated UTF8 string containing
89280 ** the original text of the SQL statement as it was passed into
89281 ** [sqlite3_prepare_v2()] or the equivalent. {END}  Note that the
89282 ** host parameter are not expanded in the SQL statement text.
89283 **
89284 ** {F12287} The callback function registered by sqlite3_profile() is invoked
89285 ** as each SQL statement finishes.  {F12288} The first parameter to the
89286 ** profile callback is a copy of the 3rd parameter to sqlite3_profile().
89287 ** {F12289} The second parameter to the profile callback is a
89288 ** zero-terminated UTF-8 string that contains the complete text of
89289 ** the SQL statement as it was processed by [sqlite3_prepare_v2()] or
89290 ** the equivalent.  {F12290} The third parameter to the profile 
89291 ** callback is an estimate of the number of nanoseconds of
89292 ** wall-clock time required to run the SQL statement from start
89293 ** to finish. {END}  
89294 **
89295 ** The sqlite3_profile() API is currently considered experimental and
89296 ** is subject to change.
89297 */
89298 void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
89299 void *sqlite3_profile(sqlite3*,
89300    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
89301
89302 /*
89303 ** CAPI3REF: Query Progress Callbacks {F12910}
89304 **
89305 ** {F12911} This routine configures a callback function - the
89306 ** progress callback - that is invoked periodically during long
89307 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
89308 ** [sqlite3_get_table()]. {END}  An example use for this 
89309 ** interface is to keep a GUI updated during a large query.
89310 **
89311 ** {F12912} The progress callback is invoked once for every N virtual
89312 ** machine opcodes, where N is the second argument to this function.
89313 ** {F12913} The progress callback itself is identified by the third
89314 ** argument to this function. {F12914} The fourth argument to this
89315 ** function is a void pointer passed to the progress callback
89316 ** function each time it is invoked. {END}
89317 **
89318 ** {F12915} If a call to [sqlite3_exec()], [sqlite3_step()], or
89319 ** [sqlite3_get_table()] results in fewer than N opcodes being executed,
89320 ** then the progress callback is never invoked. {END}
89321 ** 
89322 ** {F12916} Only a single progress callback function may be registered for each
89323 ** open database connection.  Every call to sqlite3_progress_handler()
89324 ** overwrites the results of the previous call. {F12917}
89325 ** To remove the progress callback altogether, pass NULL as the third
89326 ** argument to this function. {END}
89327 **
89328 ** {F12918} If the progress callback returns a result other than 0, then
89329 ** the current query is immediately terminated and any database changes
89330 ** rolled back. {F12919}
89331 ** The containing [sqlite3_exec()], [sqlite3_step()], or
89332 ** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. {END}  This feature
89333 ** can be used, for example, to implement the "Cancel" button on a
89334 ** progress dialog box in a GUI.
89335 */
89336 void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
89337
89338 /*
89339 ** CAPI3REF: Opening A New Database Connection {F12700}
89340 **
89341 ** {F12701} These routines open an SQLite database file whose name
89342 ** is given by the filename argument.
89343 ** {F12702} The filename argument is interpreted as UTF-8
89344 ** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16
89345 ** in the native byte order for [sqlite3_open16()].
89346 ** {F12703} An [sqlite3*] handle is returned in *ppDb, even
89347 ** if an error occurs.  {F12723} (Exception: if SQLite is unable
89348 ** to allocate memory to hold the [sqlite3] object, a NULL will
89349 ** be written into *ppDb instead of a pointer to the [sqlite3] object.)
89350 ** {F12704} If the database is opened (and/or created)
89351 ** successfully, then [SQLITE_OK] is returned.  {F12705} Otherwise an
89352 ** error code is returned.  {F12706} The
89353 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()]  routines can be used to obtain
89354 ** an English language description of the error.
89355 **
89356 ** {F12707} The default encoding for the database will be UTF-8 if
89357 ** [sqlite3_open()] or [sqlite3_open_v2()] is called and
89358 ** UTF-16 in the native byte order if [sqlite3_open16()] is used.
89359 **
89360 ** {F12708} Whether or not an error occurs when it is opened, resources
89361 ** associated with the [sqlite3*] handle should be released by passing it
89362 ** to [sqlite3_close()] when it is no longer required.
89363 **
89364 ** {F12709} The [sqlite3_open_v2()] interface works like [sqlite3_open()] 
89365 ** except that it acccepts two additional parameters for additional control
89366 ** over the new database connection.  {F12710} The flags parameter can be
89367 ** one of:
89368 **
89369 ** <ol>
89370 ** <li>  [SQLITE_OPEN_READONLY]
89371 ** <li>  [SQLITE_OPEN_READWRITE]
89372 ** <li>  [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
89373 ** </ol>
89374 **
89375 ** {F12711} The first value opens the database read-only. 
89376 ** {F12712} If the database does not previously exist, an error is returned.
89377 ** {F12713} The second option opens
89378 ** the database for reading and writing if possible, or reading only if
89379 ** if the file is write protected.  {F12714} In either case the database
89380 ** must already exist or an error is returned.  {F12715} The third option
89381 ** opens the database for reading and writing and creates it if it does
89382 ** not already exist. {F12716}
89383 ** The third options is behavior that is always used for [sqlite3_open()]
89384 ** and [sqlite3_open16()].
89385 **
89386 ** {F12717} If the filename is ":memory:", then an private
89387 ** in-memory database is created for the connection. {F12718} This in-memory
89388 ** database will vanish when the database connection is closed. {END}  Future
89389 ** version of SQLite might make use of additional special filenames
89390 ** that begin with the ":" character.  It is recommended that 
89391 ** when a database filename really does begin with
89392 ** ":" that you prefix the filename with a pathname like "./" to
89393 ** avoid ambiguity.
89394 **
89395 ** {F12719} If the filename is an empty string, then a private temporary
89396 ** on-disk database will be created.  {F12720} This private database will be
89397 ** automatically deleted as soon as the database connection is closed.
89398 **
89399 ** {F12721} The fourth parameter to sqlite3_open_v2() is the name of the
89400 ** [sqlite3_vfs] object that defines the operating system 
89401 ** interface that the new database connection should use.  {F12722} If the
89402 ** fourth parameter is a NULL pointer then the default [sqlite3_vfs]
89403 ** object is used. {END}
89404 **
89405 ** <b>Note to windows users:</b>  The encoding used for the filename argument
89406 ** of [sqlite3_open()] and [sqlite3_open_v2()] must be UTF-8, not whatever
89407 ** codepage is currently defined.  Filenames containing international
89408 ** characters must be converted to UTF-8 prior to passing them into
89409 ** [sqlite3_open()] or [sqlite3_open_v2()].
89410 */
89411 int sqlite3_open(
89412   const char *filename,   /* Database filename (UTF-8) */
89413   sqlite3 **ppDb          /* OUT: SQLite db handle */
89414 );
89415 int sqlite3_open16(
89416   const void *filename,   /* Database filename (UTF-16) */
89417   sqlite3 **ppDb          /* OUT: SQLite db handle */
89418 );
89419 int sqlite3_open_v2(
89420   const char *filename,   /* Database filename (UTF-8) */
89421   sqlite3 **ppDb,         /* OUT: SQLite db handle */
89422   int flags,              /* Flags */
89423   const char *zVfs        /* Name of VFS module to use */
89424 );
89425
89426 /*
89427 ** CAPI3REF: Error Codes And Messages {F12800}
89428 **
89429 ** {F12801} The sqlite3_errcode() interface returns the numeric
89430 ** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code]
89431 ** for the most recent failed sqlite3_* API call associated
89432 ** with [sqlite3] handle 'db'. {U12802} If a prior API call failed but the
89433 ** most recent API call succeeded, the return value from sqlite3_errcode()
89434 ** is undefined. {END}
89435 **
89436 ** {F12803} The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
89437 ** text that describes the error, as either UTF8 or UTF16 respectively.
89438 ** {F12804} Memory to hold the error message string is managed internally.
89439 ** {U12805} The 
89440 ** string may be overwritten or deallocated by subsequent calls to SQLite
89441 ** interface functions. {END}
89442 **
89443 ** {F12806} Calls to many sqlite3_* functions set the error code and
89444 ** string returned by [sqlite3_errcode()], [sqlite3_errmsg()], and
89445 ** [sqlite3_errmsg16()] overwriting the previous values.  {F12807}
89446 ** Except, calls to [sqlite3_errcode()],
89447 ** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the
89448 ** results of future invocations.  {F12808} Calls to API routines that
89449 ** do not return an error code (example: [sqlite3_data_count()]) do not
89450 ** change the error code returned by this routine.  {F12809} Interfaces that
89451 ** are not associated with a specific database connection (examples:
89452 ** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change
89453 ** the return code. {END}
89454 **
89455 ** {F12810} Assuming no other intervening sqlite3_* API calls are made,
89456 ** the error code returned by this function is associated with the same
89457 ** error as the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()].
89458 */
89459 int sqlite3_errcode(sqlite3 *db);
89460 const char *sqlite3_errmsg(sqlite3*);
89461 const void *sqlite3_errmsg16(sqlite3*);
89462
89463 /*
89464 ** CAPI3REF: SQL Statement Object {F13000}
89465 **
89466 ** An instance of this object represent single SQL statements.  This
89467 ** object is variously known as a "prepared statement" or a 
89468 ** "compiled SQL statement" or simply as a "statement".
89469 ** 
89470 ** The life of a statement object goes something like this:
89471 **
89472 ** <ol>
89473 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
89474 **      function.
89475 ** <li> Bind values to host parameters using
89476 **      [sqlite3_bind_blob | sqlite3_bind_* interfaces].
89477 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
89478 ** <li> Reset the statement using [sqlite3_reset()] then go back
89479 **      to step 2.  Do this zero or more times.
89480 ** <li> Destroy the object using [sqlite3_finalize()].
89481 ** </ol>
89482 **
89483 ** Refer to documentation on individual methods above for additional
89484 ** information.
89485 */
89486 typedef struct sqlite3_stmt sqlite3_stmt;
89487
89488 /*
89489 ** CAPI3REF: Compiling An SQL Statement {F13010}
89490 **
89491 ** To execute an SQL query, it must first be compiled into a byte-code
89492 ** program using one of these routines. 
89493 **
89494 ** {F13011} The first argument "db" is an [sqlite3 | SQLite database handle] 
89495 ** obtained from a prior call to [sqlite3_open()], [sqlite3_open_v2()]
89496 ** or [sqlite3_open16()]. {F13012}
89497 ** The second argument "zSql" is the statement to be compiled, encoded
89498 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
89499 ** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2()
89500 ** use UTF-16. {END}
89501 **
89502 ** {F13013} If the nByte argument is less
89503 ** than zero, then zSql is read up to the first zero terminator.
89504 ** {F13014} If nByte is non-negative, then it is the maximum number of 
89505 ** bytes read from zSql.  When nByte is non-negative, the
89506 ** zSql string ends at either the first '\000' or '\u0000' character or 
89507 ** until the nByte-th byte, whichever comes first. {END}
89508 **
89509 ** {F13015} *pzTail is made to point to the first byte past the end of the
89510 ** first SQL statement in zSql.  These routines only compiles the first
89511 ** statement in zSql, so *pzTail is left pointing to what remains
89512 ** uncompiled. {END}
89513 **
89514 ** {F13016} *ppStmt is left pointing to a compiled 
89515 ** [sqlite3_stmt | SQL statement structure] that can be
89516 ** executed using [sqlite3_step()].  Or if there is an error, *ppStmt may be
89517 ** set to NULL.  {F13017} If the input text contains no SQL (if the input
89518 ** is and empty string or a comment) then *ppStmt is set to NULL.
89519 ** {U13018} The calling procedure is responsible for deleting the
89520 ** compiled SQL statement
89521 ** using [sqlite3_finalize()] after it has finished with it.
89522 **
89523 ** {F13019} On success, [SQLITE_OK] is returned.  Otherwise an 
89524 ** [SQLITE_ERROR | error code] is returned. {END}
89525 **
89526 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
89527 ** recommended for all new programs. The two older interfaces are retained
89528 ** for backwards compatibility, but their use is discouraged.
89529 ** {F13020} In the "v2" interfaces, the prepared statement
89530 ** that is returned (the [sqlite3_stmt] object) contains a copy of the 
89531 ** original SQL text. {END} This causes the [sqlite3_step()] interface to
89532 ** behave a differently in two ways:
89533 **
89534 ** <ol>
89535 ** <li>{F13022}
89536 ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
89537 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
89538 ** statement and try to run it again. {F12023} If the schema has changed in
89539 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
89540 ** return [SQLITE_SCHEMA].  {END} But unlike the legacy behavior, 
89541 ** [SQLITE_SCHEMA] is now a fatal error.  {F12024} Calling
89542 ** [sqlite3_prepare_v2()] again will not make the
89543 ** error go away.  {F12025} Note: use [sqlite3_errmsg()] to find the text
89544 ** of the parsing error that results in an [SQLITE_SCHEMA] return. {END}
89545 ** </li>
89546 **
89547 ** <li>
89548 ** {F13030} When an error occurs, 
89549 ** [sqlite3_step()] will return one of the detailed 
89550 ** [SQLITE_ERROR | result codes] or
89551 ** [SQLITE_IOERR_READ | extended result codes].  {F13031}
89552 ** The legacy behavior was that [sqlite3_step()] would only return a generic
89553 ** [SQLITE_ERROR] result code and you would have to make a second call to
89554 ** [sqlite3_reset()] in order to find the underlying cause of the problem.
89555 ** {F13032}
89556 ** With the "v2" prepare interfaces, the underlying reason for the error is
89557 ** returned immediately. {END}
89558 ** </li>
89559 ** </ol>
89560 */
89561 int sqlite3_prepare(
89562   sqlite3 *db,            /* Database handle */
89563   const char *zSql,       /* SQL statement, UTF-8 encoded */
89564   int nByte,              /* Maximum length of zSql in bytes. */
89565   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
89566   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
89567 );
89568 int sqlite3_prepare_v2(
89569   sqlite3 *db,            /* Database handle */
89570   const char *zSql,       /* SQL statement, UTF-8 encoded */
89571   int nByte,              /* Maximum length of zSql in bytes. */
89572   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
89573   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
89574 );
89575 int sqlite3_prepare16(
89576   sqlite3 *db,            /* Database handle */
89577   const void *zSql,       /* SQL statement, UTF-16 encoded */
89578   int nByte,              /* Maximum length of zSql in bytes. */
89579   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
89580   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
89581 );
89582 int sqlite3_prepare16_v2(
89583   sqlite3 *db,            /* Database handle */
89584   const void *zSql,       /* SQL statement, UTF-16 encoded */
89585   int nByte,              /* Maximum length of zSql in bytes. */
89586   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
89587   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
89588 );
89589
89590 /*
89591 ** CAPIREF: Retrieving Statement SQL {F13100}
89592 **
89593 ** {F13101} If the compiled SQL statement passed as an argument was
89594 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()],
89595 ** then this function returns a pointer to a zero-terminated string
89596 ** containing a copy of the original SQL statement. {F13102} The
89597 ** pointer is valid until the statement
89598 ** is deleted using sqlite3_finalize().
89599 ** {F13103} The string returned by sqlite3_sql() is always UTF8 even
89600 ** if a UTF16 string was originally entered using [sqlite3_prepare16_v2()]
89601 ** or the equivalent.
89602 **
89603 ** {F13104} If the statement was compiled using either of the legacy
89604 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this
89605 ** function returns NULL.
89606 */
89607 const char *sqlite3_sql(sqlite3_stmt *pStmt);
89608
89609 /*
89610 ** CAPI3REF:  Dynamically Typed Value Object  {F15000}
89611 **
89612 ** {F15001} SQLite uses the sqlite3_value object to represent all values
89613 ** that are or can be stored in a database table. {END}
89614 ** SQLite uses dynamic typing for the values it stores.  
89615 ** {F15002} Values stored in sqlite3_value objects can be
89616 ** be integers, floating point values, strings, BLOBs, or NULL.
89617 */
89618 typedef struct Mem sqlite3_value;
89619
89620 /*
89621 ** CAPI3REF:  SQL Function Context Object {F16001}
89622 **
89623 ** The context in which an SQL function executes is stored in an
89624 ** sqlite3_context object.  {F16002} A pointer to an sqlite3_context
89625 ** object is always first parameter to application-defined SQL functions.
89626 */
89627 typedef struct sqlite3_context sqlite3_context;
89628
89629 /*
89630 ** CAPI3REF:  Binding Values To Prepared Statements {F13500}
89631 **
89632 ** {F13501} In the SQL strings input to [sqlite3_prepare_v2()] and its
89633 ** variants, literals may be replace by a parameter in one
89634 ** of these forms:
89635 **
89636 ** <ul>
89637 ** <li>  ?
89638 ** <li>  ?NNN
89639 ** <li>  :AAA
89640 ** <li>  @AAA
89641 ** <li>  $VVV
89642 ** </ul>
89643 **
89644 ** In the parameter forms shown above NNN is an integer literal,
89645 ** AAA is an alphanumeric identifier and VVV is a variable name according
89646 ** to the syntax rules of the TCL programming language. {END}
89647 ** The values of these parameters (also called "host parameter names")
89648 ** can be set using the sqlite3_bind_*() routines defined here.
89649 **
89650 ** {F13502} The first argument to the sqlite3_bind_*() routines always
89651 ** is a pointer to the [sqlite3_stmt] object returned from
89652 ** [sqlite3_prepare_v2()] or its variants.  {F13503} The second
89653 ** argument is the index of the parameter to be set.  {F13504} The
89654 ** first parameter has an index of 1.  {F13505} When the same named
89655 ** parameter is used more than once, second and subsequent
89656 ** occurrences have the same index as the first occurrence. 
89657 ** {F13506} The index for named parameters can be looked up using the
89658 ** [sqlite3_bind_parameter_name()] API if desired.  {F13507} The index
89659 ** for "?NNN" parameters is the value of NNN.
89660 ** {F13508} The NNN value must be between 1 and the compile-time
89661 ** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). {END}
89662 ** See <a href="limits.html">limits.html</a> for additional information.
89663 **
89664 ** {F13509} The third argument is the value to bind to the parameter. {END}
89665 **
89666 ** {F13510} In those
89667 ** routines that have a fourth argument, its value is the number of bytes
89668 ** in the parameter.  To be clear: the value is the number of bytes in the
89669 ** string, not the number of characters. {F13511}  The number
89670 ** of bytes does not include the zero-terminator at the end of strings.
89671 ** {F13512}
89672 ** If the fourth parameter is negative, the length of the string is
89673 ** number of bytes up to the first zero terminator. {END}
89674 **
89675 ** {F13513}
89676 ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
89677 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
89678 ** text after SQLite has finished with it. {F13514} If the fifth argument is
89679 ** the special value [SQLITE_STATIC], then the library assumes that the
89680 ** information is in static, unmanaged space and does not need to be freed.
89681 ** {F13515} If the fifth argument has the value [SQLITE_TRANSIENT], then
89682 ** SQLite makes its own private copy of the data immediately, before
89683 ** the sqlite3_bind_*() routine returns. {END}
89684 **
89685 ** {F13520} The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
89686 ** is filled with zeros.  {F13521} A zeroblob uses a fixed amount of memory
89687 ** (just an integer to hold it size) while it is being processed. {END}
89688 ** Zeroblobs are intended to serve as place-holders for BLOBs whose
89689 ** content is later written using 
89690 ** [sqlite3_blob_open | increment BLOB I/O] routines. {F13522} A negative
89691 ** value for the zeroblob results in a zero-length BLOB. {END}
89692 **
89693 ** {F13530} The sqlite3_bind_*() routines must be called after
89694 ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and
89695 ** before [sqlite3_step()]. {F13531}
89696 ** Bindings are not cleared by the [sqlite3_reset()] routine.
89697 ** {F13532} Unbound parameters are interpreted as NULL. {END}
89698 **
89699 ** {F13540} These routines return [SQLITE_OK] on success or an error code if
89700 ** anything goes wrong.  {F13541} [SQLITE_RANGE] is returned if the parameter
89701 ** index is out of range.  {F13542} [SQLITE_NOMEM] is returned if malloc fails.
89702 ** {F13543} [SQLITE_MISUSE] is returned if these routines are called on a
89703 ** virtual machine that is the wrong state or which has already been finalized.
89704 */
89705 int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
89706 int sqlite3_bind_double(sqlite3_stmt*, int, double);
89707 int sqlite3_bind_int(sqlite3_stmt*, int, int);
89708 int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
89709 int sqlite3_bind_null(sqlite3_stmt*, int);
89710 int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
89711 int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
89712 int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
89713 int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
89714
89715 /*
89716 ** CAPI3REF: Number Of Host Parameters {F13600}
89717 **
89718 ** {F13601} Return the largest host parameter index in the precompiled
89719 ** statement given as the argument. {F13602} When the host parameters
89720 ** are of the forms like ":AAA", "$VVV", "@AAA", or "?",
89721 ** then they are assigned sequential increasing numbers beginning
89722 ** with one, so the value returned is the number of parameters.
89723 ** {F13603} However
89724 ** if the same host parameter name is used multiple times, each occurrance
89725 ** is given the same number, so the value returned in that case is the number
89726 ** of unique host parameter names. {F13604} If host parameters of the
89727 ** form "?NNN" are used (where NNN is an integer) then there might be
89728 ** gaps in the numbering and the value returned by this interface is
89729 ** the index of the host parameter with the largest index value. {END}
89730 **
89731 ** {U13605} The prepared statement must not be [sqlite3_finalize | finalized]
89732 ** prior to this routine returning.  Otherwise the results are undefined
89733 ** and probably undesirable.
89734 */
89735 int sqlite3_bind_parameter_count(sqlite3_stmt*);
89736
89737 /*
89738 ** CAPI3REF: Name Of A Host Parameter {F13620}
89739 **
89740 ** {F13621} This routine returns a pointer to the name of the n-th
89741 ** parameter in a [sqlite3_stmt | prepared statement]. {F13622}
89742 ** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name
89743 ** which is the string ":AAA" or "@AAA" or "$VVV". 
89744 ** In other words, the initial ":" or "$" or "@"
89745 ** is included as part of the name.  {F13626}
89746 ** Parameters of the form "?" or "?NNN" have no name.
89747 **
89748 ** {F13623} The first host parameter has an index of 1, not 0.
89749 **
89750 ** {F13624} If the value n is out of range or if the n-th parameter is
89751 ** nameless, then NULL is returned.  {F13625} The returned string is
89752 ** always in the UTF-8 encoding even if the named parameter was
89753 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
89754 ** [sqlite3_prepare16_v2()].
89755 */
89756 const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
89757
89758 /*
89759 ** CAPI3REF: Index Of A Parameter With A Given Name {F13640}
89760 **
89761 ** {F13641} This routine returns the index of a host parameter with the
89762 ** given name.  {F13642} The name must match exactly.  {F13643}
89763 ** If no parameter with the given name is found, return 0.
89764 ** {F13644} Parameter names must be UTF8.
89765 */
89766 int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
89767
89768 /*
89769 ** CAPI3REF: Reset All Bindings On A Prepared Statement {F13660}
89770 **
89771 ** {F13661} Contrary to the intuition of many, [sqlite3_reset()] does not
89772 ** reset the [sqlite3_bind_blob | bindings] on a 
89773 ** [sqlite3_stmt | prepared statement]. {F13662} Use this routine to
89774 ** reset all host parameters to NULL.
89775 */
89776 int sqlite3_clear_bindings(sqlite3_stmt*);
89777
89778 /*
89779 ** CAPI3REF: Number Of Columns In A Result Set {F13710}
89780 **
89781 ** {F13711} Return the number of columns in the result set returned by the 
89782 ** [sqlite3_stmt | compiled SQL statement]. {F13712} This routine returns 0
89783 ** if pStmt is an SQL statement that does not return data (for 
89784 ** example an UPDATE).
89785 */
89786 int sqlite3_column_count(sqlite3_stmt *pStmt);
89787
89788 /*
89789 ** CAPI3REF: Column Names In A Result Set {F13720}
89790 **
89791 ** {F13721} These routines return the name assigned to a particular column
89792 ** in the result set of a SELECT statement.  {F13722} The sqlite3_column_name()
89793 ** interface returns a pointer to a zero-terminated UTF8 string
89794 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
89795 ** UTF16 string. {F13723}  The first parameter is the
89796 ** [sqlite3_stmt | prepared statement] that implements the SELECT statement.
89797 ** The second parameter is the column number.  The left-most column is
89798 ** number 0.
89799 **
89800 ** {F13724} The returned string pointer is valid until either the 
89801 ** [sqlite3_stmt | prepared statement] is destroyed by [sqlite3_finalize()]
89802 ** or until the next call sqlite3_column_name() or sqlite3_column_name16()
89803 ** on the same column.
89804 **
89805 ** {F13725} If sqlite3_malloc() fails during the processing of either routine
89806 ** (for example during a conversion from UTF-8 to UTF-16) then a
89807 ** NULL pointer is returned.
89808 */
89809 const char *sqlite3_column_name(sqlite3_stmt*, int N);
89810 const void *sqlite3_column_name16(sqlite3_stmt*, int N);
89811
89812 /*
89813 ** CAPI3REF: Source Of Data In A Query Result {F13740}
89814 **
89815 ** {F13741} These routines provide a means to determine what column of what
89816 ** table in which database a result of a SELECT statement comes from.
89817 ** {F13742} The name of the database or table or column can be returned as
89818 ** either a UTF8 or UTF16 string.  {F13743} The _database_ routines return
89819 ** the database name, the _table_ routines return the table name, and
89820 ** the origin_ routines return the column name. {F13744}
89821 ** The returned string is valid until
89822 ** the [sqlite3_stmt | prepared statement] is destroyed using
89823 ** [sqlite3_finalize()] or until the same information is requested
89824 ** again in a different encoding.
89825 **
89826 ** {F13745} The names returned are the original un-aliased names of the
89827 ** database, table, and column.
89828 **
89829 ** {F13746} The first argument to the following calls is a 
89830 ** [sqlite3_stmt | compiled SQL statement].
89831 ** {F13747} These functions return information about the Nth column returned by 
89832 ** the statement, where N is the second function argument.
89833 **
89834 ** {F13748} If the Nth column returned by the statement is an expression
89835 ** or subquery and is not a column value, then all of these functions
89836 ** return NULL.  {F13749} Otherwise, they return the 
89837 ** name of the attached database, table and column that query result
89838 ** column was extracted from.
89839 **
89840 ** {F13750} As with all other SQLite APIs, those postfixed with "16" return
89841 ** UTF-16 encoded strings, the other functions return UTF-8. {END}
89842 **
89843 ** These APIs are only available if the library was compiled with the 
89844 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
89845 **
89846 ** {U13751}
89847 ** If two or more threads call one or more of these routines against the same
89848 ** prepared statement and column at the same time then the results are
89849 ** undefined.
89850 */
89851 const char *sqlite3_column_database_name(sqlite3_stmt*,int);
89852 const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
89853 const char *sqlite3_column_table_name(sqlite3_stmt*,int);
89854 const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
89855 const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
89856 const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
89857
89858 /*
89859 ** CAPI3REF: Declared Datatype Of A Query Result {F13760}
89860 **
89861 ** The first parameter is a [sqlite3_stmt | compiled SQL statement]. 
89862 ** {F13761} If this statement is a SELECT statement and the Nth column of the 
89863 ** returned result set of that SELECT is a table column (not an
89864 ** expression or subquery) then the declared type of the table
89865 ** column is returned.  {F13762} If the Nth column of the result set is an
89866 ** expression or subquery, then a NULL pointer is returned.
89867 ** {F13763} The returned string is always UTF-8 encoded.  {END} 
89868 ** For example, in the database schema:
89869 **
89870 ** CREATE TABLE t1(c1 VARIANT);
89871 **
89872 ** And the following statement compiled:
89873 **
89874 ** SELECT c1 + 1, c1 FROM t1;
89875 **
89876 ** Then this routine would return the string "VARIANT" for the second
89877 ** result column (i==1), and a NULL pointer for the first result column
89878 ** (i==0).
89879 **
89880 ** SQLite uses dynamic run-time typing.  So just because a column
89881 ** is declared to contain a particular type does not mean that the
89882 ** data stored in that column is of the declared type.  SQLite is
89883 ** strongly typed, but the typing is dynamic not static.  Type
89884 ** is associated with individual values, not with the containers
89885 ** used to hold those values.
89886 */
89887 const char *sqlite3_column_decltype(sqlite3_stmt *, int i);
89888 const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
89889
89890 /* 
89891 ** CAPI3REF:  Evaluate An SQL Statement {F13200}
89892 **
89893 ** After an [sqlite3_stmt | SQL statement] has been prepared with a call
89894 ** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of
89895 ** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()],
89896 ** then this function must be called one or more times to evaluate the 
89897 ** statement.
89898 **
89899 ** The details of the behavior of this sqlite3_step() interface depend
89900 ** on whether the statement was prepared using the newer "v2" interface
89901 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
89902 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
89903 ** new "v2" interface is recommended for new applications but the legacy
89904 ** interface will continue to be supported.
89905 **
89906 ** In the lagacy interface, the return value will be either [SQLITE_BUSY], 
89907 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
89908 ** With the "v2" interface, any of the other [SQLITE_OK | result code]
89909 ** or [SQLITE_IOERR_READ | extended result code] might be returned as
89910 ** well.
89911 **
89912 ** [SQLITE_BUSY] means that the database engine was unable to acquire the
89913 ** database locks it needs to do its job.  If the statement is a COMMIT
89914 ** or occurs outside of an explicit transaction, then you can retry the
89915 ** statement.  If the statement is not a COMMIT and occurs within a
89916 ** explicit transaction then you should rollback the transaction before
89917 ** continuing.
89918 **
89919 ** [SQLITE_DONE] means that the statement has finished executing
89920 ** successfully.  sqlite3_step() should not be called again on this virtual
89921 ** machine without first calling [sqlite3_reset()] to reset the virtual
89922 ** machine back to its initial state.
89923 **
89924 ** If the SQL statement being executed returns any data, then 
89925 ** [SQLITE_ROW] is returned each time a new row of data is ready
89926 ** for processing by the caller. The values may be accessed using
89927 ** the [sqlite3_column_int | column access functions].
89928 ** sqlite3_step() is called again to retrieve the next row of data.
89929 ** 
89930 ** [SQLITE_ERROR] means that a run-time error (such as a constraint
89931 ** violation) has occurred.  sqlite3_step() should not be called again on
89932 ** the VM. More information may be found by calling [sqlite3_errmsg()].
89933 ** With the legacy interface, a more specific error code (example:
89934 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
89935 ** can be obtained by calling [sqlite3_reset()] on the
89936 ** [sqlite3_stmt | prepared statement].  In the "v2" interface,
89937 ** the more specific error code is returned directly by sqlite3_step().
89938 **
89939 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
89940 ** Perhaps it was called on a [sqlite3_stmt | prepared statement] that has
89941 ** already been [sqlite3_finalize | finalized] or on one that had 
89942 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
89943 ** be the case that the same database connection is being used by two or
89944 ** more threads at the same moment in time.
89945 **
89946 ** <b>Goofy Interface Alert:</b>
89947 ** In the legacy interface, 
89948 ** the sqlite3_step() API always returns a generic error code,
89949 ** [SQLITE_ERROR], following any error other than [SQLITE_BUSY]
89950 ** and [SQLITE_MISUSE].  You must call [sqlite3_reset()] or
89951 ** [sqlite3_finalize()] in order to find one of the specific
89952 ** [SQLITE_ERROR | result codes] that better describes the error.
89953 ** We admit that this is a goofy design.  The problem has been fixed
89954 ** with the "v2" interface.  If you prepare all of your SQL statements
89955 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
89956 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the 
89957 ** more specific [SQLITE_ERROR | result codes] are returned directly
89958 ** by sqlite3_step().  The use of the "v2" interface is recommended.
89959 */
89960 int sqlite3_step(sqlite3_stmt*);
89961
89962 /*
89963 ** CAPI3REF: Number of columns in a result set {F13770}
89964 **
89965 ** Return the number of values in the current row of the result set.
89966 **
89967 ** {F13771} After a call to [sqlite3_step()] that returns [SQLITE_ROW],
89968 ** this routine
89969 ** will return the same value as the [sqlite3_column_count()] function.
89970 ** {F13772}
89971 ** After [sqlite3_step()] has returned an [SQLITE_DONE], [SQLITE_BUSY], or
89972 ** a [SQLITE_ERROR | error code], or before [sqlite3_step()] has been 
89973 ** called on the [sqlite3_stmt | prepared statement] for the first time,
89974 ** this routine returns zero.
89975 */
89976 int sqlite3_data_count(sqlite3_stmt *pStmt);
89977
89978 /*
89979 ** CAPI3REF: Fundamental Datatypes {F10265}
89980 **
89981 ** {F10266}Every value in SQLite has one of five fundamental datatypes:
89982 **
89983 ** <ul>
89984 ** <li> 64-bit signed integer
89985 ** <li> 64-bit IEEE floating point number
89986 ** <li> string
89987 ** <li> BLOB
89988 ** <li> NULL
89989 ** </ul> {END}
89990 **
89991 ** These constants are codes for each of those types.
89992 **
89993 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
89994 ** for a completely different meaning.  Software that links against both
89995 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not
89996 ** SQLITE_TEXT.
89997 */
89998 #define SQLITE_INTEGER  1
89999 #define SQLITE_FLOAT    2
90000 #define SQLITE_BLOB     4
90001 #define SQLITE_NULL     5
90002 #ifdef SQLITE_TEXT
90003 # undef SQLITE_TEXT
90004 #else
90005 # define SQLITE_TEXT     3
90006 #endif
90007 #define SQLITE3_TEXT     3
90008
90009 /*
90010 ** CAPI3REF: Results Values From A Query {F13800}
90011 **
90012 ** These routines return information about
90013 ** a single column of the current result row of a query.  In every
90014 ** case the first argument is a pointer to the 
90015 ** [sqlite3_stmt | SQL statement] that is being
90016 ** evaluated (the [sqlite3_stmt*] that was returned from 
90017 ** [sqlite3_prepare_v2()] or one of its variants) and
90018 ** the second argument is the index of the column for which information 
90019 ** should be returned.  The left-most column of the result set
90020 ** has an index of 0.
90021 **
90022 ** If the SQL statement is not currently point to a valid row, or if the
90023 ** the column index is out of range, the result is undefined. 
90024 ** These routines may only be called when the most recent call to
90025 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
90026 ** [sqlite3_reset()] nor [sqlite3_finalize()] has been call subsequently.
90027 ** If any of these routines are called after [sqlite3_reset()] or
90028 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
90029 ** something other than [SQLITE_ROW], the results are undefined.
90030 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
90031 ** are called from a different thread while any of these routines
90032 ** are pending, then the results are undefined.  
90033 **
90034 ** The sqlite3_column_type() routine returns 
90035 ** [SQLITE_INTEGER | datatype code] for the initial data type
90036 ** of the result column.  The returned value is one of [SQLITE_INTEGER],
90037 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
90038 ** returned by sqlite3_column_type() is only meaningful if no type
90039 ** conversions have occurred as described below.  After a type conversion,
90040 ** the value returned by sqlite3_column_type() is undefined.  Future
90041 ** versions of SQLite may change the behavior of sqlite3_column_type()
90042 ** following a type conversion.
90043 **
90044 ** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() 
90045 ** routine returns the number of bytes in that BLOB or string.
90046 ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
90047 ** the string to UTF-8 and then returns the number of bytes.
90048 ** If the result is a numeric value then sqlite3_column_bytes() uses
90049 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
90050 ** the number of bytes in that string.
90051 ** The value returned does not include the zero terminator at the end
90052 ** of the string.  For clarity: the value returned is the number of
90053 ** bytes in the string, not the number of characters.
90054 **
90055 ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
90056 ** even zero-length strings, are always zero terminated.  The return
90057 ** value from sqlite3_column_blob() for a zero-length blob is an arbitrary
90058 ** pointer, possibly even a NULL pointer.
90059 **
90060 ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
90061 ** but leaves the result in UTF-16 instead of UTF-8.  
90062 ** The zero terminator is not included in this count.
90063 **
90064 ** These routines attempt to convert the value where appropriate.  For
90065 ** example, if the internal representation is FLOAT and a text result
90066 ** is requested, [sqlite3_snprintf()] is used internally to do the conversion
90067 ** automatically.  The following table details the conversions that
90068 ** are applied:
90069 **
90070 ** <blockquote>
90071 ** <table border="1">
90072 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
90073 **
90074 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
90075 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
90076 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
90077 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
90078 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
90079 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
90080 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as for INTEGER->TEXT
90081 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
90082 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
90083 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
90084 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
90085 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
90086 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
90087 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
90088 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
90089 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
90090 ** </table>
90091 ** </blockquote>
90092 **
90093 ** The table above makes reference to standard C library functions atoi()
90094 ** and atof().  SQLite does not really use these functions.  It has its
90095 ** on equavalent internal routines.  The atoi() and atof() names are
90096 ** used in the table for brevity and because they are familiar to most
90097 ** C programmers.
90098 **
90099 ** Note that when type conversions occur, pointers returned by prior
90100 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
90101 ** sqlite3_column_text16() may be invalidated. 
90102 ** Type conversions and pointer invalidations might occur
90103 ** in the following cases:
90104 **
90105 ** <ul>
90106 ** <li><p>  The initial content is a BLOB and sqlite3_column_text() 
90107 **          or sqlite3_column_text16() is called.  A zero-terminator might
90108 **          need to be added to the string.</p></li>
90109 **
90110 ** <li><p>  The initial content is UTF-8 text and sqlite3_column_bytes16() or
90111 **          sqlite3_column_text16() is called.  The content must be converted
90112 **          to UTF-16.</p></li>
90113 **
90114 ** <li><p>  The initial content is UTF-16 text and sqlite3_column_bytes() or
90115 **          sqlite3_column_text() is called.  The content must be converted
90116 **          to UTF-8.</p></li>
90117 ** </ul>
90118 **
90119 ** Conversions between UTF-16be and UTF-16le are always done in place and do
90120 ** not invalidate a prior pointer, though of course the content of the buffer
90121 ** that the prior pointer points to will have been modified.  Other kinds
90122 ** of conversion are done in place when it is possible, but sometime it is
90123 ** not possible and in those cases prior pointers are invalidated.  
90124 **
90125 ** The safest and easiest to remember policy is to invoke these routines
90126 ** in one of the following ways:
90127 **
90128 **  <ul>
90129 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
90130 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
90131 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
90132 **  </ul>
90133 **
90134 ** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(),
90135 ** or sqlite3_column_text16() first to force the result into the desired
90136 ** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to
90137 ** find the size of the result.  Do not mix call to sqlite3_column_text() or
90138 ** sqlite3_column_blob() with calls to sqlite3_column_bytes16().  And do not
90139 ** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes().
90140 **
90141 ** The pointers returned are valid until a type conversion occurs as
90142 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
90143 ** [sqlite3_finalize()] is called.  The memory space used to hold strings
90144 ** and blobs is freed automatically.  Do <b>not</b> pass the pointers returned
90145 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into 
90146 ** [sqlite3_free()].
90147 **
90148 ** If a memory allocation error occurs during the evaluation of any
90149 ** of these routines, a default value is returned.  The default value
90150 ** is either the integer 0, the floating point number 0.0, or a NULL
90151 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
90152 ** [SQLITE_NOMEM].
90153 */
90154 const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
90155 int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
90156 int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
90157 double sqlite3_column_double(sqlite3_stmt*, int iCol);
90158 int sqlite3_column_int(sqlite3_stmt*, int iCol);
90159 sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
90160 const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
90161 const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
90162 int sqlite3_column_type(sqlite3_stmt*, int iCol);
90163 sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
90164
90165 /*
90166 ** CAPI3REF: Destroy A Prepared Statement Object {F13300}
90167 **
90168 ** The sqlite3_finalize() function is called to delete a 
90169 ** [sqlite3_stmt | compiled SQL statement]. If the statement was
90170 ** executed successfully, or not executed at all, then SQLITE_OK is returned.
90171 ** If execution of the statement failed then an 
90172 ** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code]
90173 ** is returned. 
90174 **
90175 ** This routine can be called at any point during the execution of the
90176 ** [sqlite3_stmt | virtual machine].  If the virtual machine has not 
90177 ** completed execution when this routine is called, that is like
90178 ** encountering an error or an interrupt.  (See [sqlite3_interrupt()].) 
90179 ** Incomplete updates may be rolled back and transactions cancelled,  
90180 ** depending on the circumstances, and the 
90181 ** [SQLITE_ERROR | result code] returned will be [SQLITE_ABORT].
90182 */
90183 int sqlite3_finalize(sqlite3_stmt *pStmt);
90184
90185 /*
90186 ** CAPI3REF: Reset A Prepared Statement Object {F13330}
90187 **
90188 ** The sqlite3_reset() function is called to reset a 
90189 ** [sqlite3_stmt | compiled SQL statement] object.
90190 ** back to its initial state, ready to be re-executed.
90191 ** Any SQL statement variables that had values bound to them using
90192 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
90193 ** Use [sqlite3_clear_bindings()] to reset the bindings.
90194 */
90195 int sqlite3_reset(sqlite3_stmt *pStmt);
90196
90197 /*
90198 ** CAPI3REF: Create Or Redefine SQL Functions {F16100}
90199 **
90200 ** The following two functions are used to add SQL functions or aggregates
90201 ** or to redefine the behavior of existing SQL functions or aggregates.  The
90202 ** difference only between the two is that the second parameter, the
90203 ** name of the (scalar) function or aggregate, is encoded in UTF-8 for
90204 ** sqlite3_create_function() and UTF-16 for sqlite3_create_function16().
90205 **
90206 ** The first argument is the [sqlite3 | database handle] that holds the
90207 ** SQL function or aggregate is to be added or redefined. If a single
90208 ** program uses more than one database handle internally, then SQL
90209 ** functions or aggregates must be added individually to each database
90210 ** handle with which they will be used.
90211 **
90212 ** The second parameter is the name of the SQL function to be created
90213 ** or redefined.
90214 ** The length of the name is limited to 255 bytes, exclusive of the 
90215 ** zero-terminator.  Note that the name length limit is in bytes, not
90216 ** characters.  Any attempt to create a function with a longer name
90217 ** will result in an SQLITE_ERROR error.
90218 **
90219 ** The third parameter is the number of arguments that the SQL function or
90220 ** aggregate takes. If this parameter is negative, then the SQL function or
90221 ** aggregate may take any number of arguments.
90222 **
90223 ** The fourth parameter, eTextRep, specifies what 
90224 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
90225 ** its parameters.  Any SQL function implementation should be able to work
90226 ** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
90227 ** more efficient with one encoding than another.  It is allowed to
90228 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
90229 ** times with the same function but with different values of eTextRep.
90230 ** When multiple implementations of the same function are available, SQLite
90231 ** will pick the one that involves the least amount of data conversion.
90232 ** If there is only a single implementation which does not care what
90233 ** text encoding is used, then the fourth argument should be
90234 ** [SQLITE_ANY].
90235 **
90236 ** The fifth parameter is an arbitrary pointer.  The implementation
90237 ** of the function can gain access to this pointer using
90238 ** [sqlite3_user_data()].
90239 **
90240 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
90241 ** pointers to C-language functions that implement the SQL
90242 ** function or aggregate. A scalar SQL function requires an implementation of
90243 ** the xFunc callback only, NULL pointers should be passed as the xStep
90244 ** and xFinal parameters. An aggregate SQL function requires an implementation
90245 ** of xStep and xFinal and NULL should be passed for xFunc. To delete an
90246 ** existing SQL function or aggregate, pass NULL for all three function
90247 ** callback.
90248 **
90249 ** It is permitted to register multiple implementations of the same
90250 ** functions with the same name but with either differing numbers of
90251 ** arguments or differing perferred text encodings.  SQLite will use
90252 ** the implementation most closely matches the way in which the
90253 ** SQL function is used.
90254 */
90255 int sqlite3_create_function(
90256   sqlite3 *,
90257   const char *zFunctionName,
90258   int nArg,
90259   int eTextRep,
90260   void*,
90261   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
90262   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
90263   void (*xFinal)(sqlite3_context*)
90264 );
90265 int sqlite3_create_function16(
90266   sqlite3*,
90267   const void *zFunctionName,
90268   int nArg,
90269   int eTextRep,
90270   void*,
90271   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
90272   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
90273   void (*xFinal)(sqlite3_context*)
90274 );
90275
90276 /*
90277 ** CAPI3REF: Text Encodings {F10267}
90278 **
90279 ** These constant define integer codes that represent the various
90280 ** text encodings supported by SQLite.
90281 */
90282 #define SQLITE_UTF8           1
90283 #define SQLITE_UTF16LE        2
90284 #define SQLITE_UTF16BE        3
90285 #define SQLITE_UTF16          4    /* Use native byte order */
90286 #define SQLITE_ANY            5    /* sqlite3_create_function only */
90287 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
90288
90289 /*
90290 ** CAPI3REF: Obsolete Functions
90291 **
90292 ** These functions are all now obsolete.  In order to maintain
90293 ** backwards compatibility with older code, we continue to support
90294 ** these functions.  However, new development projects should avoid
90295 ** the use of these functions.  To help encourage people to avoid
90296 ** using these functions, we are not going to tell you want they do.
90297 */
90298 int sqlite3_aggregate_count(sqlite3_context*);
90299 int sqlite3_expired(sqlite3_stmt*);
90300 int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
90301 int sqlite3_global_recover(void);
90302 void sqlite3_thread_cleanup(void);
90303 int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
90304
90305 /*
90306 ** CAPI3REF: Obtaining SQL Function Parameter Values {F15100}
90307 **
90308 ** The C-language implementation of SQL functions and aggregates uses
90309 ** this set of interface routines to access the parameter values on
90310 ** the function or aggregate.
90311 **
90312 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
90313 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
90314 ** define callbacks that implement the SQL functions and aggregates.
90315 ** The 4th parameter to these callbacks is an array of pointers to
90316 ** [sqlite3_value] objects.  There is one [sqlite3_value] object for
90317 ** each parameter to the SQL function.  These routines are used to
90318 ** extract values from the [sqlite3_value] objects.
90319 **
90320 ** These routines work just like the corresponding 
90321 ** [sqlite3_column_blob | sqlite3_column_* routines] except that 
90322 ** these routines take a single [sqlite3_value*] pointer instead
90323 ** of an [sqlite3_stmt*] pointer and an integer column number.
90324 **
90325 ** The sqlite3_value_text16() interface extracts a UTF16 string
90326 ** in the native byte-order of the host machine.  The
90327 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
90328 ** extract UTF16 strings as big-endian and little-endian respectively.
90329 **
90330 ** The sqlite3_value_numeric_type() interface attempts to apply
90331 ** numeric affinity to the value.  This means that an attempt is
90332 ** made to convert the value to an integer or floating point.  If
90333 ** such a conversion is possible without loss of information (in other
90334 ** words if the value is a string that looks like a number)
90335 ** then the conversion is done.  Otherwise no conversion occurs.  The 
90336 ** [SQLITE_INTEGER | datatype] after conversion is returned.
90337 **
90338 ** Please pay particular attention to the fact that the pointer that
90339 ** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or
90340 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
90341 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
90342 ** or [sqlite3_value_text16()].  
90343 **
90344 ** These routines must be called from the same thread as
90345 ** the SQL function that supplied the sqlite3_value* parameters.
90346 ** Or, if the sqlite3_value* argument comes from the [sqlite3_column_value()]
90347 ** interface, then these routines should be called from the same thread
90348 ** that ran [sqlite3_column_value()].
90349 **
90350 */
90351 const void *sqlite3_value_blob(sqlite3_value*);
90352 int sqlite3_value_bytes(sqlite3_value*);
90353 int sqlite3_value_bytes16(sqlite3_value*);
90354 double sqlite3_value_double(sqlite3_value*);
90355 int sqlite3_value_int(sqlite3_value*);
90356 sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
90357 const unsigned char *sqlite3_value_text(sqlite3_value*);
90358 const void *sqlite3_value_text16(sqlite3_value*);
90359 const void *sqlite3_value_text16le(sqlite3_value*);
90360 const void *sqlite3_value_text16be(sqlite3_value*);
90361 int sqlite3_value_type(sqlite3_value*);
90362 int sqlite3_value_numeric_type(sqlite3_value*);
90363
90364 /*
90365 ** CAPI3REF: Obtain Aggregate Function Context {F16210}
90366 **
90367 ** The implementation of aggregate SQL functions use this routine to allocate
90368 ** a structure for storing their state.  
90369 ** {F16211} The first time the sqlite3_aggregate_context() routine is
90370 ** is called for a particular aggregate, SQLite allocates nBytes of memory
90371 ** zeros that memory, and returns a pointer to it.
90372 ** {F16212} On second and subsequent calls to sqlite3_aggregate_context()
90373 ** for the same aggregate function index, the same buffer is returned. {END}
90374 ** The implementation
90375 ** of the aggregate can use the returned buffer to accumulate data.
90376 **
90377 ** {F16213} SQLite automatically frees the allocated buffer when the aggregate
90378 ** query concludes. {END}
90379 **
90380 ** The first parameter should be a copy of the 
90381 ** [sqlite3_context | SQL function context] that is the first
90382 ** parameter to the callback routine that implements the aggregate
90383 ** function.
90384 **
90385 ** This routine must be called from the same thread in which
90386 ** the aggregate SQL function is running.
90387 */
90388 void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
90389
90390 /*
90391 ** CAPI3REF: User Data For Functions {F16240}
90392 **
90393 ** {F16241} The sqlite3_user_data() interface returns a copy of
90394 ** the pointer that was the pUserData parameter (the 5th parameter)
90395 ** of the the [sqlite3_create_function()]
90396 ** and [sqlite3_create_function16()] routines that originally
90397 ** registered the application defined function. {END}
90398 **
90399 ** {U16243} This routine must be called from the same thread in which
90400 ** the application-defined function is running.
90401 */
90402 void *sqlite3_user_data(sqlite3_context*);
90403
90404 /*
90405 ** CAPI3REF: Function Auxiliary Data {F16270}
90406 **
90407 ** The following two functions may be used by scalar SQL functions to
90408 ** associate meta-data with argument values. If the same value is passed to
90409 ** multiple invocations of the same SQL function during query execution, under
90410 ** some circumstances the associated meta-data may be preserved. This may
90411 ** be used, for example, to add a regular-expression matching scalar
90412 ** function. The compiled version of the regular expression is stored as
90413 ** meta-data associated with the SQL value passed as the regular expression
90414 ** pattern.  The compiled regular expression can be reused on multiple
90415 ** invocations of the same function so that the original pattern string
90416 ** does not need to be recompiled on each invocation.
90417 **
90418 ** {F16271}
90419 ** The sqlite3_get_auxdata() interface returns a pointer to the meta-data
90420 ** associated by the sqlite3_set_auxdata() function with the Nth argument
90421 ** value to the application-defined function.
90422 ** {F16272} If no meta-data has been ever been set for the Nth
90423 ** argument of the function, or if the cooresponding function parameter
90424 ** has changed since the meta-data was set, then sqlite3_get_auxdata()
90425 ** returns a NULL pointer.
90426 **
90427 ** {F16275} The sqlite3_set_auxdata() interface saves the meta-data
90428 ** pointed to by its 3rd parameter as the meta-data for the N-th
90429 ** argument of the application-defined function. {END} Subsequent
90430 ** calls to sqlite3_get_auxdata() might return this data, if it has
90431 ** not been destroyed. 
90432 ** {F16277} If it is not NULL, SQLite will invoke the destructor 
90433 ** function given by the 4th parameter to sqlite3_set_auxdata() on
90434 ** the meta-data when the corresponding function parameter changes
90435 ** or when the SQL statement completes, whichever comes first. {END}
90436 **
90437 ** In practice, meta-data is preserved between function calls for
90438 ** expressions that are constant at compile time. This includes literal
90439 ** values and SQL variables.
90440 **
90441 ** These routines must be called from the same thread in which
90442 ** the SQL function is running.
90443 */
90444 void *sqlite3_get_auxdata(sqlite3_context*, int N);
90445 void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
90446
90447
90448 /*
90449 ** CAPI3REF: Constants Defining Special Destructor Behavior {F10280}
90450 **
90451 ** These are special value for the destructor that is passed in as the
90452 ** final argument to routines like [sqlite3_result_blob()].  If the destructor
90453 ** argument is SQLITE_STATIC, it means that the content pointer is constant
90454 ** and will never change.  It does not need to be destroyed.  The 
90455 ** SQLITE_TRANSIENT value means that the content will likely change in
90456 ** the near future and that SQLite should make its own private copy of
90457 ** the content before returning.
90458 **
90459 ** The typedef is necessary to work around problems in certain
90460 ** C++ compilers.  See ticket #2191.
90461 */
90462 typedef void (*sqlite3_destructor_type)(void*);
90463 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
90464 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
90465
90466 /*
90467 ** CAPI3REF: Setting The Result Of An SQL Function {F16400}
90468 **
90469 ** These routines are used by the xFunc or xFinal callbacks that
90470 ** implement SQL functions and aggregates.  See
90471 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
90472 ** for additional information.
90473 **
90474 ** These functions work very much like the 
90475 ** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used
90476 ** to bind values to host parameters in prepared statements.
90477 ** Refer to the
90478 ** [sqlite3_bind_blob | sqlite3_bind_* documentation] for
90479 ** additional information.
90480 **
90481 ** {F16402} The sqlite3_result_blob() interface sets the result from
90482 ** an application defined function to be the BLOB whose content is pointed
90483 ** to by the second parameter and which is N bytes long where N is the
90484 ** third parameter. 
90485 ** {F16403} The sqlite3_result_zeroblob() inerfaces set the result of
90486 ** the application defined function to be a BLOB containing all zero
90487 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
90488 **
90489 ** {F16407} The sqlite3_result_double() interface sets the result from
90490 ** an application defined function to be a floating point value specified
90491 ** by its 2nd argument.
90492 **
90493 ** {F16409} The sqlite3_result_error() and sqlite3_result_error16() functions
90494 ** cause the implemented SQL function to throw an exception.
90495 ** {F16411} SQLite uses the string pointed to by the
90496 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
90497 ** as the text of an error message. {F16412} SQLite interprets the error
90498 ** message string from sqlite3_result_error() as UTF8.  {F16413} SQLite
90499 ** interprets the string from sqlite3_result_error16() as UTF16 in native
90500 ** byte order.  {F16414} If the third parameter to sqlite3_result_error()
90501 ** or sqlite3_result_error16() is negative then SQLite takes as the error
90502 ** message all text up through the first zero character.
90503 ** {F16415} If the third parameter to sqlite3_result_error() or
90504 ** sqlite3_result_error16() is non-negative then SQLite takes that many
90505 ** bytes (not characters) from the 2nd parameter as the error message.
90506 ** {F16417} The sqlite3_result_error() and sqlite3_result_error16()
90507 ** routines make a copy private copy of the error message text before
90508 ** they return.  {END} Hence, the calling function can deallocate or
90509 ** modify the text after they return without harm.
90510 **
90511 ** {F16421} The sqlite3_result_toobig() interface causes SQLite
90512 ** to throw an error indicating that a string or BLOB is to long
90513 ** to represent.  {F16422} The sqlite3_result_nomem() interface
90514 ** causes SQLite to throw an exception indicating that the a
90515 ** memory allocation failed.
90516 **
90517 ** {F16431} The sqlite3_result_int() interface sets the return value
90518 ** of the application-defined function to be the 32-bit signed integer
90519 ** value given in the 2nd argument.
90520 ** {F16432} The sqlite3_result_int64() interface sets the return value
90521 ** of the application-defined function to be the 64-bit signed integer
90522 ** value given in the 2nd argument.
90523 **
90524 ** {F16437} The sqlite3_result_null() interface sets the return value
90525 ** of the application-defined function to be NULL.
90526 **
90527 ** {F16441} The sqlite3_result_text(), sqlite3_result_text16(), 
90528 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
90529 ** set the return value of the application-defined function to be
90530 ** a text string which is represented as UTF-8, UTF-16 native byte order,
90531 ** UTF-16 little endian, or UTF-16 big endian, respectively.
90532 ** {F16442} SQLite takes the text result from the application from
90533 ** the 2nd parameter of the sqlite3_result_text* interfaces.
90534 ** {F16444} If the 3rd parameter to the sqlite3_result_text* interfaces
90535 ** is negative, then SQLite takes result text from the 2nd parameter 
90536 ** through the first zero character.
90537 ** {F16447} If the 3rd parameter to the sqlite3_result_text* interfaces
90538 ** is non-negative, then as many bytes (not characters) of the text
90539 ** pointed to by the 2nd parameter are taken as the application-defined
90540 ** function result.
90541 ** {F16451} If the 4th parameter to the sqlite3_result_text* interfaces
90542 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
90543 ** function as the destructor on the text or blob result when it has
90544 ** finished using that result.
90545 ** {F16453} If the 4th parameter to the sqlite3_result_text* interfaces
90546 ** or sqlite3_result_blob is the special constant SQLITE_STATIC, then
90547 ** SQLite assumes that the text or blob result is constant space and
90548 ** does not copy the space or call a destructor when it has
90549 ** finished using that result.
90550 ** {F16454} If the 4th parameter to the sqlite3_result_text* interfaces
90551 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
90552 ** then SQLite makes a copy of the result into space obtained from
90553 ** from [sqlite3_malloc()] before it returns.
90554 **
90555 ** {F16461} The sqlite3_result_value() interface sets the result of
90556 ** the application-defined function to be a copy the [sqlite3_value]
90557 ** object specified by the 2nd parameter.  {F16463} The
90558 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
90559 ** so that [sqlite3_value] specified in the parameter may change or
90560 ** be deallocated after sqlite3_result_value() returns without harm.
90561 **
90562 ** {U16491} These routines are called from within the different thread 
90563 ** than the one containing the application-defined function that recieved
90564 ** the [sqlite3_context] pointer, the results are undefined.
90565 */
90566 void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
90567 void sqlite3_result_double(sqlite3_context*, double);
90568 void sqlite3_result_error(sqlite3_context*, const char*, int);
90569 void sqlite3_result_error16(sqlite3_context*, const void*, int);
90570 void sqlite3_result_error_toobig(sqlite3_context*);
90571 void sqlite3_result_error_nomem(sqlite3_context*);
90572 void sqlite3_result_int(sqlite3_context*, int);
90573 void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
90574 void sqlite3_result_null(sqlite3_context*);
90575 void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
90576 void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
90577 void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
90578 void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
90579 void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
90580 void sqlite3_result_zeroblob(sqlite3_context*, int n);
90581
90582 /*
90583 ** CAPI3REF: Define New Collating Sequences {F16600}
90584 **
90585 ** {F16601}
90586 ** These functions are used to add new collation sequences to the
90587 ** [sqlite3*] handle specified as the first argument. 
90588 **
90589 ** {F16602}
90590 ** The name of the new collation sequence is specified as a UTF-8 string
90591 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
90592 ** and a UTF-16 string for sqlite3_create_collation16(). {F16603} In all cases
90593 ** the name is passed as the second function argument.
90594 **
90595 ** {F16604}
90596 ** The third argument may be one of the constants [SQLITE_UTF8],
90597 ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
90598 ** routine expects to be passed pointers to strings encoded using UTF-8,
90599 ** UTF-16 little-endian or UTF-16 big-endian respectively. {F16605} The
90600 ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that
90601 ** the routine expects pointers to 16-bit word aligned strings
90602 ** of UTF16 in the native byte order of the host computer.
90603 **
90604 ** {F16607}
90605 ** A pointer to the user supplied routine must be passed as the fifth
90606 ** argument. {F16609} If it is NULL, this is the same as deleting the collation
90607 ** sequence (so that SQLite cannot call it anymore).
90608 ** {F16611} Each time the application
90609 ** supplied function is invoked, it is passed a copy of the void* passed as
90610 ** the fourth argument to sqlite3_create_collation() or
90611 ** sqlite3_create_collation16() as its first parameter.
90612 **
90613 ** {F16612}
90614 ** The remaining arguments to the application-supplied routine are two strings,
90615 ** each represented by a [length, data] pair and encoded in the encoding
90616 ** that was passed as the third argument when the collation sequence was
90617 ** registered. {END} The application defined collation routine should
90618 ** return negative, zero or positive if
90619 ** the first string is less than, equal to, or greater than the second
90620 ** string. i.e. (STRING1 - STRING2).
90621 **
90622 ** {F16615}
90623 ** The sqlite3_create_collation_v2() works like sqlite3_create_collation()
90624 ** excapt that it takes an extra argument which is a destructor for
90625 ** the collation.  {F16617} The destructor is called when the collation is
90626 ** destroyed and is passed a copy of the fourth parameter void* pointer
90627 ** of the sqlite3_create_collation_v2().
90628 ** {F16618}  Collations are destroyed when
90629 ** they are overridden by later calls to the collation creation functions
90630 ** or when the [sqlite3*] database handle is closed using [sqlite3_close()].
90631 */
90632 int sqlite3_create_collation(
90633   sqlite3*, 
90634   const char *zName, 
90635   int eTextRep, 
90636   void*,
90637   int(*xCompare)(void*,int,const void*,int,const void*)
90638 );
90639 int sqlite3_create_collation_v2(
90640   sqlite3*, 
90641   const char *zName, 
90642   int eTextRep, 
90643   void*,
90644   int(*xCompare)(void*,int,const void*,int,const void*),
90645   void(*xDestroy)(void*)
90646 );
90647 int sqlite3_create_collation16(
90648   sqlite3*, 
90649   const char *zName, 
90650   int eTextRep, 
90651   void*,
90652   int(*xCompare)(void*,int,const void*,int,const void*)
90653 );
90654
90655 /*
90656 ** CAPI3REF: Collation Needed Callbacks {F16700}
90657 **
90658 ** {F16701}
90659 ** To avoid having to register all collation sequences before a database
90660 ** can be used, a single callback function may be registered with the
90661 ** database handle to be called whenever an undefined collation sequence is
90662 ** required.
90663 **
90664 ** {F16702}
90665 ** If the function is registered using the sqlite3_collation_needed() API,
90666 ** then it is passed the names of undefined collation sequences as strings
90667 ** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, the names
90668 ** are passed as UTF-16 in machine native byte order. {F16704} A call to either
90669 ** function replaces any existing callback.
90670 **
90671 ** {F16705} When the callback is invoked, the first argument passed is a copy
90672 ** of the second argument to sqlite3_collation_needed() or
90673 ** sqlite3_collation_needed16(). {F16706} The second argument is the database
90674 ** handle.  {F16707} The third argument is one of [SQLITE_UTF8],
90675 ** [SQLITE_UTF16BE], or [SQLITE_UTF16LE], indicating the most
90676 ** desirable form of the collation sequence function required.
90677 ** {F16708} The fourth parameter is the name of the
90678 ** required collation sequence. {END}
90679 **
90680 ** The callback function should register the desired collation using
90681 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
90682 ** [sqlite3_create_collation_v2()].
90683 */
90684 int sqlite3_collation_needed(
90685   sqlite3*, 
90686   void*, 
90687   void(*)(void*,sqlite3*,int eTextRep,const char*)
90688 );
90689 int sqlite3_collation_needed16(
90690   sqlite3*, 
90691   void*,
90692   void(*)(void*,sqlite3*,int eTextRep,const void*)
90693 );
90694
90695 /*
90696 ** Specify the key for an encrypted database.  This routine should be
90697 ** called right after sqlite3_open().
90698 **
90699 ** The code to implement this API is not available in the public release
90700 ** of SQLite.
90701 */
90702 int sqlite3_key(
90703   sqlite3 *db,                   /* Database to be rekeyed */
90704   const void *pKey, int nKey     /* The key */
90705 );
90706
90707 /*
90708 ** Change the key on an open database.  If the current database is not
90709 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
90710 ** database is decrypted.
90711 **
90712 ** The code to implement this API is not available in the public release
90713 ** of SQLite.
90714 */
90715 int sqlite3_rekey(
90716   sqlite3 *db,                   /* Database to be rekeyed */
90717   const void *pKey, int nKey     /* The new key */
90718 );
90719
90720 /*
90721 ** CAPI3REF:  Suspend Execution For A Short Time {F10530}
90722 **
90723 ** {F10531} The sqlite3_sleep() function
90724 ** causes the current thread to suspend execution
90725 ** for at least a number of milliseconds specified in its parameter.
90726 **
90727 ** {F10532} If the operating system does not support sleep requests with 
90728 ** millisecond time resolution, then the time will be rounded up to 
90729 ** the nearest second. {F10533} The number of milliseconds of sleep actually 
90730 ** requested from the operating system is returned.
90731 **
90732 ** {F10534} SQLite implements this interface by calling the xSleep()
90733 ** method of the default [sqlite3_vfs] object. {END}
90734 */
90735 int sqlite3_sleep(int);
90736
90737 /*
90738 ** CAPI3REF:  Name Of The Folder Holding Temporary Files {F10310}
90739 **
90740 ** If this global variable is made to point to a string which is
90741 ** the name of a folder (a.ka. directory), then all temporary files
90742 ** created by SQLite will be placed in that directory.  If this variable
90743 ** is NULL pointer, then SQLite does a search for an appropriate temporary
90744 ** file directory.
90745 **
90746 ** It is not safe to modify this variable once a database connection
90747 ** has been opened.  It is intended that this variable be set once
90748 ** as part of process initialization and before any SQLite interface
90749 ** routines have been call and remain unchanged thereafter.
90750 */
90751 SQLITE_EXTERN char *sqlite3_temp_directory;
90752
90753 /*
90754 ** CAPI3REF:  Test To See If The Database Is In Auto-Commit Mode {F12930}
90755 **
90756 ** {F12931} The sqlite3_get_autocommit() interfaces returns non-zero or
90757 ** zero if the given database connection is or is not in autocommit mode,
90758 ** respectively. {F12932}  Autocommit mode is on
90759 ** by default.  {F12933} Autocommit mode is disabled by a BEGIN statement.
90760 ** {F12934} Autocommit mode is reenabled by a COMMIT or ROLLBACK. {END}
90761 **
90762 ** If certain kinds of errors occur on a statement within a multi-statement
90763 ** transactions (errors including [SQLITE_FULL], [SQLITE_IOERR], 
90764 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
90765 ** transaction might be rolled back automatically.  {F12935} The only way to
90766 ** find out if SQLite automatically rolled back the transaction after
90767 ** an error is to use this function. {END}
90768 **
90769 ** {U12936} If another thread changes the autocommit status of the database
90770 ** connection while this routine is running, then the return value
90771 ** is undefined. {END}
90772 */
90773 int sqlite3_get_autocommit(sqlite3*);
90774
90775 /*
90776 ** CAPI3REF:  Find The Database Handle Of A Prepared Statement {F13120}
90777 **
90778 ** {F13121} The sqlite3_db_handle interface
90779 ** returns the [sqlite3*] database handle to which a
90780 ** [sqlite3_stmt | prepared statement] belongs.
90781 ** {F13122} the database handle returned by sqlite3_db_handle
90782 ** is the same database handle that was
90783 ** the first argument to the [sqlite3_prepare_v2()] or its variants
90784 ** that was used to create the statement in the first place.
90785 */
90786 sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
90787
90788
90789 /*
90790 ** CAPI3REF: Commit And Rollback Notification Callbacks {F12950}
90791 **
90792 ** {F12951} The sqlite3_commit_hook() interface registers a callback
90793 ** function to be invoked whenever a transaction is committed.
90794 ** {F12952} Any callback set by a previous call to sqlite3_commit_hook()
90795 ** for the same database connection is overridden.
90796 ** {F12953} The sqlite3_rollback_hook() interface registers a callback
90797 ** function to be invoked whenever a transaction is committed.
90798 ** {F12954} Any callback set by a previous call to sqlite3_commit_hook()
90799 ** for the same database connection is overridden.
90800 ** {F12956} The pArg argument is passed through
90801 ** to the callback.  {F12957} If the callback on a commit hook function 
90802 ** returns non-zero, then the commit is converted into a rollback.
90803 **
90804 ** {F12958} If another function was previously registered, its
90805 ** pArg value is returned.  Otherwise NULL is returned.
90806 **
90807 ** {F12959} Registering a NULL function disables the callback.
90808 **
90809 ** {F12961} For the purposes of this API, a transaction is said to have been 
90810 ** rolled back if an explicit "ROLLBACK" statement is executed, or
90811 ** an error or constraint causes an implicit rollback to occur.
90812 ** {F12962} The rollback callback is not invoked if a transaction is
90813 ** automatically rolled back because the database connection is closed.
90814 ** {F12964} The rollback callback is not invoked if a transaction is
90815 ** rolled back because a commit callback returned non-zero.
90816 ** <todo> Check on this </todo> {END}
90817 **
90818 ** These are experimental interfaces and are subject to change.
90819 */
90820 void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
90821 void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
90822
90823 /*
90824 ** CAPI3REF: Data Change Notification Callbacks {F12970}
90825 **
90826 ** {F12971} The sqlite3_update_hook() interface
90827 ** registers a callback function with the database connection identified by the 
90828 ** first argument to be invoked whenever a row is updated, inserted or deleted.
90829 ** {F12972} Any callback set by a previous call to this function for the same 
90830 ** database connection is overridden.
90831 **
90832 ** {F12974} The second argument is a pointer to the function to invoke when a 
90833 ** row is updated, inserted or deleted. 
90834 ** {F12976} The first argument to the callback is
90835 ** a copy of the third argument to sqlite3_update_hook().
90836 ** {F12977} The second callback 
90837 ** argument is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
90838 ** depending on the operation that caused the callback to be invoked.
90839 ** {F12978} The third and 
90840 ** fourth arguments to the callback contain pointers to the database and 
90841 ** table name containing the affected row.
90842 ** {F12979} The final callback parameter is 
90843 ** the rowid of the row.
90844 ** {F12981} In the case of an update, this is the rowid after 
90845 ** the update takes place.
90846 **
90847 ** {F12983} The update hook is not invoked when internal system tables are
90848 ** modified (i.e. sqlite_master and sqlite_sequence).
90849 **
90850 ** {F12984} If another function was previously registered, its pArg value
90851 ** is returned.  {F12985} Otherwise NULL is returned.
90852 */
90853 void *sqlite3_update_hook(
90854   sqlite3*, 
90855   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
90856   void*
90857 );
90858
90859 /*
90860 ** CAPI3REF:  Enable Or Disable Shared Pager Cache {F10330}
90861 **
90862 ** {F10331}
90863 ** This routine enables or disables the sharing of the database cache
90864 ** and schema data structures between connections to the same database.
90865 ** {F10332}
90866 ** Sharing is enabled if the argument is true and disabled if the argument
90867 ** is false.
90868 **
90869 ** {F10333} Cache sharing is enabled and disabled
90870 ** for an entire process. {END} This is a change as of SQLite version 3.5.0.
90871 ** In prior versions of SQLite, sharing was
90872 ** enabled or disabled for each thread separately.
90873 **
90874 ** {F10334}
90875 ** The cache sharing mode set by this interface effects all subsequent
90876 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
90877 ** {F10335} Existing database connections continue use the sharing mode
90878 ** that was in effect at the time they were opened. {END}
90879 **
90880 ** Virtual tables cannot be used with a shared cache.  {F10336} When shared
90881 ** cache is enabled, the [sqlite3_create_module()] API used to register
90882 ** virtual tables will always return an error. {END}
90883 **
90884 ** {F10337} This routine returns [SQLITE_OK] if shared cache was
90885 ** enabled or disabled successfully.  {F10338} An [SQLITE_ERROR | error code]
90886 ** is returned otherwise. {END}
90887 **
90888 ** {F10339} Shared cache is disabled by default. {END} But this might change in
90889 ** future releases of SQLite.  Applications that care about shared
90890 ** cache setting should set it explicitly.
90891 */
90892 int sqlite3_enable_shared_cache(int);
90893
90894 /*
90895 ** CAPI3REF:  Attempt To Free Heap Memory {F17340}
90896 **
90897 ** {F17341} The sqlite3_release_memory() interface attempts to
90898 ** free N bytes of heap memory by deallocating non-essential memory
90899 ** allocations held by the database labrary. {END}  Memory used
90900 ** to cache database pages to improve performance is an example of
90901 ** non-essential memory.  {F16342} sqlite3_release_memory() returns
90902 ** the number of bytes actually freed, which might be more or less
90903 ** than the amount requested.
90904 */
90905 int sqlite3_release_memory(int);
90906
90907 /*
90908 ** CAPI3REF:  Impose A Limit On Heap Size {F17350}
90909 **
90910 ** {F16351} The sqlite3_soft_heap_limit() interface
90911 ** places a "soft" limit on the amount of heap memory that may be allocated
90912 ** by SQLite. {F16352} If an internal allocation is requested 
90913 ** that would exceed the soft heap limit, [sqlite3_release_memory()] is
90914 ** invoked one or more times to free up some space before the allocation
90915 ** is made. {END}
90916 **
90917 ** {F16353} The limit is called "soft", because if
90918 ** [sqlite3_release_memory()] cannot
90919 ** free sufficient memory to prevent the limit from being exceeded,
90920 ** the memory is allocated anyway and the current operation proceeds.
90921 **
90922 ** {F16354}
90923 ** A negative or zero value for N means that there is no soft heap limit and
90924 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
90925 ** {F16355} The default value for the soft heap limit is zero.
90926 **
90927 ** SQLite makes a best effort to honor the soft heap limit.  
90928 ** {F16356} But if the soft heap limit cannot honored, execution will
90929 ** continue without error or notification. {END}  This is why the limit is 
90930 ** called a "soft" limit.  It is advisory only.
90931 **
90932 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
90933 ** allocated by a single thread - the same thread in which this routine
90934 ** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
90935 ** applied to all threads. {F16357} The value specified for the soft heap limit
90936 ** is an upper bound on the total memory allocation for all threads. {END}  In
90937 ** version 3.5.0 there is no mechanism for limiting the heap usage for
90938 ** individual threads.
90939 */
90940 void sqlite3_soft_heap_limit(int);
90941
90942 /*
90943 ** CAPI3REF:  Extract Metadata About A Column Of A Table {F12850}
90944 **
90945 ** This routine
90946 ** returns meta-data about a specific column of a specific database
90947 ** table accessible using the connection handle passed as the first function 
90948 ** argument.
90949 **
90950 ** The column is identified by the second, third and fourth parameters to 
90951 ** this function. The second parameter is either the name of the database
90952 ** (i.e. "main", "temp" or an attached database) containing the specified
90953 ** table or NULL. If it is NULL, then all attached databases are searched
90954 ** for the table using the same algorithm as the database engine uses to 
90955 ** resolve unqualified table references.
90956 **
90957 ** The third and fourth parameters to this function are the table and column 
90958 ** name of the desired column, respectively. Neither of these parameters 
90959 ** may be NULL.
90960 **
90961 ** Meta information is returned by writing to the memory locations passed as
90962 ** the 5th and subsequent parameters to this function. Any of these 
90963 ** arguments may be NULL, in which case the corresponding element of meta 
90964 ** information is ommitted.
90965 **
90966 ** <pre>
90967 ** Parameter     Output Type      Description
90968 ** -----------------------------------
90969 **
90970 **   5th         const char*      Data type
90971 **   6th         const char*      Name of the default collation sequence 
90972 **   7th         int              True if the column has a NOT NULL constraint
90973 **   8th         int              True if the column is part of the PRIMARY KEY
90974 **   9th         int              True if the column is AUTOINCREMENT
90975 ** </pre>
90976 **
90977 **
90978 ** The memory pointed to by the character pointers returned for the 
90979 ** declaration type and collation sequence is valid only until the next 
90980 ** call to any sqlite API function.
90981 **
90982 ** If the specified table is actually a view, then an error is returned.
90983 **
90984 ** If the specified column is "rowid", "oid" or "_rowid_" and an 
90985 ** INTEGER PRIMARY KEY column has been explicitly declared, then the output 
90986 ** parameters are set for the explicitly declared column. If there is no
90987 ** explicitly declared IPK column, then the output parameters are set as 
90988 ** follows:
90989 **
90990 ** <pre>
90991 **     data type: "INTEGER"
90992 **     collation sequence: "BINARY"
90993 **     not null: 0
90994 **     primary key: 1
90995 **     auto increment: 0
90996 ** </pre>
90997 **
90998 ** This function may load one or more schemas from database files. If an
90999 ** error occurs during this process, or if the requested table or column
91000 ** cannot be found, an SQLITE error code is returned and an error message
91001 ** left in the database handle (to be retrieved using sqlite3_errmsg()).
91002 **
91003 ** This API is only available if the library was compiled with the
91004 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
91005 */
91006 int sqlite3_table_column_metadata(
91007   sqlite3 *db,                /* Connection handle */
91008   const char *zDbName,        /* Database name or NULL */
91009   const char *zTableName,     /* Table name */
91010   const char *zColumnName,    /* Column name */
91011   char const **pzDataType,    /* OUTPUT: Declared data type */
91012   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
91013   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
91014   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
91015   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
91016 );
91017
91018 /*
91019 ** CAPI3REF: Load An Extension {F12600}
91020 **
91021 ** {F12601} The sqlite3_load_extension() interface
91022 ** attempts to load an SQLite extension library contained in the file
91023 ** zFile. {F12602} The entry point is zProc. {F12603} zProc may be 0
91024 ** in which case the name of the entry point defaults
91025 ** to "sqlite3_extension_init".
91026 **
91027 ** {F12604} The sqlite3_load_extension() interface shall
91028 ** return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
91029 **
91030 ** {F12605}
91031 ** If an error occurs and pzErrMsg is not 0, then the
91032 ** sqlite3_load_extension() interface shall attempt to fill *pzErrMsg with 
91033 ** error message text stored in memory obtained from [sqlite3_malloc()].
91034 ** {END}  The calling function should free this memory
91035 ** by calling [sqlite3_free()].
91036 **
91037 ** {F12606}
91038 ** Extension loading must be enabled using [sqlite3_enable_load_extension()]
91039 ** prior to calling this API or an error will be returned.
91040 */
91041 int sqlite3_load_extension(
91042   sqlite3 *db,          /* Load the extension into this database connection */
91043   const char *zFile,    /* Name of the shared library containing extension */
91044   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
91045   char **pzErrMsg       /* Put error message here if not 0 */
91046 );
91047
91048 /*
91049 ** CAPI3REF:  Enable Or Disable Extension Loading {F12620}
91050 **
91051 ** So as not to open security holes in older applications that are
91052 ** unprepared to deal with extension loading, and as a means of disabling
91053 ** extension loading while evaluating user-entered SQL, the following
91054 ** API is provided to turn the [sqlite3_load_extension()] mechanism on and
91055 ** off.  {F12622} It is off by default. {END} See ticket #1863.
91056 **
91057 ** {F12621} Call the sqlite3_enable_load_extension() routine
91058 ** with onoff==1 to turn extension loading on
91059 ** and call it with onoff==0 to turn it back off again. {END}
91060 */
91061 int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
91062
91063 /*
91064 ** CAPI3REF: Make Arrangements To Automatically Load An Extension {F12640}
91065 **
91066 ** {F12641} This function
91067 ** registers an extension entry point that is automatically invoked
91068 ** whenever a new database connection is opened using
91069 ** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. {END}
91070 **
91071 ** This API can be invoked at program startup in order to register
91072 ** one or more statically linked extensions that will be available
91073 ** to all new database connections.
91074 **
91075 ** {F12642} Duplicate extensions are detected so calling this routine multiple
91076 ** times with the same extension is harmless.
91077 **
91078 ** {F12643} This routine stores a pointer to the extension in an array
91079 ** that is obtained from sqlite_malloc(). {END} If you run a memory leak
91080 ** checker on your program and it reports a leak because of this
91081 ** array, then invoke [sqlite3_reset_auto_extension()] prior
91082 ** to shutdown to free the memory.
91083 **
91084 ** {F12644} Automatic extensions apply across all threads. {END}
91085 **
91086 ** This interface is experimental and is subject to change or
91087 ** removal in future releases of SQLite.
91088 */
91089 int sqlite3_auto_extension(void *xEntryPoint);
91090
91091
91092 /*
91093 ** CAPI3REF: Reset Automatic Extension Loading {F12660}
91094 **
91095 ** {F12661} This function disables all previously registered
91096 ** automatic extensions. {END}  This
91097 ** routine undoes the effect of all prior [sqlite3_automatic_extension()]
91098 ** calls.
91099 **
91100 ** {F12662} This call disabled automatic extensions in all threads. {END}
91101 **
91102 ** This interface is experimental and is subject to change or
91103 ** removal in future releases of SQLite.
91104 */
91105 void sqlite3_reset_auto_extension(void);
91106
91107
91108 /*
91109 ****** EXPERIMENTAL - subject to change without notice **************
91110 **
91111 ** The interface to the virtual-table mechanism is currently considered
91112 ** to be experimental.  The interface might change in incompatible ways.
91113 ** If this is a problem for you, do not use the interface at this time.
91114 **
91115 ** When the virtual-table mechanism stablizes, we will declare the
91116 ** interface fixed, support it indefinitely, and remove this comment.
91117 */
91118
91119 /*
91120 ** Structures used by the virtual table interface
91121 */
91122 typedef struct sqlite3_vtab sqlite3_vtab;
91123 typedef struct sqlite3_index_info sqlite3_index_info;
91124 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
91125 typedef struct sqlite3_module sqlite3_module;
91126
91127 /*
91128 ** A module is a class of virtual tables.  Each module is defined
91129 ** by an instance of the following structure.  This structure consists
91130 ** mostly of methods for the module.
91131 */
91132 struct sqlite3_module {
91133   int iVersion;
91134   int (*xCreate)(sqlite3*, void *pAux,
91135                int argc, const char *const*argv,
91136                sqlite3_vtab **ppVTab, char**);
91137   int (*xConnect)(sqlite3*, void *pAux,
91138                int argc, const char *const*argv,
91139                sqlite3_vtab **ppVTab, char**);
91140   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
91141   int (*xDisconnect)(sqlite3_vtab *pVTab);
91142   int (*xDestroy)(sqlite3_vtab *pVTab);
91143   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
91144   int (*xClose)(sqlite3_vtab_cursor*);
91145   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
91146                 int argc, sqlite3_value **argv);
91147   int (*xNext)(sqlite3_vtab_cursor*);
91148   int (*xEof)(sqlite3_vtab_cursor*);
91149   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
91150   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
91151   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
91152   int (*xBegin)(sqlite3_vtab *pVTab);
91153   int (*xSync)(sqlite3_vtab *pVTab);
91154   int (*xCommit)(sqlite3_vtab *pVTab);
91155   int (*xRollback)(sqlite3_vtab *pVTab);
91156   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
91157                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
91158                        void **ppArg);
91159
91160   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
91161 };
91162
91163 /*
91164 ** The sqlite3_index_info structure and its substructures is used to
91165 ** pass information into and receive the reply from the xBestIndex
91166 ** method of an sqlite3_module.  The fields under **Inputs** are the
91167 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
91168 ** results into the **Outputs** fields.
91169 **
91170 ** The aConstraint[] array records WHERE clause constraints of the
91171 ** form:
91172 **
91173 **         column OP expr
91174 **
91175 ** Where OP is =, &lt;, &lt;=, &gt;, or &gt;=.  
91176 ** The particular operator is stored
91177 ** in aConstraint[].op.  The index of the column is stored in 
91178 ** aConstraint[].iColumn.  aConstraint[].usable is TRUE if the
91179 ** expr on the right-hand side can be evaluated (and thus the constraint
91180 ** is usable) and false if it cannot.
91181 **
91182 ** The optimizer automatically inverts terms of the form "expr OP column"
91183 ** and makes other simplifications to the WHERE clause in an attempt to
91184 ** get as many WHERE clause terms into the form shown above as possible.
91185 ** The aConstraint[] array only reports WHERE clause terms in the correct
91186 ** form that refer to the particular virtual table being queried.
91187 **
91188 ** Information about the ORDER BY clause is stored in aOrderBy[].
91189 ** Each term of aOrderBy records a column of the ORDER BY clause.
91190 **
91191 ** The xBestIndex method must fill aConstraintUsage[] with information
91192 ** about what parameters to pass to xFilter.  If argvIndex>0 then
91193 ** the right-hand side of the corresponding aConstraint[] is evaluated
91194 ** and becomes the argvIndex-th entry in argv.  If aConstraintUsage[].omit
91195 ** is true, then the constraint is assumed to be fully handled by the
91196 ** virtual table and is not checked again by SQLite.
91197 **
91198 ** The idxNum and idxPtr values are recorded and passed into xFilter.
91199 ** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
91200 **
91201 ** The orderByConsumed means that output from xFilter will occur in
91202 ** the correct order to satisfy the ORDER BY clause so that no separate
91203 ** sorting step is required.
91204 **
91205 ** The estimatedCost value is an estimate of the cost of doing the
91206 ** particular lookup.  A full scan of a table with N entries should have
91207 ** a cost of N.  A binary search of a table of N entries should have a
91208 ** cost of approximately log(N).
91209 */
91210 struct sqlite3_index_info {
91211   /* Inputs */
91212   int nConstraint;           /* Number of entries in aConstraint */
91213   struct sqlite3_index_constraint {
91214      int iColumn;              /* Column on left-hand side of constraint */
91215      unsigned char op;         /* Constraint operator */
91216      unsigned char usable;     /* True if this constraint is usable */
91217      int iTermOffset;          /* Used internally - xBestIndex should ignore */
91218   } *aConstraint;            /* Table of WHERE clause constraints */
91219   int nOrderBy;              /* Number of terms in the ORDER BY clause */
91220   struct sqlite3_index_orderby {
91221      int iColumn;              /* Column number */
91222      unsigned char desc;       /* True for DESC.  False for ASC. */
91223   } *aOrderBy;               /* The ORDER BY clause */
91224
91225   /* Outputs */
91226   struct sqlite3_index_constraint_usage {
91227     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
91228     unsigned char omit;      /* Do not code a test for this constraint */
91229   } *aConstraintUsage;
91230   int idxNum;                /* Number used to identify the index */
91231   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
91232   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
91233   int orderByConsumed;       /* True if output is already ordered */
91234   double estimatedCost;      /* Estimated cost of using this index */
91235 };
91236 #define SQLITE_INDEX_CONSTRAINT_EQ    2
91237 #define SQLITE_INDEX_CONSTRAINT_GT    4
91238 #define SQLITE_INDEX_CONSTRAINT_LE    8
91239 #define SQLITE_INDEX_CONSTRAINT_LT    16
91240 #define SQLITE_INDEX_CONSTRAINT_GE    32
91241 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
91242
91243 /*
91244 ** This routine is used to register a new module name with an SQLite
91245 ** connection.  Module names must be registered before creating new
91246 ** virtual tables on the module, or before using preexisting virtual
91247 ** tables of the module.
91248 */
91249 int sqlite3_create_module(
91250   sqlite3 *db,               /* SQLite connection to register module with */
91251   const char *zName,         /* Name of the module */
91252   const sqlite3_module *,    /* Methods for the module */
91253   void *                     /* Client data for xCreate/xConnect */
91254 );
91255
91256 /*
91257 ** This routine is identical to the sqlite3_create_module() method above,
91258 ** except that it allows a destructor function to be specified. It is
91259 ** even more experimental than the rest of the virtual tables API.
91260 */
91261 int sqlite3_create_module_v2(
91262   sqlite3 *db,               /* SQLite connection to register module with */
91263   const char *zName,         /* Name of the module */
91264   const sqlite3_module *,    /* Methods for the module */
91265   void *,                    /* Client data for xCreate/xConnect */
91266   void(*xDestroy)(void*)     /* Module destructor function */
91267 );
91268
91269 /*
91270 ** Every module implementation uses a subclass of the following structure
91271 ** to describe a particular instance of the module.  Each subclass will
91272 ** be tailored to the specific needs of the module implementation.   The
91273 ** purpose of this superclass is to define certain fields that are common
91274 ** to all module implementations.
91275 **
91276 ** Virtual tables methods can set an error message by assigning a
91277 ** string obtained from sqlite3_mprintf() to zErrMsg.  The method should
91278 ** take care that any prior string is freed by a call to sqlite3_free()
91279 ** prior to assigning a new string to zErrMsg.  After the error message
91280 ** is delivered up to the client application, the string will be automatically
91281 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.  Note
91282 ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
91283 ** since virtual tables are commonly implemented in loadable extensions which
91284 ** do not have access to sqlite3MPrintf() or sqlite3Free().
91285 */
91286 struct sqlite3_vtab {
91287   const sqlite3_module *pModule;  /* The module for this virtual table */
91288   int nRef;                       /* Used internally */
91289   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
91290   /* Virtual table implementations will typically add additional fields */
91291 };
91292
91293 /* Every module implementation uses a subclass of the following structure
91294 ** to describe cursors that point into the virtual table and are used
91295 ** to loop through the virtual table.  Cursors are created using the
91296 ** xOpen method of the module.  Each module implementation will define
91297 ** the content of a cursor structure to suit its own needs.
91298 **
91299 ** This superclass exists in order to define fields of the cursor that
91300 ** are common to all implementations.
91301 */
91302 struct sqlite3_vtab_cursor {
91303   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
91304   /* Virtual table implementations will typically add additional fields */
91305 };
91306
91307 /*
91308 ** The xCreate and xConnect methods of a module use the following API
91309 ** to declare the format (the names and datatypes of the columns) of
91310 ** the virtual tables they implement.
91311 */
91312 int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
91313
91314 /*
91315 ** Virtual tables can provide alternative implementations of functions
91316 ** using the xFindFunction method.  But global versions of those functions
91317 ** must exist in order to be overloaded.
91318 **
91319 ** This API makes sure a global version of a function with a particular
91320 ** name and number of parameters exists.  If no such function exists
91321 ** before this API is called, a new function is created.  The implementation
91322 ** of the new function always causes an exception to be thrown.  So
91323 ** the new function is not good for anything by itself.  Its only
91324 ** purpose is to be a place-holder function that can be overloaded
91325 ** by virtual tables.
91326 **
91327 ** This API should be considered part of the virtual table interface,
91328 ** which is experimental and subject to change.
91329 */
91330 int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
91331
91332 /*
91333 ** The interface to the virtual-table mechanism defined above (back up
91334 ** to a comment remarkably similar to this one) is currently considered
91335 ** to be experimental.  The interface might change in incompatible ways.
91336 ** If this is a problem for you, do not use the interface at this time.
91337 **
91338 ** When the virtual-table mechanism stabilizes, we will declare the
91339 ** interface fixed, support it indefinitely, and remove this comment.
91340 **
91341 ****** EXPERIMENTAL - subject to change without notice **************
91342 */
91343
91344 /*
91345 ** CAPI3REF: A Handle To An Open BLOB {F17800}
91346 **
91347 ** An instance of the following opaque structure is used to 
91348 ** represent an blob-handle.  A blob-handle is created by
91349 ** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()].
91350 ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
91351 ** can be used to read or write small subsections of the blob.
91352 ** The [sqlite3_blob_bytes()] interface returns the size of the
91353 ** blob in bytes.
91354 */
91355 typedef struct sqlite3_blob sqlite3_blob;
91356
91357 /*
91358 ** CAPI3REF: Open A BLOB For Incremental I/O {F17810}
91359 **
91360 ** {F17811} This interfaces opens a handle to the blob located
91361 ** in row iRow,, column zColumn, table zTable in database zDb;
91362 ** in other words,  the same blob that would be selected by:
91363 **
91364 ** <pre>
91365 **     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
91366 ** </pre> {END}
91367 **
91368 ** {F17812} If the flags parameter is non-zero, the blob is opened for 
91369 ** read and write access. If it is zero, the blob is opened for read 
91370 ** access. {END}
91371 **
91372 ** {F17813} On success, [SQLITE_OK] is returned and the new 
91373 ** [sqlite3_blob | blob handle] is written to *ppBlob. 
91374 ** {F17814} Otherwise an error code is returned and 
91375 ** any value written to *ppBlob should not be used by the caller.
91376 ** {F17815} This function sets the database-handle error code and message
91377 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()].
91378 ** <todo>We should go through and mark all interfaces that behave this
91379 ** way with a similar statement</todo>
91380 */
91381 int sqlite3_blob_open(
91382   sqlite3*,
91383   const char *zDb,
91384   const char *zTable,
91385   const char *zColumn,
91386   sqlite3_int64 iRow,
91387   int flags,
91388   sqlite3_blob **ppBlob
91389 );
91390
91391 /*
91392 ** CAPI3REF:  Close A BLOB Handle {F17830}
91393 **
91394 ** Close an open [sqlite3_blob | blob handle].
91395 **
91396 ** {F17831} Closing a BLOB shall cause the current transaction to commit
91397 ** if there are no other BLOBs, no pending prepared statements, and the
91398 ** database connection is in autocommit mode.
91399 ** {F17832} If any writes were made to the BLOB, they might be held in cache
91400 ** until the close operation if they will fit. {END}
91401 ** Closing the BLOB often forces the changes
91402 ** out to disk and so if any I/O errors occur, they will likely occur
91403 ** at the time when the BLOB is closed.  {F17833} Any errors that occur during
91404 ** closing are reported as a non-zero return value.
91405 **
91406 ** {F17839} The BLOB is closed unconditionally.  Even if this routine returns
91407 ** an error code, the BLOB is still closed.
91408 */
91409 int sqlite3_blob_close(sqlite3_blob *);
91410
91411 /*
91412 ** CAPI3REF:  Return The Size Of An Open BLOB {F17805}
91413 **
91414 ** {F16806} Return the size in bytes of the blob accessible via the open 
91415 ** [sqlite3_blob | blob-handle] passed as an argument.
91416 */
91417 int sqlite3_blob_bytes(sqlite3_blob *);
91418
91419 /*
91420 ** CAPI3REF:  Read Data From A BLOB Incrementally {F17850}
91421 **
91422 ** This function is used to read data from an open 
91423 ** [sqlite3_blob | blob-handle] into a caller supplied buffer.
91424 ** {F17851} n bytes of data are copied into buffer
91425 ** z from the open blob, starting at offset iOffset.
91426 **
91427 ** {F17852} If offset iOffset is less than n bytes from the end of the blob, 
91428 ** [SQLITE_ERROR] is returned and no data is read.  {F17853} If n is
91429 ** less than zero [SQLITE_ERROR] is returned and no data is read.
91430 **
91431 ** {F17854} On success, SQLITE_OK is returned. Otherwise, an 
91432 ** [SQLITE_ERROR | SQLite error code] or an
91433 ** [SQLITE_IOERR_READ | extended error code] is returned.
91434 */
91435 int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset);
91436
91437 /*
91438 ** CAPI3REF:  Write Data Into A BLOB Incrementally {F17870}
91439 **
91440 ** This function is used to write data into an open 
91441 ** [sqlite3_blob | blob-handle] from a user supplied buffer.
91442 ** {F17871} n bytes of data are copied from the buffer
91443 ** pointed to by z into the open blob, starting at offset iOffset.
91444 **
91445 ** {F17872} If the [sqlite3_blob | blob-handle] passed as the first argument
91446 ** was not opened for writing (the flags parameter to [sqlite3_blob_open()]
91447 *** was zero), this function returns [SQLITE_READONLY].
91448 **
91449 ** {F17873} This function may only modify the contents of the blob; it is
91450 ** not possible to increase the size of a blob using this API.
91451 ** {F17874} If offset iOffset is less than n bytes from the end of the blob, 
91452 ** [SQLITE_ERROR] is returned and no data is written.  {F17875} If n is
91453 ** less than zero [SQLITE_ERROR] is returned and no data is written.
91454 **
91455 ** {F17876} On success, SQLITE_OK is returned. Otherwise, an 
91456 ** [SQLITE_ERROR | SQLite error code] or an
91457 ** [SQLITE_IOERR_READ | extended error code] is returned.
91458 */
91459 int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
91460
91461 /*
91462 ** CAPI3REF:  Virtual File System Objects {F11200}
91463 **
91464 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
91465 ** that SQLite uses to interact
91466 ** with the underlying operating system.  Most builds come with a
91467 ** single default VFS that is appropriate for the host computer.
91468 ** New VFSes can be registered and existing VFSes can be unregistered.
91469 ** The following interfaces are provided.
91470 **
91471 ** {F11201} The sqlite3_vfs_find() interface returns a pointer to 
91472 ** a VFS given its name.  {F11202} Names are case sensitive.
91473 ** {F11203} Names are zero-terminated UTF-8 strings.
91474 ** {F11204} If there is no match, a NULL
91475 ** pointer is returned. {F11205} If zVfsName is NULL then the default 
91476 ** VFS is returned. {END}
91477 **
91478 ** {F11210} New VFSes are registered with sqlite3_vfs_register().
91479 ** {F11211} Each new VFS becomes the default VFS if the makeDflt flag is set.
91480 ** {F11212} The same VFS can be registered multiple times without injury.
91481 ** {F11213} To make an existing VFS into the default VFS, register it again
91482 ** with the makeDflt flag set. {U11214} If two different VFSes with the
91483 ** same name are registered, the behavior is undefined.  {U11215} If a
91484 ** VFS is registered with a name that is NULL or an empty string,
91485 ** then the behavior is undefined.
91486 ** 
91487 ** {F11220} Unregister a VFS with the sqlite3_vfs_unregister() interface.
91488 ** {F11221} If the default VFS is unregistered, another VFS is chosen as
91489 ** the default.  The choice for the new VFS is arbitrary.
91490 */
91491 sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
91492 int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
91493 int sqlite3_vfs_unregister(sqlite3_vfs*);
91494
91495 /*
91496 ** CAPI3REF: Mutexes {F17000}
91497 **
91498 ** The SQLite core uses these routines for thread
91499 ** synchronization.  Though they are intended for internal
91500 ** use by SQLite, code that links against SQLite is
91501 ** permitted to use any of these routines.
91502 **
91503 ** The SQLite source code contains multiple implementations 
91504 ** of these mutex routines.  An appropriate implementation
91505 ** is selected automatically at compile-time.  The following
91506 ** implementations are available in the SQLite core:
91507 **
91508 ** <ul>
91509 ** <li>   SQLITE_MUTEX_OS2
91510 ** <li>   SQLITE_MUTEX_PTHREAD
91511 ** <li>   SQLITE_MUTEX_W32
91512 ** <li>   SQLITE_MUTEX_NOOP
91513 ** </ul>
91514 **
91515 ** The SQLITE_MUTEX_NOOP implementation is a set of routines 
91516 ** that does no real locking and is appropriate for use in 
91517 ** a single-threaded application.  The SQLITE_MUTEX_OS2,
91518 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
91519 ** are appropriate for use on os/2, unix, and windows.
91520 ** 
91521 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
91522 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
91523 ** implementation is included with the library.  The
91524 ** mutex interface routines defined here become external
91525 ** references in the SQLite library for which implementations
91526 ** must be provided by the application.  This facility allows an
91527 ** application that links against SQLite to provide its own mutex
91528 ** implementation without having to modify the SQLite core.
91529 **
91530 ** {F17011} The sqlite3_mutex_alloc() routine allocates a new
91531 ** mutex and returns a pointer to it. {F17012} If it returns NULL
91532 ** that means that a mutex could not be allocated. {F17013} SQLite
91533 ** will unwind its stack and return an error. {F17014} The argument
91534 ** to sqlite3_mutex_alloc() is one of these integer constants:
91535 **
91536 ** <ul>
91537 ** <li>  SQLITE_MUTEX_FAST
91538 ** <li>  SQLITE_MUTEX_RECURSIVE
91539 ** <li>  SQLITE_MUTEX_STATIC_MASTER
91540 ** <li>  SQLITE_MUTEX_STATIC_MEM
91541 ** <li>  SQLITE_MUTEX_STATIC_MEM2
91542 ** <li>  SQLITE_MUTEX_STATIC_PRNG
91543 ** <li>  SQLITE_MUTEX_STATIC_LRU
91544 ** </ul> {END}
91545 **
91546 ** {F17015} The first two constants cause sqlite3_mutex_alloc() to create
91547 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
91548 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END}
91549 ** The mutex implementation does not need to make a distinction
91550 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
91551 ** not want to.  {F17016} But SQLite will only request a recursive mutex in
91552 ** cases where it really needs one.  {END} If a faster non-recursive mutex
91553 ** implementation is available on the host platform, the mutex subsystem
91554 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
91555 **
91556 ** {F17017} The other allowed parameters to sqlite3_mutex_alloc() each return
91557 ** a pointer to a static preexisting mutex. {END}  Four static mutexes are
91558 ** used by the current version of SQLite.  Future versions of SQLite
91559 ** may add additional static mutexes.  Static mutexes are for internal
91560 ** use by SQLite only.  Applications that use SQLite mutexes should
91561 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
91562 ** SQLITE_MUTEX_RECURSIVE.
91563 **
91564 ** {F17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
91565 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
91566 ** returns a different mutex on every call.  {F17034} But for the static 
91567 ** mutex types, the same mutex is returned on every call that has
91568 ** the same type number. {END}
91569 **
91570 ** {F17019} The sqlite3_mutex_free() routine deallocates a previously
91571 ** allocated dynamic mutex. {F17020} SQLite is careful to deallocate every
91572 ** dynamic mutex that it allocates. {U17021} The dynamic mutexes must not be in 
91573 ** use when they are deallocated. {U17022} Attempting to deallocate a static
91574 ** mutex results in undefined behavior. {F17023} SQLite never deallocates
91575 ** a static mutex. {END}
91576 **
91577 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
91578 ** to enter a mutex. {F17024} If another thread is already within the mutex,
91579 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
91580 ** SQLITE_BUSY. {F17025}  The sqlite3_mutex_try() interface returns SQLITE_OK
91581 ** upon successful entry.  {F17026} Mutexes created using
91582 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
91583 ** {F17027} In such cases the,
91584 ** mutex must be exited an equal number of times before another thread
91585 ** can enter.  {U17028} If the same thread tries to enter any other
91586 ** kind of mutex more than once, the behavior is undefined.
91587 ** {F17029} SQLite will never exhibit
91588 ** such behavior in its own use of mutexes. {END}
91589 **
91590 ** Some systems (ex: windows95) do not the operation implemented by
91591 ** sqlite3_mutex_try().  On those systems, sqlite3_mutex_try() will
91592 ** always return SQLITE_BUSY.  {F17030} The SQLite core only ever uses
91593 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior. {END}
91594 **
91595 ** {F17031} The sqlite3_mutex_leave() routine exits a mutex that was
91596 ** previously entered by the same thread.  {U17032} The behavior
91597 ** is undefined if the mutex is not currently entered by the
91598 ** calling thread or is not currently allocated.  {F17033} SQLite will
91599 ** never do either. {END}
91600 **
91601 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
91602 */
91603 sqlite3_mutex *sqlite3_mutex_alloc(int);
91604 void sqlite3_mutex_free(sqlite3_mutex*);
91605 void sqlite3_mutex_enter(sqlite3_mutex*);
91606 int sqlite3_mutex_try(sqlite3_mutex*);
91607 void sqlite3_mutex_leave(sqlite3_mutex*);
91608
91609 /*
91610 ** CAPI3REF: Mutex Verifcation Routines {F17080}
91611 **
91612 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
91613 ** are intended for use inside assert() statements. {F17081} The SQLite core
91614 ** never uses these routines except inside an assert() and applications
91615 ** are advised to follow the lead of the core.  {F17082} The core only
91616 ** provides implementations for these routines when it is compiled
91617 ** with the SQLITE_DEBUG flag.  {U17087} External mutex implementations
91618 ** are only required to provide these routines if SQLITE_DEBUG is
91619 ** defined and if NDEBUG is not defined.
91620 **
91621 ** {F17083} These routines should return true if the mutex in their argument
91622 ** is held or not held, respectively, by the calling thread. {END}
91623 **
91624 ** {X17084} The implementation is not required to provided versions of these
91625 ** routines that actually work.
91626 ** If the implementation does not provide working
91627 ** versions of these routines, it should at least provide stubs
91628 ** that always return true so that one does not get spurious
91629 ** assertion failures. {END}
91630 **
91631 ** {F17085} If the argument to sqlite3_mutex_held() is a NULL pointer then
91632 ** the routine should return 1.  {END} This seems counter-intuitive since
91633 ** clearly the mutex cannot be held if it does not exist.  But the
91634 ** the reason the mutex does not exist is because the build is not
91635 ** using mutexes.  And we do not want the assert() containing the
91636 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
91637 ** the appropriate thing to do.  {F17086} The sqlite3_mutex_notheld() 
91638 ** interface should also return 1 when given a NULL pointer.
91639 */
91640 int sqlite3_mutex_held(sqlite3_mutex*);
91641 int sqlite3_mutex_notheld(sqlite3_mutex*);
91642
91643 /*
91644 ** CAPI3REF: Mutex Types {F17001}
91645 **
91646 ** {F17002} The [sqlite3_mutex_alloc()] interface takes a single argument
91647 ** which is one of these integer constants. {END}
91648 */
91649 #define SQLITE_MUTEX_FAST             0
91650 #define SQLITE_MUTEX_RECURSIVE        1
91651 #define SQLITE_MUTEX_STATIC_MASTER    2
91652 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
91653 #define SQLITE_MUTEX_STATIC_MEM2      4  /* sqlite3_release_memory() */
91654 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
91655 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
91656
91657 /*
91658 ** CAPI3REF: Low-Level Control Of Database Files {F11300}
91659 **
91660 ** {F11301} The [sqlite3_file_control()] interface makes a direct call to the
91661 ** xFileControl method for the [sqlite3_io_methods] object associated
91662 ** with a particular database identified by the second argument. {F11302} The
91663 ** name of the database is the name assigned to the database by the
91664 ** <a href="lang_attach.html">ATTACH</a> SQL command that opened the
91665 ** database. {F11303} To control the main database file, use the name "main"
91666 ** or a NULL pointer. {F11304} The third and fourth parameters to this routine
91667 ** are passed directly through to the second and third parameters of
91668 ** the xFileControl method.  {F11305} The return value of the xFileControl
91669 ** method becomes the return value of this routine.
91670 **
91671 ** {F11306} If the second parameter (zDbName) does not match the name of any
91672 ** open database file, then SQLITE_ERROR is returned. {F11307} This error
91673 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
91674 ** or [sqlite3_errmsg()]. {U11308} The underlying xFileControl method might
91675 ** also return SQLITE_ERROR.  {U11309} There is no way to distinguish between
91676 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
91677 ** xFileControl method. {END}
91678 **
91679 ** See also: [SQLITE_FCNTL_LOCKSTATE]
91680 */
91681 int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
91682
91683 /*
91684 ** Undo the hack that converts floating point types to integer for
91685 ** builds on processors without floating point support.
91686 */
91687 #ifdef SQLITE_OMIT_FLOATING_POINT
91688 # undef double
91689 #endif
91690
91691 #if 0
91692 }  /* End of the 'extern "C"' block */
91693 #endif
91694 #endif
91695
91696 /************** End of sqlite3.h *********************************************/
91697 /************** Continuing where we left off in fts3_hash.c ******************/
91698 /************** Include fts3_hash.h in the middle of fts3_hash.c *************/
91699 /************** Begin file fts3_hash.h ***************************************/
91700 /*
91701 ** 2001 September 22
91702 **
91703 ** The author disclaims copyright to this source code.  In place of
91704 ** a legal notice, here is a blessing:
91705 **
91706 **    May you do good and not evil.
91707 **    May you find forgiveness for yourself and forgive others.
91708 **    May you share freely, never taking more than you give.
91709 **
91710 *************************************************************************
91711 ** This is the header file for the generic hash-table implemenation
91712 ** used in SQLite.  We've modified it slightly to serve as a standalone
91713 ** hash table implementation for the full-text indexing module.
91714 **
91715 */
91716 #ifndef _FTS3_HASH_H_
91717 #define _FTS3_HASH_H_
91718
91719 /* Forward declarations of structures. */
91720 typedef struct fts3Hash fts3Hash;
91721 typedef struct fts3HashElem fts3HashElem;
91722
91723 /* A complete hash table is an instance of the following structure.
91724 ** The internals of this structure are intended to be opaque -- client
91725 ** code should not attempt to access or modify the fields of this structure
91726 ** directly.  Change this structure only by using the routines below.
91727 ** However, many of the "procedures" and "functions" for modifying and
91728 ** accessing this structure are really macros, so we can't really make
91729 ** this structure opaque.
91730 */
91731 struct fts3Hash {
91732   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
91733   char copyKey;           /* True if copy of key made on insert */
91734   int count;              /* Number of entries in this table */
91735   fts3HashElem *first;    /* The first element of the array */
91736   int htsize;             /* Number of buckets in the hash table */
91737   struct _fts3ht {        /* the hash table */
91738     int count;               /* Number of entries with this hash */
91739     fts3HashElem *chain;     /* Pointer to first entry with this hash */
91740   } *ht;
91741 };
91742
91743 /* Each element in the hash table is an instance of the following 
91744 ** structure.  All elements are stored on a single doubly-linked list.
91745 **
91746 ** Again, this structure is intended to be opaque, but it can't really
91747 ** be opaque because it is used by macros.
91748 */
91749 struct fts3HashElem {
91750   fts3HashElem *next, *prev; /* Next and previous elements in the table */
91751   void *data;                /* Data associated with this element */
91752   void *pKey; int nKey;      /* Key associated with this element */
91753 };
91754
91755 /*
91756 ** There are 2 different modes of operation for a hash table:
91757 **
91758 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
91759 **                           (including the null-terminator, if any).  Case
91760 **                           is respected in comparisons.
91761 **
91762 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
91763 **                           memcmp() is used to compare keys.
91764 **
91765 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
91766 */
91767 #define FTS3_HASH_STRING    1
91768 #define FTS3_HASH_BINARY    2
91769
91770 /*
91771 ** Access routines.  To delete, insert a NULL pointer.
91772 */
91773 void sqlite3Fts3HashInit(fts3Hash*, int keytype, int copyKey);
91774 void *sqlite3Fts3HashInsert(fts3Hash*, const void *pKey, int nKey, void *pData);
91775 void *sqlite3Fts3HashFind(const fts3Hash*, const void *pKey, int nKey);
91776 void sqlite3Fts3HashClear(fts3Hash*);
91777
91778 /*
91779 ** Shorthand for the functions above
91780 */
91781 #define fts3HashInit   sqlite3Fts3HashInit
91782 #define fts3HashInsert sqlite3Fts3HashInsert
91783 #define fts3HashFind   sqlite3Fts3HashFind
91784 #define fts3HashClear  sqlite3Fts3HashClear
91785
91786 /*
91787 ** Macros for looping over all elements of a hash table.  The idiom is
91788 ** like this:
91789 **
91790 **   fts3Hash h;
91791 **   fts3HashElem *p;
91792 **   ...
91793 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
91794 **     SomeStructure *pData = fts3HashData(p);
91795 **     // do something with pData
91796 **   }
91797 */
91798 #define fts3HashFirst(H)  ((H)->first)
91799 #define fts3HashNext(E)   ((E)->next)
91800 #define fts3HashData(E)   ((E)->data)
91801 #define fts3HashKey(E)    ((E)->pKey)
91802 #define fts3HashKeysize(E) ((E)->nKey)
91803
91804 /*
91805 ** Number of entries in a hash table
91806 */
91807 #define fts3HashCount(H)  ((H)->count)
91808
91809 #endif /* _FTS3_HASH_H_ */
91810
91811 /************** End of fts3_hash.h *******************************************/
91812 /************** Continuing where we left off in fts3_hash.c ******************/
91813
91814 /*
91815 ** Malloc and Free functions
91816 */
91817 static void *fts3HashMalloc(int n){
91818   void *p = sqlite3_malloc(n);
91819   if( p ){
91820     memset(p, 0, n);
91821   }
91822   return p;
91823 }
91824 static void fts3HashFree(void *p){
91825   sqlite3_free(p);
91826 }
91827
91828 /* Turn bulk memory into a hash table object by initializing the
91829 ** fields of the Hash structure.
91830 **
91831 ** "pNew" is a pointer to the hash table that is to be initialized.
91832 ** keyClass is one of the constants 
91833 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
91834 ** determines what kind of key the hash table will use.  "copyKey" is
91835 ** true if the hash table should make its own private copy of keys and
91836 ** false if it should just use the supplied pointer.
91837 */
91838 void sqlite3Fts3HashInit(fts3Hash *pNew, int keyClass, int copyKey){
91839   assert( pNew!=0 );
91840   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
91841   pNew->keyClass = keyClass;
91842   pNew->copyKey = copyKey;
91843   pNew->first = 0;
91844   pNew->count = 0;
91845   pNew->htsize = 0;
91846   pNew->ht = 0;
91847 }
91848
91849 /* Remove all entries from a hash table.  Reclaim all memory.
91850 ** Call this routine to delete a hash table or to reset a hash table
91851 ** to the empty state.
91852 */
91853 void sqlite3Fts3HashClear(fts3Hash *pH){
91854   fts3HashElem *elem;         /* For looping over all elements of the table */
91855
91856   assert( pH!=0 );
91857   elem = pH->first;
91858   pH->first = 0;
91859   fts3HashFree(pH->ht);
91860   pH->ht = 0;
91861   pH->htsize = 0;
91862   while( elem ){
91863     fts3HashElem *next_elem = elem->next;
91864     if( pH->copyKey && elem->pKey ){
91865       fts3HashFree(elem->pKey);
91866     }
91867     fts3HashFree(elem);
91868     elem = next_elem;
91869   }
91870   pH->count = 0;
91871 }
91872
91873 /*
91874 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
91875 */
91876 static int fts3StrHash(const void *pKey, int nKey){
91877   const char *z = (const char *)pKey;
91878   int h = 0;
91879   if( nKey<=0 ) nKey = (int) strlen(z);
91880   while( nKey > 0  ){
91881     h = (h<<3) ^ h ^ *z++;
91882     nKey--;
91883   }
91884   return h & 0x7fffffff;
91885 }
91886 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
91887   if( n1!=n2 ) return 1;
91888   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
91889 }
91890
91891 /*
91892 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
91893 */
91894 static int fts3BinHash(const void *pKey, int nKey){
91895   int h = 0;
91896   const char *z = (const char *)pKey;
91897   while( nKey-- > 0 ){
91898     h = (h<<3) ^ h ^ *(z++);
91899   }
91900   return h & 0x7fffffff;
91901 }
91902 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
91903   if( n1!=n2 ) return 1;
91904   return memcmp(pKey1,pKey2,n1);
91905 }
91906
91907 /*
91908 ** Return a pointer to the appropriate hash function given the key class.
91909 **
91910 ** The C syntax in this function definition may be unfamilar to some 
91911 ** programmers, so we provide the following additional explanation:
91912 **
91913 ** The name of the function is "ftsHashFunction".  The function takes a
91914 ** single parameter "keyClass".  The return value of ftsHashFunction()
91915 ** is a pointer to another function.  Specifically, the return value
91916 ** of ftsHashFunction() is a pointer to a function that takes two parameters
91917 ** with types "const void*" and "int" and returns an "int".
91918 */
91919 static int (*ftsHashFunction(int keyClass))(const void*,int){
91920   if( keyClass==FTS3_HASH_STRING ){
91921     return &fts3StrHash;
91922   }else{
91923     assert( keyClass==FTS3_HASH_BINARY );
91924     return &fts3BinHash;
91925   }
91926 }
91927
91928 /*
91929 ** Return a pointer to the appropriate hash function given the key class.
91930 **
91931 ** For help in interpreted the obscure C code in the function definition,
91932 ** see the header comment on the previous function.
91933 */
91934 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
91935   if( keyClass==FTS3_HASH_STRING ){
91936     return &fts3StrCompare;
91937   }else{
91938     assert( keyClass==FTS3_HASH_BINARY );
91939     return &fts3BinCompare;
91940   }
91941 }
91942
91943 /* Link an element into the hash table
91944 */
91945 static void fts3HashInsertElement(
91946   fts3Hash *pH,            /* The complete hash table */
91947   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
91948   fts3HashElem *pNew       /* The element to be inserted */
91949 ){
91950   fts3HashElem *pHead;     /* First element already in pEntry */
91951   pHead = pEntry->chain;
91952   if( pHead ){
91953     pNew->next = pHead;
91954     pNew->prev = pHead->prev;
91955     if( pHead->prev ){ pHead->prev->next = pNew; }
91956     else             { pH->first = pNew; }
91957     pHead->prev = pNew;
91958   }else{
91959     pNew->next = pH->first;
91960     if( pH->first ){ pH->first->prev = pNew; }
91961     pNew->prev = 0;
91962     pH->first = pNew;
91963   }
91964   pEntry->count++;
91965   pEntry->chain = pNew;
91966 }
91967
91968
91969 /* Resize the hash table so that it cantains "new_size" buckets.
91970 ** "new_size" must be a power of 2.  The hash table might fail 
91971 ** to resize if sqliteMalloc() fails.
91972 */
91973 static void fts3Rehash(fts3Hash *pH, int new_size){
91974   struct _fts3ht *new_ht;          /* The new hash table */
91975   fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
91976   int (*xHash)(const void*,int);   /* The hash function */
91977
91978   assert( (new_size & (new_size-1))==0 );
91979   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
91980   if( new_ht==0 ) return;
91981   fts3HashFree(pH->ht);
91982   pH->ht = new_ht;
91983   pH->htsize = new_size;
91984   xHash = ftsHashFunction(pH->keyClass);
91985   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
91986     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
91987     next_elem = elem->next;
91988     fts3HashInsertElement(pH, &new_ht[h], elem);
91989   }
91990 }
91991
91992 /* This function (for internal use only) locates an element in an
91993 ** hash table that matches the given key.  The hash for this key has
91994 ** already been computed and is passed as the 4th parameter.
91995 */
91996 static fts3HashElem *fts3FindElementByHash(
91997   const fts3Hash *pH, /* The pH to be searched */
91998   const void *pKey,   /* The key we are searching for */
91999   int nKey,
92000   int h               /* The hash for this key. */
92001 ){
92002   fts3HashElem *elem;            /* Used to loop thru the element list */
92003   int count;                     /* Number of elements left to test */
92004   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
92005
92006   if( pH->ht ){
92007     struct _fts3ht *pEntry = &pH->ht[h];
92008     elem = pEntry->chain;
92009     count = pEntry->count;
92010     xCompare = ftsCompareFunction(pH->keyClass);
92011     while( count-- && elem ){
92012       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
92013         return elem;
92014       }
92015       elem = elem->next;
92016     }
92017   }
92018   return 0;
92019 }
92020
92021 /* Remove a single entry from the hash table given a pointer to that
92022 ** element and a hash on the element's key.
92023 */
92024 static void fts3RemoveElementByHash(
92025   fts3Hash *pH,         /* The pH containing "elem" */
92026   fts3HashElem* elem,   /* The element to be removed from the pH */
92027   int h                 /* Hash value for the element */
92028 ){
92029   struct _fts3ht *pEntry;
92030   if( elem->prev ){
92031     elem->prev->next = elem->next; 
92032   }else{
92033     pH->first = elem->next;
92034   }
92035   if( elem->next ){
92036     elem->next->prev = elem->prev;
92037   }
92038   pEntry = &pH->ht[h];
92039   if( pEntry->chain==elem ){
92040     pEntry->chain = elem->next;
92041   }
92042   pEntry->count--;
92043   if( pEntry->count<=0 ){
92044     pEntry->chain = 0;
92045   }
92046   if( pH->copyKey && elem->pKey ){
92047     fts3HashFree(elem->pKey);
92048   }
92049   fts3HashFree( elem );
92050   pH->count--;
92051   if( pH->count<=0 ){
92052     assert( pH->first==0 );
92053     assert( pH->count==0 );
92054     fts3HashClear(pH);
92055   }
92056 }
92057
92058 /* Attempt to locate an element of the hash table pH with a key
92059 ** that matches pKey,nKey.  Return the data for this element if it is
92060 ** found, or NULL if there is no match.
92061 */
92062 void *sqlite3Fts3HashFind(const fts3Hash *pH, const void *pKey, int nKey){
92063   int h;                 /* A hash on key */
92064   fts3HashElem *elem;    /* The element that matches key */
92065   int (*xHash)(const void*,int);  /* The hash function */
92066
92067   if( pH==0 || pH->ht==0 ) return 0;
92068   xHash = ftsHashFunction(pH->keyClass);
92069   assert( xHash!=0 );
92070   h = (*xHash)(pKey,nKey);
92071   assert( (pH->htsize & (pH->htsize-1))==0 );
92072   elem = fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
92073   return elem ? elem->data : 0;
92074 }
92075
92076 /* Insert an element into the hash table pH.  The key is pKey,nKey
92077 ** and the data is "data".
92078 **
92079 ** If no element exists with a matching key, then a new
92080 ** element is created.  A copy of the key is made if the copyKey
92081 ** flag is set.  NULL is returned.
92082 **
92083 ** If another element already exists with the same key, then the
92084 ** new data replaces the old data and the old data is returned.
92085 ** The key is not copied in this instance.  If a malloc fails, then
92086 ** the new data is returned and the hash table is unchanged.
92087 **
92088 ** If the "data" parameter to this function is NULL, then the
92089 ** element corresponding to "key" is removed from the hash table.
92090 */
92091 void *sqlite3Fts3HashInsert(
92092   fts3Hash *pH,        /* The hash table to insert into */
92093   const void *pKey,    /* The key */
92094   int nKey,            /* Number of bytes in the key */
92095   void *data           /* The data */
92096 ){
92097   int hraw;                 /* Raw hash value of the key */
92098   int h;                    /* the hash of the key modulo hash table size */
92099   fts3HashElem *elem;       /* Used to loop thru the element list */
92100   fts3HashElem *new_elem;   /* New element added to the pH */
92101   int (*xHash)(const void*,int);  /* The hash function */
92102
92103   assert( pH!=0 );
92104   xHash = ftsHashFunction(pH->keyClass);
92105   assert( xHash!=0 );
92106   hraw = (*xHash)(pKey, nKey);
92107   assert( (pH->htsize & (pH->htsize-1))==0 );
92108   h = hraw & (pH->htsize-1);
92109   elem = fts3FindElementByHash(pH,pKey,nKey,h);
92110   if( elem ){
92111     void *old_data = elem->data;
92112     if( data==0 ){
92113       fts3RemoveElementByHash(pH,elem,h);
92114     }else{
92115       elem->data = data;
92116     }
92117     return old_data;
92118   }
92119   if( data==0 ) return 0;
92120   new_elem = (fts3HashElem*)fts3HashMalloc( sizeof(fts3HashElem) );
92121   if( new_elem==0 ) return data;
92122   if( pH->copyKey && pKey!=0 ){
92123     new_elem->pKey = fts3HashMalloc( nKey );
92124     if( new_elem->pKey==0 ){
92125       fts3HashFree(new_elem);
92126       return data;
92127     }
92128     memcpy((void*)new_elem->pKey, pKey, nKey);
92129   }else{
92130     new_elem->pKey = (void*)pKey;
92131   }
92132   new_elem->nKey = nKey;
92133   pH->count++;
92134   if( pH->htsize==0 ){
92135     fts3Rehash(pH,8);
92136     if( pH->htsize==0 ){
92137       pH->count = 0;
92138       fts3HashFree(new_elem);
92139       return data;
92140     }
92141   }
92142   if( pH->count > pH->htsize ){
92143     fts3Rehash(pH,pH->htsize*2);
92144   }
92145   assert( pH->htsize>0 );
92146   assert( (pH->htsize & (pH->htsize-1))==0 );
92147   h = hraw & (pH->htsize-1);
92148   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
92149   new_elem->data = data;
92150   return 0;
92151 }
92152
92153 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
92154
92155 /************** End of fts3_hash.c *******************************************/
92156 /************** Begin file fts3_porter.c *************************************/
92157 /*
92158 ** 2006 September 30
92159 **
92160 ** The author disclaims copyright to this source code.  In place of
92161 ** a legal notice, here is a blessing:
92162 **
92163 **    May you do good and not evil.
92164 **    May you find forgiveness for yourself and forgive others.
92165 **    May you share freely, never taking more than you give.
92166 **
92167 *************************************************************************
92168 ** Implementation of the full-text-search tokenizer that implements
92169 ** a Porter stemmer.
92170 */
92171
92172 /*
92173 ** The code in this file is only compiled if:
92174 **
92175 **     * The FTS3 module is being built as an extension
92176 **       (in which case SQLITE_CORE is not defined), or
92177 **
92178 **     * The FTS3 module is being built into the core of
92179 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
92180 */
92181 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
92182
92183
92184
92185 /************** Include fts3_tokenizer.h in the middle of fts3_porter.c ******/
92186 /************** Begin file fts3_tokenizer.h **********************************/
92187 /*
92188 ** 2006 July 10
92189 **
92190 ** The author disclaims copyright to this source code.
92191 **
92192 *************************************************************************
92193 ** Defines the interface to tokenizers used by fulltext-search.  There
92194 ** are three basic components:
92195 **
92196 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
92197 ** interface functions.  This is essentially the class structure for
92198 ** tokenizers.
92199 **
92200 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
92201 ** including customization information defined at creation time.
92202 **
92203 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
92204 ** tokens from a particular input.
92205 */
92206 #ifndef _FTS3_TOKENIZER_H_
92207 #define _FTS3_TOKENIZER_H_
92208
92209 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
92210 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
92211 ** we will need a way to register the API consistently.
92212 */
92213 /************** Include sqlite3.h in the middle of fts3_tokenizer.h **********/
92214 /************** Begin file sqlite3.h *****************************************/
92215 /*
92216 ** 2001 September 15
92217 **
92218 ** The author disclaims copyright to this source code.  In place of
92219 ** a legal notice, here is a blessing:
92220 **
92221 **    May you do good and not evil.
92222 **    May you find forgiveness for yourself and forgive others.
92223 **    May you share freely, never taking more than you give.
92224 **
92225 *************************************************************************
92226 ** This header file defines the interface that the SQLite library
92227 ** presents to client programs.  If a C-function, structure, datatype,
92228 ** or constant definition does not appear in this file, then it is
92229 ** not a published API of SQLite, is subject to change without
92230 ** notice, and should not be referenced by programs that use SQLite.
92231 **
92232 ** Some of the definitions that are in this file are marked as
92233 ** "experimental".  Experimental interfaces are normally new
92234 ** features recently added to SQLite.  We do not anticipate changes 
92235 ** to experimental interfaces but reserve to make minor changes if
92236 ** experience from use "in the wild" suggest such changes are prudent.
92237 **
92238 ** The official C-language API documentation for SQLite is derived
92239 ** from comments in this file.  This file is the authoritative source
92240 ** on how SQLite interfaces are suppose to operate.
92241 **
92242 ** The name of this file under configuration management is "sqlite.h.in".
92243 ** The makefile makes some minor changes to this file (such as inserting
92244 ** the version number) and changes its name to "sqlite3.h" as
92245 ** part of the build process.
92246 **
92247 ** @(#) $Id: sqlite.h.in,v 1.278 2007/12/13 21:54:11 drh Exp $
92248 */
92249 #ifndef _SQLITE3_H_
92250 #define _SQLITE3_H_
92251
92252 /*
92253 ** Make sure we can call this stuff from C++.
92254 */
92255 #if 0
92256 extern "C" {
92257 #endif
92258
92259
92260 /*
92261 ** Add the ability to override 'extern'
92262 */
92263 #ifndef SQLITE_EXTERN
92264 # define SQLITE_EXTERN extern
92265 #endif
92266
92267 /*
92268 ** Make sure these symbols where not defined by some previous header
92269 ** file.
92270 */
92271 #ifdef SQLITE_VERSION
92272 # undef SQLITE_VERSION
92273 #endif
92274 #ifdef SQLITE_VERSION_NUMBER
92275 # undef SQLITE_VERSION_NUMBER
92276 #endif
92277
92278 /*
92279 ** CAPI3REF: Compile-Time Library Version Numbers {F10010}
92280 **
92281 ** {F10011} The #define in the sqlite3.h header file named
92282 ** SQLITE_VERSION resolves to a string literal that identifies
92283 ** the version of the SQLite library in the format "X.Y.Z", where
92284 ** X is the major version number, Y is the minor version number and Z
92285 ** is the release number.  The X.Y.Z might be followed by "alpha" or "beta".
92286 ** {END} For example "3.1.1beta".
92287 **
92288 ** The X value is always 3 in SQLite.  The X value only changes when
92289 ** backwards compatibility is broken and we intend to never break
92290 ** backwards compatibility.  The Y value only changes when
92291 ** there are major feature enhancements that are forwards compatible
92292 ** but not backwards compatible.  The Z value is incremented with
92293 ** each release but resets back to 0 when Y is incremented.
92294 **
92295 ** {F10014} The SQLITE_VERSION_NUMBER #define resolves to an integer
92296 ** with the value  (X*1000000 + Y*1000 + Z) where X, Y, and Z are as
92297 ** with SQLITE_VERSION. {END} For example, for version "3.1.1beta", 
92298 ** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using 
92299 ** version 3.1.1 or greater at compile time, programs may use the test 
92300 ** (SQLITE_VERSION_NUMBER>=3001001).
92301 **
92302 ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
92303 */
92304 #define SQLITE_VERSION         "3.5.4"
92305 #define SQLITE_VERSION_NUMBER 3005004
92306
92307 /*
92308 ** CAPI3REF: Run-Time Library Version Numbers {F10020}
92309 **
92310 ** {F10021} The sqlite3_libversion_number() interface returns an integer
92311 ** equal to [SQLITE_VERSION_NUMBER].  {END} The value returned
92312 ** by this routine should only be different from the header values
92313 ** if the application is compiled using an sqlite3.h header from a
92314 ** different version of SQLite than library.  Cautious programmers might
92315 ** include a check in their application to verify that 
92316 ** sqlite3_libversion_number() always returns the value 
92317 ** [SQLITE_VERSION_NUMBER].
92318 **
92319 ** {F10022} The sqlite3_version[] string constant contains the text of the
92320 ** [SQLITE_VERSION] string. {F10023} The sqlite3_libversion() function returns
92321 ** a pointer to the sqlite3_version[] string constant. {END} The 
92322 ** sqlite3_libversion() function
92323 ** is provided for DLL users who can only access functions and not
92324 ** constants within the DLL.
92325 */
92326 SQLITE_EXTERN const char sqlite3_version[];
92327 const char *sqlite3_libversion(void);
92328 int sqlite3_libversion_number(void);
92329
92330 /*
92331 ** CAPI3REF: Test To See If The Library Is Threadsafe {F10100}
92332 **
92333 ** {F10101} The sqlite3_threadsafe() routine returns nonzero
92334 ** if SQLite was compiled with its mutexes enabled or zero if
92335 ** SQLite was compiled with mutexes disabled. {END}  If this
92336 ** routine returns false, then it is not safe for simultaneously
92337 ** running threads to both invoke SQLite interfaces.
92338 **
92339 ** Really all this routine does is return true if SQLite was
92340 ** compiled with the -DSQLITE_THREADSAFE=1 option and false if
92341 ** compiled with -DSQLITE_THREADSAFE=0.  If SQLite uses an
92342 ** application-defined mutex subsystem, malloc subsystem, collating
92343 ** sequence, VFS, SQL function, progress callback, commit hook,
92344 ** extension, or other accessories and these add-ons are not
92345 ** threadsafe, then clearly the combination will not be threadsafe
92346 ** either.  Hence, this routine never reports that the library
92347 ** is guaranteed to be threadsafe, only when it is guaranteed not
92348 ** to be.
92349 */
92350 int sqlite3_threadsafe(void);
92351
92352 /*
92353 ** CAPI3REF: Database Connection Handle {F12000}
92354 **
92355 ** Each open SQLite database is represented by pointer to an instance of the
92356 ** opaque structure named "sqlite3".  It is useful to think of an sqlite3
92357 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
92358 ** [sqlite3_open_v2()] interfaces are its constructors
92359 ** and [sqlite3_close()] is its destructor.  There are many other interfaces
92360 ** (such as [sqlite3_prepare_v2()], [sqlite3_create_function()], and
92361 ** [sqlite3_busy_timeout()] to name but three) that are methods on this
92362 ** object.
92363 */
92364 typedef struct sqlite3 sqlite3;
92365
92366
92367 /*
92368 ** CAPI3REF: 64-Bit Integer Types {F10200}
92369 **
92370 ** Because there is no cross-platform way to specify such types
92371 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
92372 ** {F10201} The sqlite_int64 and sqlite3_int64 types specify a
92373 ** 64-bit signed integer. {F10202} The sqlite_uint64 and
92374 ** sqlite3_uint64 types specify a 64-bit unsigned integer. {END}
92375 **
92376 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type
92377 ** definitions.  The sqlite_int64 and sqlite_uint64 types are
92378 ** supported for backwards compatibility only.
92379 */
92380 #ifdef SQLITE_INT64_TYPE
92381   typedef SQLITE_INT64_TYPE sqlite_int64;
92382   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
92383 #elif defined(_MSC_VER) || defined(__BORLANDC__)
92384   typedef __int64 sqlite_int64;
92385   typedef unsigned __int64 sqlite_uint64;
92386 #else
92387   typedef long long int sqlite_int64;
92388   typedef unsigned long long int sqlite_uint64;
92389 #endif
92390 typedef sqlite_int64 sqlite3_int64;
92391 typedef sqlite_uint64 sqlite3_uint64;
92392
92393 /*
92394 ** If compiling for a processor that lacks floating point support,
92395 ** substitute integer for floating-point
92396 */
92397 #ifdef SQLITE_OMIT_FLOATING_POINT
92398 # define double sqlite3_int64
92399 #endif
92400
92401 /*
92402 ** CAPI3REF: Closing A Database Connection {F12010}
92403 **
92404 ** {F12011} The sqlite3_close() interfaces destroys an [sqlite3] object
92405 ** allocated by a prior call to [sqlite3_open()], [sqlite3_open16()], or
92406 ** [sqlite3_open_v2()]. {F12012} Sqlite3_close() releases all
92407 ** memory used by the connection and closes all open files. {END}.
92408 **
92409 ** {F12013} If the database connection contains
92410 ** [sqlite3_stmt | prepared statements] that have not been finalized
92411 ** by [sqlite3_finalize()], then sqlite3_close() returns SQLITE_BUSY
92412 ** and leaves the connection open.  {F12014} Giving sqlite3_close()
92413 ** a NULL pointer is a harmless no-op. {END}
92414 **
92415 ** {U12015} Passing this routine a database connection that has already been
92416 ** closed results in undefined behavior. {U12016} If other interfaces that
92417 ** reference the same database connection are pending (either in the
92418 ** same thread or in different threads) when this routine is called,
92419 ** then the behavior is undefined and is almost certainly undesirable.
92420 */
92421 int sqlite3_close(sqlite3 *);
92422
92423 /*
92424 ** The type for a callback function.
92425 ** This is legacy and deprecated.  It is included for historical
92426 ** compatibility and is not documented.
92427 */
92428 typedef int (*sqlite3_callback)(void*,int,char**, char**);
92429
92430 /*
92431 ** CAPI3REF: One-Step Query Execution Interface {F12100}
92432 **
92433 ** {F12101} The sqlite3_exec() interface evaluates zero or more 
92434 ** UTF-8 encoded, semicolon-separated SQL statements in the zero-terminated
92435 ** string of its second argument.  {F12102} The SQL
92436 ** statements are evaluated in the context of the database connection
92437 ** specified by in the first argument.
92438 ** {F12103} SQL statements are prepared one by one using
92439 ** [sqlite3_prepare()] or the equivalent, evaluated
92440 ** using one or more calls to [sqlite3_step()], then destroyed
92441 ** using [sqlite3_finalize()]. {F12104} The return value of
92442 ** sqlite3_exec() is SQLITE_OK if all SQL statement run
92443 ** successfully.
92444 **
92445 ** {F12105} If one or more of the SQL statements handed to
92446 ** sqlite3_exec() are queries, then
92447 ** the callback function specified by the 3rd parameter is
92448 ** invoked once for each row of the query result. {F12106}
92449 ** If the callback returns a non-zero value then the query
92450 ** is aborted, all subsequent SQL statements
92451 ** are skipped and the sqlite3_exec() function returns the [SQLITE_ABORT].
92452 **
92453 ** {F12107} The 4th parameter to sqlite3_exec() is an arbitrary pointer
92454 ** that is passed through to the callback function as its first parameter.
92455 **
92456 ** {F12108} The 2nd parameter to the callback function is the number of
92457 ** columns in the query result.  {F12109} The 3rd parameter to the callback
92458 ** is an array of pointers to strings holding the values for each column
92459 ** as extracted using [sqlite3_column_text()].  NULL values in the result
92460 ** set result in a NULL pointer.  All other value are in their UTF-8
92461 ** string representation. {F12117}
92462 ** The 4th parameter to the callback is an array of strings
92463 ** obtained using [sqlite3_column_name()] and holding
92464 ** the names of each column, also in UTF-8.
92465 **
92466 ** {F12110} The callback function may be NULL, even for queries.  A NULL
92467 ** callback is not an error.  It just means that no callback
92468 ** will be invoked. 
92469 **
92470 ** {F12112} If an error occurs while parsing or evaluating the SQL
92471 ** then an appropriate error message is written into memory obtained
92472 ** from [sqlite3_malloc()] and *errmsg is made to point to that message
92473 ** assuming errmsg is not NULL.  
92474 ** {U12113} The calling function is responsible for freeing the memory
92475 ** using [sqlite3_free()].
92476 ** {F12116} If [sqlite3_malloc()] fails while attempting to generate
92477 ** the error message, *errmsg is set to NULL.
92478 ** {F12114} If errmsg is NULL then no attempt is made to generate an
92479 ** error message. <todo>Is the return code SQLITE_NOMEM or the original
92480 ** error code?</todo> <todo>What happens if there are multiple errors?
92481 ** Do we get code for the first error, or is the choice of reported
92482 ** error arbitrary?</todo>
92483 **
92484 ** {F12115} The return value is is SQLITE_OK if there are no errors and
92485 ** some other [SQLITE_OK | return code] if there is an error.  
92486 ** The particular return value depends on the type of error.  {END}
92487 */
92488 int sqlite3_exec(
92489   sqlite3*,                                  /* An open database */
92490   const char *sql,                           /* SQL to be evaluted */
92491   int (*callback)(void*,int,char**,char**),  /* Callback function */
92492   void *,                                    /* 1st argument to callback */
92493   char **errmsg                              /* Error msg written here */
92494 );
92495
92496 /*
92497 ** CAPI3REF: Result Codes {F10210}
92498 ** KEYWORDS: SQLITE_OK
92499 **
92500 ** Many SQLite functions return an integer result code from the set shown
92501 ** above in order to indicates success or failure.
92502 **
92503 ** {F10211} The result codes shown here are the only ones returned 
92504 ** by SQLite in its default configuration. {F10212} However, the
92505 ** [sqlite3_extended_result_codes()] API can be used to set a database
92506 ** connectoin to return more detailed result codes. {END}
92507 **
92508 ** See also: [SQLITE_IOERR_READ | extended result codes]
92509 **
92510 */
92511 #define SQLITE_OK           0   /* Successful result */
92512 /* beginning-of-error-codes */
92513 #define SQLITE_ERROR        1   /* SQL error or missing database */
92514 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
92515 #define SQLITE_PERM         3   /* Access permission denied */
92516 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
92517 #define SQLITE_BUSY         5   /* The database file is locked */
92518 #define SQLITE_LOCKED       6   /* A table in the database is locked */
92519 #define SQLITE_NOMEM        7   /* A malloc() failed */
92520 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
92521 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
92522 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
92523 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
92524 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
92525 #define SQLITE_FULL        13   /* Insertion failed because database is full */
92526 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
92527 #define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
92528 #define SQLITE_EMPTY       16   /* Database is empty */
92529 #define SQLITE_SCHEMA      17   /* The database schema changed */
92530 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
92531 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
92532 #define SQLITE_MISMATCH    20   /* Data type mismatch */
92533 #define SQLITE_MISUSE      21   /* Library used incorrectly */
92534 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
92535 #define SQLITE_AUTH        23   /* Authorization denied */
92536 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
92537 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
92538 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
92539 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
92540 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
92541 /* end-of-error-codes */
92542
92543 /*
92544 ** CAPI3REF: Extended Result Codes {F10220}
92545 **
92546 ** In its default configuration, SQLite API routines return one of 26 integer
92547 ** [SQLITE_OK | result codes].  However, experience has shown that
92548 ** many of these result codes are too course-grained.  They do not provide as
92549 ** much information about problems as programmers might like.  In an effort to
92550 ** address this, newer versions of SQLite (version 3.3.8 and later) include
92551 ** support for additional result codes that provide more detailed information
92552 ** about errors. {F10221} The extended result codes are enabled or disabled
92553 ** for each database connection using the [sqlite3_extended_result_codes()]
92554 ** API. {END}
92555 ** 
92556 ** Some of the available extended result codes are listed above.
92557 ** We expect the number of extended result codes will be expand
92558 ** over time.  {U10422} Software that uses extended result codes should expect
92559 ** to see new result codes in future releases of SQLite. {END}
92560 ** 
92561 ** {F10223} The symbolic name for an extended result code always contains
92562 ** a related primary result code as a prefix. {F10224} Primary result
92563 ** codes contain a single "_" character.  {F10225} Extended result codes
92564 ** contain two or more "_" characters. {F10226} The numeric value of an
92565 ** extended result code can be converted to its
92566 ** corresponding primary result code by masking off the lower 8 bytes. {END}
92567 **
92568 ** The SQLITE_OK result code will never be extended.  It will always
92569 ** be exactly zero.
92570 */
92571 #define SQLITE_IOERR_READ          (SQLITE_IOERR | (1<<8))
92572 #define SQLITE_IOERR_SHORT_READ    (SQLITE_IOERR | (2<<8))
92573 #define SQLITE_IOERR_WRITE         (SQLITE_IOERR | (3<<8))
92574 #define SQLITE_IOERR_FSYNC         (SQLITE_IOERR | (4<<8))
92575 #define SQLITE_IOERR_DIR_FSYNC     (SQLITE_IOERR | (5<<8))
92576 #define SQLITE_IOERR_TRUNCATE      (SQLITE_IOERR | (6<<8))
92577 #define SQLITE_IOERR_FSTAT         (SQLITE_IOERR | (7<<8))
92578 #define SQLITE_IOERR_UNLOCK        (SQLITE_IOERR | (8<<8))
92579 #define SQLITE_IOERR_RDLOCK        (SQLITE_IOERR | (9<<8))
92580 #define SQLITE_IOERR_DELETE        (SQLITE_IOERR | (10<<8))
92581 #define SQLITE_IOERR_BLOCKED       (SQLITE_IOERR | (11<<8))
92582 #define SQLITE_IOERR_NOMEM         (SQLITE_IOERR | (12<<8))
92583
92584 /*
92585 ** CAPI3REF: Flags For File Open Operations {F10230}
92586 **
92587 ** {F10231} Some combination of the these bit values are used as the
92588 ** third argument to the [sqlite3_open_v2()] interface and
92589 ** as fourth argument to the xOpen method of the
92590 ** [sqlite3_vfs] object.
92591 */
92592 #define SQLITE_OPEN_READONLY         0x00000001
92593 #define SQLITE_OPEN_READWRITE        0x00000002
92594 #define SQLITE_OPEN_CREATE           0x00000004
92595 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008
92596 #define SQLITE_OPEN_EXCLUSIVE        0x00000010
92597 #define SQLITE_OPEN_MAIN_DB          0x00000100
92598 #define SQLITE_OPEN_TEMP_DB          0x00000200
92599 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400
92600 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800
92601 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000
92602 #define SQLITE_OPEN_SUBJOURNAL       0x00002000
92603 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000
92604
92605 /*
92606 ** CAPI3REF: Device Characteristics {F10240}
92607 **
92608 ** {F10241} The xDeviceCapabilities method of the [sqlite3_io_methods]
92609 ** object returns an integer which is a vector of the these
92610 ** bit values expressing I/O characteristics of the mass storage
92611 ** device that holds the file that the [sqlite3_io_methods]
92612 ** refers to. {END}
92613 **
92614 ** {F10242} The SQLITE_IOCAP_ATOMIC property means that all writes of
92615 ** any size are atomic.  {F10243} The SQLITE_IOCAP_ATOMICnnn values
92616 ** mean that writes of blocks that are nnn bytes in size and
92617 ** are aligned to an address which is an integer multiple of
92618 ** nnn are atomic.  {F10244} The SQLITE_IOCAP_SAFE_APPEND value means
92619 ** that when data is appended to a file, the data is appended
92620 ** first then the size of the file is extended, never the other
92621 ** way around.  {F10245} The SQLITE_IOCAP_SEQUENTIAL property means that
92622 ** information is written to disk in the same order as calls
92623 ** to xWrite().
92624 */
92625 #define SQLITE_IOCAP_ATOMIC          0x00000001
92626 #define SQLITE_IOCAP_ATOMIC512       0x00000002
92627 #define SQLITE_IOCAP_ATOMIC1K        0x00000004
92628 #define SQLITE_IOCAP_ATOMIC2K        0x00000008
92629 #define SQLITE_IOCAP_ATOMIC4K        0x00000010
92630 #define SQLITE_IOCAP_ATOMIC8K        0x00000020
92631 #define SQLITE_IOCAP_ATOMIC16K       0x00000040
92632 #define SQLITE_IOCAP_ATOMIC32K       0x00000080
92633 #define SQLITE_IOCAP_ATOMIC64K       0x00000100
92634 #define SQLITE_IOCAP_SAFE_APPEND     0x00000200
92635 #define SQLITE_IOCAP_SEQUENTIAL      0x00000400
92636
92637 /*
92638 ** CAPI3REF: File Locking Levels {F10250}
92639 **
92640 ** {F10251} SQLite uses one of the following integer values as the second
92641 ** argument to calls it makes to the xLock() and xUnlock() methods
92642 ** of an [sqlite3_io_methods] object. {END}
92643 */
92644 #define SQLITE_LOCK_NONE          0
92645 #define SQLITE_LOCK_SHARED        1
92646 #define SQLITE_LOCK_RESERVED      2
92647 #define SQLITE_LOCK_PENDING       3
92648 #define SQLITE_LOCK_EXCLUSIVE     4
92649
92650 /*
92651 ** CAPI3REF: Synchronization Type Flags {F10260}
92652 **
92653 ** {F10261} When SQLite invokes the xSync() method of an
92654 ** [sqlite3_io_methods] object it uses a combination of the
92655 ** these integer values as the second argument.
92656 **
92657 ** {F10262} When the SQLITE_SYNC_DATAONLY flag is used, it means that the
92658 ** sync operation only needs to flush data to mass storage.  Inode
92659 ** information need not be flushed. {F10263} The SQLITE_SYNC_NORMAL means 
92660 ** to use normal fsync() semantics. {F10264} The SQLITE_SYNC_FULL flag means 
92661 ** to use Mac OS-X style fullsync instead of fsync().
92662 */
92663 #define SQLITE_SYNC_NORMAL        0x00002
92664 #define SQLITE_SYNC_FULL          0x00003
92665 #define SQLITE_SYNC_DATAONLY      0x00010
92666
92667
92668 /*
92669 ** CAPI3REF: OS Interface Open File Handle {F11110}
92670 **
92671 ** An [sqlite3_file] object represents an open file in the OS
92672 ** interface layer.  Individual OS interface implementations will
92673 ** want to subclass this object by appending additional fields
92674 ** for their own use.  The pMethods entry is a pointer to an
92675 ** [sqlite3_io_methods] object that defines methods for performing
92676 ** I/O operations on the open file.
92677 */
92678 typedef struct sqlite3_file sqlite3_file;
92679 struct sqlite3_file {
92680   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
92681 };
92682
92683 /*
92684 ** CAPI3REF: OS Interface File Virtual Methods Object {F11120}
92685 **
92686 ** Every file opened by the [sqlite3_vfs] xOpen method contains a pointer to
92687 ** an instance of the this object.  This object defines the
92688 ** methods used to perform various operations against the open file.
92689 **
92690 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
92691 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
92692 *  The second choice is an
92693 ** OS-X style fullsync.  The SQLITE_SYNC_DATA flag may be ORed in to
92694 ** indicate that only the data of the file and not its inode needs to be
92695 ** synced.
92696 ** 
92697 ** The integer values to xLock() and xUnlock() are one of
92698 ** <ul>
92699 ** <li> [SQLITE_LOCK_NONE],
92700 ** <li> [SQLITE_LOCK_SHARED],
92701 ** <li> [SQLITE_LOCK_RESERVED],
92702 ** <li> [SQLITE_LOCK_PENDING], or
92703 ** <li> [SQLITE_LOCK_EXCLUSIVE].
92704 ** </ul>
92705 ** xLock() increases the lock. xUnlock() decreases the lock.  
92706 ** The xCheckReservedLock() method looks
92707 ** to see if any database connection, either in this
92708 ** process or in some other process, is holding an RESERVED,
92709 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
92710 ** if such a lock exists and false if not.
92711 ** 
92712 ** The xFileControl() method is a generic interface that allows custom
92713 ** VFS implementations to directly control an open file using the
92714 ** [sqlite3_file_control()] interface.  The second "op" argument
92715 ** is an integer opcode.   The third
92716 ** argument is a generic pointer which is intended to be a pointer
92717 ** to a structure that may contain arguments or space in which to
92718 ** write return values.  Potential uses for xFileControl() might be
92719 ** functions to enable blocking locks with timeouts, to change the
92720 ** locking strategy (for example to use dot-file locks), to inquire
92721 ** about the status of a lock, or to break stale locks.  The SQLite
92722 ** core reserves opcodes less than 100 for its own use. 
92723 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
92724 ** Applications that define a custom xFileControl method should use opcodes 
92725 ** greater than 100 to avoid conflicts.
92726 **
92727 ** The xSectorSize() method returns the sector size of the
92728 ** device that underlies the file.  The sector size is the
92729 ** minimum write that can be performed without disturbing
92730 ** other bytes in the file.  The xDeviceCharacteristics()
92731 ** method returns a bit vector describing behaviors of the
92732 ** underlying device:
92733 **
92734 ** <ul>
92735 ** <li> [SQLITE_IOCAP_ATOMIC]
92736 ** <li> [SQLITE_IOCAP_ATOMIC512]
92737 ** <li> [SQLITE_IOCAP_ATOMIC1K]
92738 ** <li> [SQLITE_IOCAP_ATOMIC2K]
92739 ** <li> [SQLITE_IOCAP_ATOMIC4K]
92740 ** <li> [SQLITE_IOCAP_ATOMIC8K]
92741 ** <li> [SQLITE_IOCAP_ATOMIC16K]
92742 ** <li> [SQLITE_IOCAP_ATOMIC32K]
92743 ** <li> [SQLITE_IOCAP_ATOMIC64K]
92744 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
92745 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
92746 ** </ul>
92747 **
92748 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
92749 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
92750 ** mean that writes of blocks that are nnn bytes in size and
92751 ** are aligned to an address which is an integer multiple of
92752 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
92753 ** that when data is appended to a file, the data is appended
92754 ** first then the size of the file is extended, never the other
92755 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
92756 ** information is written to disk in the same order as calls
92757 ** to xWrite().
92758 */
92759 typedef struct sqlite3_io_methods sqlite3_io_methods;
92760 struct sqlite3_io_methods {
92761   int iVersion;
92762   int (*xClose)(sqlite3_file*);
92763   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
92764   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
92765   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
92766   int (*xSync)(sqlite3_file*, int flags);
92767   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
92768   int (*xLock)(sqlite3_file*, int);
92769   int (*xUnlock)(sqlite3_file*, int);
92770   int (*xCheckReservedLock)(sqlite3_file*);
92771   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
92772   int (*xSectorSize)(sqlite3_file*);
92773   int (*xDeviceCharacteristics)(sqlite3_file*);
92774   /* Additional methods may be added in future releases */
92775 };
92776
92777 /*
92778 ** CAPI3REF: Standard File Control Opcodes {F11310}
92779 **
92780 ** These integer constants are opcodes for the xFileControl method
92781 ** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()]
92782 ** interface.
92783 **
92784 ** {F11311} The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
92785 ** opcode cases the xFileControl method to write the current state of
92786 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
92787 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
92788 ** into an integer that the pArg argument points to. {F11312} This capability
92789 ** is used during testing and only needs to be supported when SQLITE_TEST
92790 ** is defined.
92791 */
92792 #define SQLITE_FCNTL_LOCKSTATE        1
92793
92794 /*
92795 ** CAPI3REF: Mutex Handle {F17110}
92796 **
92797 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
92798 ** abstract type for a mutex object.  {F17111} The SQLite core never looks
92799 ** at the internal representation of an [sqlite3_mutex]. {END} It only
92800 ** deals with pointers to the [sqlite3_mutex] object.
92801 **
92802 ** Mutexes are created using [sqlite3_mutex_alloc()].
92803 */
92804 typedef struct sqlite3_mutex sqlite3_mutex;
92805
92806 /*
92807 ** CAPI3REF: OS Interface Object {F11140}
92808 **
92809 ** An instance of this object defines the interface between the
92810 ** SQLite core and the underlying operating system.  The "vfs"
92811 ** in the name of the object stands for "virtual file system".
92812 **
92813 ** The iVersion field is initially 1 but may be larger for future
92814 ** versions of SQLite.  Additional fields may be appended to this
92815 ** object when the iVersion value is increased.
92816 **
92817 ** The szOsFile field is the size of the subclassed [sqlite3_file]
92818 ** structure used by this VFS.  mxPathname is the maximum length of
92819 ** a pathname in this VFS.
92820 **
92821 ** Registered vfs modules are kept on a linked list formed by
92822 ** the pNext pointer.  The [sqlite3_vfs_register()]
92823 ** and [sqlite3_vfs_unregister()] interfaces manage this list
92824 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
92825 ** searches the list.
92826 **
92827 ** The pNext field is the only fields in the sqlite3_vfs 
92828 ** structure that SQLite will ever modify.  SQLite will only access
92829 ** or modify this field while holding a particular static mutex.
92830 ** The application should never modify anything within the sqlite3_vfs
92831 ** object once the object has been registered.
92832 **
92833 ** The zName field holds the name of the VFS module.  The name must
92834 ** be unique across all VFS modules.
92835 **
92836 ** {F11141} SQLite will guarantee that the zFilename string passed to
92837 ** xOpen() is a full pathname as generated by xFullPathname() and
92838 ** that the string will be valid and unchanged until xClose() is
92839 ** called.  {END} So the [sqlite3_file] can store a pointer to the
92840 ** filename if it needs to remember the filename for some reason.
92841 **
92842 ** {F11142} The flags argument to xOpen() includes all bits set in
92843 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
92844 ** or [sqlite3_open16()] is used, then flags includes at least
92845 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END}
92846 ** If xOpen() opens a file read-only then it sets *pOutFlags to
92847 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be
92848 ** set.
92849 ** 
92850 ** {F11143} SQLite will also add one of the following flags to the xOpen()
92851 ** call, depending on the object being opened:
92852 ** 
92853 ** <ul>
92854 ** <li>  [SQLITE_OPEN_MAIN_DB]
92855 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
92856 ** <li>  [SQLITE_OPEN_TEMP_DB]
92857 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
92858 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
92859 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
92860 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
92861 ** </ul> {END}
92862 **
92863 ** The file I/O implementation can use the object type flags to
92864 ** changes the way it deals with files.  For example, an application
92865 ** that does not care about crash recovery or rollback, might make
92866 ** the open of a journal file a no-op.  Writes to this journal are
92867 ** also a no-op.  Any attempt to read the journal return SQLITE_IOERR.
92868 ** Or the implementation might recognize the a database file will
92869 ** be doing page-aligned sector reads and writes in a random order
92870 ** and set up its I/O subsystem accordingly.
92871 ** 
92872 ** {F11144} SQLite might also add one of the following flags to the xOpen
92873 ** method:
92874 ** 
92875 ** <ul>
92876 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
92877 ** <li> [SQLITE_OPEN_EXCLUSIVE]
92878 ** </ul>
92879 ** 
92880 ** {F11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
92881 ** deleted when it is closed.  {F11146} The [SQLITE_OPEN_DELETEONCLOSE]
92882 ** will be set for TEMP  databases, journals and for subjournals. 
92883 ** {F11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened
92884 ** for exclusive access.  This flag is set for all files except
92885 ** for the main database file. {END}
92886 ** 
92887 ** {F11148} At least szOsFile bytes of memory is allocated by SQLite 
92888 ** to hold the  [sqlite3_file] structure passed as the third 
92889 ** argument to xOpen.  {END}  The xOpen method does not have to
92890 ** allocate the structure; it should just fill it in.
92891 ** 
92892 ** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] 
92893 ** to test for the existance of a file,
92894 ** or [SQLITE_ACCESS_READWRITE] to test to see
92895 ** if a file is readable and writable, or [SQLITE_ACCESS_READ]
92896 ** to test to see if a file is at least readable.  {END} The file can be a 
92897 ** directory.
92898 ** 
92899 ** {F11150} SQLite will always allocate at least mxPathname+1 byte for
92900 ** the output buffers for xGetTempname and xFullPathname. {F11151} The exact
92901 ** size of the output buffer is also passed as a parameter to both 
92902 ** methods. {END} If the output buffer is not large enough, SQLITE_CANTOPEN
92903 ** should be returned. As this is handled as a fatal error by SQLite,
92904 ** vfs implementations should endeavor to prevent this by setting 
92905 ** mxPathname to a sufficiently large value.
92906 ** 
92907 ** The xRandomness(), xSleep(), and xCurrentTime() interfaces
92908 ** are not strictly a part of the filesystem, but they are
92909 ** included in the VFS structure for completeness.
92910 ** The xRandomness() function attempts to return nBytes bytes
92911 ** of good-quality randomness into zOut.  The return value is
92912 ** the actual number of bytes of randomness obtained.  The
92913 ** xSleep() method cause the calling thread to sleep for at
92914 ** least the number of microseconds given.  The xCurrentTime()
92915 ** method returns a Julian Day Number for the current date and
92916 ** time.
92917 */
92918 typedef struct sqlite3_vfs sqlite3_vfs;
92919 struct sqlite3_vfs {
92920   int iVersion;            /* Structure version number */
92921   int szOsFile;            /* Size of subclassed sqlite3_file */
92922   int mxPathname;          /* Maximum file pathname length */
92923   sqlite3_vfs *pNext;      /* Next registered VFS */
92924   const char *zName;       /* Name of this virtual file system */
92925   void *pAppData;          /* Pointer to application-specific data */
92926   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
92927                int flags, int *pOutFlags);
92928   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
92929   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags);
92930   int (*xGetTempname)(sqlite3_vfs*, int nOut, char *zOut);
92931   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
92932   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
92933   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
92934   void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol);
92935   void (*xDlClose)(sqlite3_vfs*, void*);
92936   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
92937   int (*xSleep)(sqlite3_vfs*, int microseconds);
92938   int (*xCurrentTime)(sqlite3_vfs*, double*);
92939   /* New fields may be appended in figure versions.  The iVersion
92940   ** value will increment whenever this happens. */
92941 };
92942
92943 /*
92944 ** CAPI3REF: Flags for the xAccess VFS method {F11190}
92945 **
92946 ** {F11191} These integer constants can be used as the third parameter to
92947 ** the xAccess method of an [sqlite3_vfs] object. {END}  They determine
92948 ** the kind of what kind of permissions the xAccess method is
92949 ** looking for.  {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method
92950 ** simply checks to see if the file exists. {F11193} With
92951 ** SQLITE_ACCESS_READWRITE, the xAccess method checks to see
92952 ** if the file is both readable and writable.  {F11194} With
92953 ** SQLITE_ACCESS_READ the xAccess method
92954 ** checks to see if the file is readable.
92955 */
92956 #define SQLITE_ACCESS_EXISTS    0
92957 #define SQLITE_ACCESS_READWRITE 1
92958 #define SQLITE_ACCESS_READ      2
92959
92960 /*
92961 ** CAPI3REF: Enable Or Disable Extended Result Codes {F12200}
92962 **
92963 ** {F12201} The sqlite3_extended_result_codes() routine enables or disables the
92964 ** [SQLITE_IOERR_READ | extended result codes] feature on a database
92965 ** connection if its 2nd parameter is
92966 ** non-zero or zero, respectively. {F12202}
92967 ** By default, SQLite API routines return one of only 26 integer
92968 ** [SQLITE_OK | result codes].  {F12203} When extended result codes
92969 ** are enabled by this routine, the repetoire of result codes can be
92970 ** much larger and can (hopefully) provide more detailed information
92971 ** about the cause of an error.
92972 **
92973 ** {F12204} The second argument is a boolean value that turns extended result
92974 ** codes on and off. {F12205} Extended result codes are off by default for
92975 ** backwards compatibility with older versions of SQLite.
92976 */
92977 int sqlite3_extended_result_codes(sqlite3*, int onoff);
92978
92979 /*
92980 ** CAPI3REF: Last Insert Rowid {F12220}
92981 **
92982 ** {F12221} Each entry in an SQLite table has a unique 64-bit signed
92983 ** integer key called the "rowid".  {F12222} The rowid is always available
92984 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
92985 ** names are not also used by explicitly declared columns. {F12223} If
92986 ** the table has a column of type INTEGER PRIMARY KEY then that column
92987 ** is another an alias for the rowid.
92988 **
92989 ** {F12224} This routine returns the rowid of the most recent
92990 ** successful INSERT into the database from the database connection
92991 ** shown in the first argument.  {F12225} If no successful inserts
92992 ** have ever occurred on this database connection, zero is returned.
92993 **
92994 ** {F12226} If an INSERT occurs within a trigger, then the rowid of the
92995 ** inserted row is returned by this routine as long as the trigger
92996 ** is running.  {F12227} But once the trigger terminates, the value returned
92997 ** by this routine reverts to the last value inserted before the
92998 ** trigger fired.
92999 **
93000 ** {F12228} An INSERT that fails due to a constraint violation is not a
93001 ** successful insert and does not change the value returned by this
93002 ** routine.  {F12229} Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
93003 ** and INSERT OR ABORT make no changes to the return value of this
93004 ** routine when their insertion fails.  {F12231} When INSERT OR REPLACE 
93005 ** encounters a constraint violation, it does not fail.  The
93006 ** INSERT continues to completion after deleting rows that caused
93007 ** the constraint problem so INSERT OR REPLACE will always change
93008 ** the return value of this interface. 
93009 **
93010 ** {UF12232} If another thread does a new insert on the same database connection
93011 ** while this routine is running and thus changes the last insert rowid,
93012 ** then the return value of this routine is undefined.
93013 */
93014 sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
93015
93016 /*
93017 ** CAPI3REF: Count The Number Of Rows Modified {F12240}
93018 **
93019 ** {F12241} This function returns the number of database rows that were changed
93020 ** or inserted or deleted by the most recently completed SQL statement
93021 ** on the connection specified by the first parameter. {F12242} Only
93022 ** changes that are directly specified by the INSERT, UPDATE, or
93023 ** DELETE statement are counted.  Auxiliary changes caused by
93024 ** triggers are not counted. {F12243} Use the [sqlite3_total_changes()] function
93025 ** to find the total number of changes including changes caused by triggers.
93026 **
93027 ** {F12244} Within the body of a trigger, the sqlite3_changes() interface
93028 ** can be called to find the number of
93029 ** changes in the most recently completed INSERT, UPDATE, or DELETE
93030 ** statement within the body of the same trigger.
93031 **
93032 ** {F12245} All changes are counted, even if they are later undone by a
93033 ** ROLLBACK or ABORT.  {F12246} Except, changes associated with creating and
93034 ** dropping tables are not counted.
93035 **
93036 ** {F12247} If a callback invokes [sqlite3_exec()] or [sqlite3_step()]
93037 ** recursively, then the changes in the inner, recursive call are
93038 ** counted together with the changes in the outer call.
93039 **
93040 ** {F12248} SQLite implements the command "DELETE FROM table" without
93041 ** a WHERE clause by dropping and recreating the table.  (This is much
93042 ** faster than going through and deleting individual elements from the
93043 ** table.)  Because of this optimization, the change count for 
93044 ** "DELETE FROM table" will be zero regardless of the number of elements
93045 ** that were originally in the table. {F12251} To get an accurate count
93046 ** of the number of rows deleted, use
93047 ** "DELETE FROM table WHERE 1" instead.
93048 **
93049 ** {UF12252} If another thread makes changes on the same database connection
93050 ** while this routine is running then the return value of this routine
93051 ** is undefined.
93052 */
93053 int sqlite3_changes(sqlite3*);
93054
93055 /*
93056 ** CAPI3REF: Total Number Of Rows Modified {F12260}
93057 ***
93058 ** {F12261} This function returns the number of database rows that have been
93059 ** modified by INSERT, UPDATE or DELETE statements since the database handle
93060 ** was opened. {F12262} The count includes UPDATE, INSERT and DELETE 
93061 ** statements executed as part of trigger programs.  {F12263} All changes
93062 ** are counted as soon as the statement that makes them is completed 
93063 ** (when the statement handle is passed to [sqlite3_reset()] or 
93064 ** [sqlite3_finalize()]). {END}
93065 **
93066 ** See also the [sqlite3_change()] interface.
93067 **
93068 ** {F12265} SQLite implements the command "DELETE FROM table" without
93069 ** a WHERE clause by dropping and recreating the table.  (This is much
93070 ** faster than going
93071 ** through and deleting individual elements form the table.)  Because of
93072 ** this optimization, the change count for "DELETE FROM table" will be
93073 ** zero regardless of the number of elements that were originally in the
93074 ** table. To get an accurate count of the number of rows deleted, use
93075 ** "DELETE FROM table WHERE 1" instead.
93076 **
93077 ** {U12264} If another thread makes changes on the same database connection
93078 ** while this routine is running then the return value of this routine
93079 ** is undefined. {END}
93080 */
93081 int sqlite3_total_changes(sqlite3*);
93082
93083 /*
93084 ** CAPI3REF: Interrupt A Long-Running Query {F12270}
93085 **
93086 ** {F12271} This function causes any pending database operation to abort and
93087 ** return at its earliest opportunity. {END} This routine is typically
93088 ** called in response to a user action such as pressing "Cancel"
93089 ** or Ctrl-C where the user wants a long query operation to halt
93090 ** immediately.
93091 **
93092 ** {F12272} It is safe to call this routine from a thread different from the
93093 ** thread that is currently running the database operation. {U12273} But it
93094 ** is not safe to call this routine with a database connection that
93095 ** is closed or might close before sqlite3_interrupt() returns.
93096 **
93097 ** If an SQL is very nearly finished at the time when sqlite3_interrupt()
93098 ** is called, then it might not have an opportunity to be interrupted.
93099 ** It might continue to completion.
93100 ** {F12274} The SQL operation that is interrupted will return
93101 ** [SQLITE_INTERRUPT].  {F12275} If the interrupted SQL operation is an
93102 ** INSERT, UPDATE, or DELETE that is inside an explicit transaction, 
93103 ** then the entire transaction will be rolled back automatically.
93104 ** {F12276} A call to sqlite3_interrupt() has no effect on SQL statements
93105 ** that are started after sqlite3_interrupt() returns.
93106 */
93107 void sqlite3_interrupt(sqlite3*);
93108
93109 /*
93110 ** CAPI3REF: Determine If An SQL Statement Is Complete {F10510}
93111 **
93112 ** These routines are useful for command-line input to determine if the
93113 ** currently entered text seems to form complete a SQL statement or
93114 ** if additional input is needed before sending the text into
93115 ** SQLite for parsing.  These routines return true if the input string
93116 ** appears to be a complete SQL statement.  A statement is judged to be
93117 ** complete if it ends with a semicolon and is not a fragment of a
93118 ** CREATE TRIGGER statement.  These routines do not parse the SQL and
93119 ** so will not detect syntactically incorrect SQL.
93120 **
93121 ** {F10511} These functions return true if the given input string 
93122 ** ends with a semicolon optionally followed by whitespace or
93123 ** comments. {F10512} For sqlite3_complete(),
93124 ** the parameter must be a zero-terminated UTF-8 string. {F10513} For
93125 ** sqlite3_complete16(), a zero-terminated machine byte order UTF-16 string
93126 ** is required.  {F10514} These routines return false if the terminal
93127 ** semicolon is within a comment, a string literal or a quoted identifier
93128 ** (in other words if the final semicolon is not really a separate token
93129 ** but part of a larger token) or if the final semicolon is
93130 ** in between the BEGIN and END keywords of a CREATE TRIGGER statement.
93131 ** {END}
93132 */
93133 int sqlite3_complete(const char *sql);
93134 int sqlite3_complete16(const void *sql);
93135
93136 /*
93137 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310}
93138 **
93139 ** {F12311} This routine identifies a callback function that might be
93140 ** invoked whenever an attempt is made to open a database table 
93141 ** that another thread or process has locked.
93142 ** {F12312} If the busy callback is NULL, then [SQLITE_BUSY]
93143 ** or [SQLITE_IOERR_BLOCKED]
93144 ** is returned immediately upon encountering the lock.
93145 ** {F12313} If the busy callback is not NULL, then the
93146 ** callback will be invoked with two arguments.  {F12314} The
93147 ** first argument to the handler is a copy of the void* pointer which
93148 ** is the third argument to this routine.  {F12315} The second argument to
93149 ** the handler is the number of times that the busy handler has
93150 ** been invoked for this locking event.  {F12316} If the
93151 ** busy callback returns 0, then no additional attempts are made to
93152 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
93153 ** {F12317} If the callback returns non-zero, then another attempt
93154 ** is made to open the database for reading and the cycle repeats.
93155 **
93156 ** The presence of a busy handler does not guarantee that
93157 ** it will be invoked when there is lock contention. {F12319}
93158 ** If SQLite determines that invoking the busy handler could result in
93159 ** a deadlock, it will go ahead and return [SQLITE_BUSY] or
93160 ** [SQLITE_IOERR_BLOCKED] instead of invoking the
93161 ** busy handler. {END}
93162 ** Consider a scenario where one process is holding a read lock that
93163 ** it is trying to promote to a reserved lock and
93164 ** a second process is holding a reserved lock that it is trying
93165 ** to promote to an exclusive lock.  The first process cannot proceed
93166 ** because it is blocked by the second and the second process cannot
93167 ** proceed because it is blocked by the first.  If both processes
93168 ** invoke the busy handlers, neither will make any progress.  Therefore,
93169 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
93170 ** will induce the first process to release its read lock and allow
93171 ** the second process to proceed.
93172 **
93173 ** {F12321} The default busy callback is NULL. {END}
93174 **
93175 ** {F12322} The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
93176 ** when SQLite is in the middle of a large transaction where all the
93177 ** changes will not fit into the in-memory cache.  {F12323} SQLite will
93178 ** already hold a RESERVED lock on the database file, but it needs
93179 ** to promote this lock to EXCLUSIVE so that it can spill cache
93180 ** pages into the database file without harm to concurrent
93181 ** readers.  {F12324} If it is unable to promote the lock, then the in-memory
93182 ** cache will be left in an inconsistent state and so the error
93183 ** code is promoted from the relatively benign [SQLITE_BUSY] to
93184 ** the more severe [SQLITE_IOERR_BLOCKED].  {F12325} This error code promotion
93185 ** forces an automatic rollback of the changes. {END} See the
93186 ** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError">
93187 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
93188 ** this is important.
93189 **      
93190 ** {F12326} Sqlite is re-entrant, so the busy handler may start a new
93191 ** query. {END} (It is not clear why anyone would every want to do this,
93192 ** but it is allowed, in theory.) {U12327} But the busy handler may not
93193 ** close the database.  Closing the database from a busy handler will delete 
93194 ** data structures out from under the executing query and will 
93195 ** probably result in a segmentation fault or other runtime error. {END}
93196 **
93197 ** {F12328} There can only be a single busy handler defined for each database
93198 ** connection.  Setting a new busy handler clears any previous one. 
93199 ** {F12329} Note that calling [sqlite3_busy_timeout()] will also set or clear
93200 ** the busy handler.
93201 **
93202 ** {F12331} When operating in [sqlite3_enable_shared_cache | shared cache mode],
93203 ** only a single busy handler can be defined for each database file.
93204 ** So if two database connections share a single cache, then changing
93205 ** the busy handler on one connection will also change the busy
93206 ** handler in the other connection.  {F12332} The busy handler is invoked
93207 ** in the thread that was running when the lock contention occurs.
93208 */
93209 int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
93210
93211 /*
93212 ** CAPI3REF: Set A Busy Timeout {F12340}
93213 **
93214 ** {F12341} This routine sets a [sqlite3_busy_handler | busy handler]
93215 ** that sleeps for a while when a
93216 ** table is locked.  {F12342} The handler will sleep multiple times until 
93217 ** at least "ms" milliseconds of sleeping have been done. {F12343} After
93218 ** "ms" milliseconds of sleeping, the handler returns 0 which
93219 ** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
93220 **
93221 ** {F12344} Calling this routine with an argument less than or equal to zero
93222 ** turns off all busy handlers.
93223 **
93224 ** {F12345} There can only be a single busy handler for a particular database
93225 ** connection.  If another busy handler was defined  
93226 ** (using [sqlite3_busy_handler()]) prior to calling
93227 ** this routine, that other busy handler is cleared.
93228 */
93229 int sqlite3_busy_timeout(sqlite3*, int ms);
93230
93231 /*
93232 ** CAPI3REF: Convenience Routines For Running Queries {F12370}
93233 **
93234 ** This next routine is a convenience wrapper around [sqlite3_exec()].
93235 ** {F12371} Instead of invoking a user-supplied callback for each row of the
93236 ** result, this routine remembers each row of the result in memory
93237 ** obtained from [sqlite3_malloc()], then returns all of the result after the
93238 ** query has finished. {F12372}
93239 **
93240 ** As an example, suppose the query result where this table:
93241 **
93242 ** <blockquote><pre>
93243 **        Name        | Age
93244 **        -----------------------
93245 **        Alice       | 43
93246 **        Bob         | 28
93247 **        Cindy       | 21
93248 ** </pre></blockquote>
93249 **
93250 ** If the 3rd argument were &azResult then after the function returns
93251 ** azResult will contain the following data:
93252 **
93253 ** <blockquote><pre>
93254 **        azResult&#91;0] = "Name";
93255 **        azResult&#91;1] = "Age";
93256 **        azResult&#91;2] = "Alice";
93257 **        azResult&#91;3] = "43";
93258 **        azResult&#91;4] = "Bob";
93259 **        azResult&#91;5] = "28";
93260 **        azResult&#91;6] = "Cindy";
93261 **        azResult&#91;7] = "21";
93262 ** </pre></blockquote>
93263 **
93264 ** Notice that there is an extra row of data containing the column
93265 ** headers.  But the *nrow return value is still 3.  *ncolumn is
93266 ** set to 2.  In general, the number of values inserted into azResult
93267 ** will be ((*nrow) + 1)*(*ncolumn).
93268 **
93269 ** {U12374} After the calling function has finished using the result, it should 
93270 ** pass the result data pointer to sqlite3_free_table() in order to 
93271 ** release the memory that was malloc-ed.  Because of the way the 
93272 ** [sqlite3_malloc()] happens, the calling function must not try to call 
93273 ** [sqlite3_free()] directly.  Only [sqlite3_free_table()] is able to release 
93274 ** the memory properly and safely. {END}
93275 **
93276 ** {F12373} The return value of this routine is the same as
93277 ** from [sqlite3_exec()].
93278 */
93279 int sqlite3_get_table(
93280   sqlite3*,              /* An open database */
93281   const char *sql,       /* SQL to be executed */
93282   char ***resultp,       /* Result written to a char *[]  that this points to */
93283   int *nrow,             /* Number of result rows written here */
93284   int *ncolumn,          /* Number of result columns written here */
93285   char **errmsg          /* Error msg written here */
93286 );
93287 void sqlite3_free_table(char **result);
93288
93289 /*
93290 ** CAPI3REF: Formatted String Printing Functions {F17400}
93291 **
93292 ** These routines are workalikes of the "printf()" family of functions
93293 ** from the standard C library.
93294 **
93295 ** {F17401} The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
93296 ** results into memory obtained from [sqlite3_malloc()].
93297 ** {U17402} The strings returned by these two routines should be
93298 ** released by [sqlite3_free()]. {F17403}  Both routines return a
93299 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
93300 ** memory to hold the resulting string.
93301 **
93302 ** {F17404} In sqlite3_snprintf() routine is similar to "snprintf()" from
93303 ** the standard C library.  The result is written into the
93304 ** buffer supplied as the second parameter whose size is given by
93305 ** the first parameter. {END} Note that the order of the
93306 ** first two parameters is reversed from snprintf().  This is an
93307 ** historical accident that cannot be fixed without breaking
93308 ** backwards compatibility.  {F17405} Note also that sqlite3_snprintf()
93309 ** returns a pointer to its buffer instead of the number of
93310 ** characters actually written into the buffer. {END} We admit that
93311 ** the number of characters written would be a more useful return
93312 ** value but we cannot change the implementation of sqlite3_snprintf()
93313 ** now without breaking compatibility.
93314 **
93315 ** {F17406} As long as the buffer size is greater than zero, sqlite3_snprintf()
93316 ** guarantees that the buffer is always zero-terminated. {F17407} The first
93317 ** parameter "n" is the total size of the buffer, including space for
93318 ** the zero terminator.  {END} So the longest string that can be completely
93319 ** written will be n-1 characters.
93320 **
93321 ** These routines all implement some additional formatting
93322 ** options that are useful for constructing SQL statements.
93323 ** All of the usual printf formatting options apply.  In addition, there
93324 ** is are "%q", "%Q", and "%z" options.
93325 **
93326 ** {F17410} The %q option works like %s in that it substitutes a null-terminated
93327 ** string from the argument list.  But %q also doubles every '\'' character.
93328 ** %q is designed for use inside a string literal. {END} By doubling each '\''
93329 ** character it escapes that character and allows it to be inserted into
93330 ** the string.
93331 **
93332 ** For example, so some string variable contains text as follows:
93333 **
93334 ** <blockquote><pre>
93335 **  char *zText = "It's a happy day!";
93336 ** </pre></blockquote>
93337 **
93338 ** One can use this text in an SQL statement as follows:
93339 **
93340 ** <blockquote><pre>
93341 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
93342 **  sqlite3_exec(db, zSQL, 0, 0, 0);
93343 **  sqlite3_free(zSQL);
93344 ** </pre></blockquote>
93345 **
93346 ** Because the %q format string is used, the '\'' character in zText
93347 ** is escaped and the SQL generated is as follows:
93348 **
93349 ** <blockquote><pre>
93350 **  INSERT INTO table1 VALUES('It''s a happy day!')
93351 ** </pre></blockquote>
93352 **
93353 ** This is correct.  Had we used %s instead of %q, the generated SQL
93354 ** would have looked like this:
93355 **
93356 ** <blockquote><pre>
93357 **  INSERT INTO table1 VALUES('It's a happy day!');
93358 ** </pre></blockquote>
93359 **
93360 ** This second example is an SQL syntax error.  As a general rule you
93361 ** should always use %q instead of %s when inserting text into a string 
93362 ** literal.
93363 **
93364 ** {F17411} The %Q option works like %q except it also adds single quotes around
93365 ** the outside of the total string.  Or if the parameter in the argument
93366 ** list is a NULL pointer, %Q substitutes the text "NULL" (without single
93367 ** quotes) in place of the %Q option. {END}  So, for example, one could say:
93368 **
93369 ** <blockquote><pre>
93370 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
93371 **  sqlite3_exec(db, zSQL, 0, 0, 0);
93372 **  sqlite3_free(zSQL);
93373 ** </pre></blockquote>
93374 **
93375 ** The code above will render a correct SQL statement in the zSQL
93376 ** variable even if the zText variable is a NULL pointer.
93377 **
93378 ** {F17412} The "%z" formatting option works exactly like "%s" with the
93379 ** addition that after the string has been read and copied into
93380 ** the result, [sqlite3_free()] is called on the input string. {END}
93381 */
93382 char *sqlite3_mprintf(const char*,...);
93383 char *sqlite3_vmprintf(const char*, va_list);
93384 char *sqlite3_snprintf(int,char*,const char*, ...);
93385
93386 /*
93387 ** CAPI3REF: Memory Allocation Subsystem {F17300}
93388 **
93389 ** {F17301} The SQLite core  uses these three routines for all of its own
93390 ** internal memory allocation needs. {END}  "Core" in the previous sentence
93391 ** does not include operating-system specific VFS implementation.  The
93392 ** windows VFS uses native malloc and free for some operations.
93393 **
93394 ** {F17302} The sqlite3_malloc() routine returns a pointer to a block
93395 ** of memory at least N bytes in length, where N is the parameter.
93396 ** {F17303} If sqlite3_malloc() is unable to obtain sufficient free
93397 ** memory, it returns a NULL pointer.  {F17304} If the parameter N to
93398 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
93399 ** a NULL pointer.
93400 **
93401 ** {F17305} Calling sqlite3_free() with a pointer previously returned
93402 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
93403 ** that it might be reused.  {F17306} The sqlite3_free() routine is
93404 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
93405 ** to sqlite3_free() is harmless.  {U17307} After being freed, memory
93406 ** should neither be read nor written.  Even reading previously freed
93407 ** memory might result in a segmentation fault or other severe error.
93408 ** {U17309} Memory corruption, a segmentation fault, or other severe error
93409 ** might result if sqlite3_free() is called with a non-NULL pointer that
93410 ** was not obtained from sqlite3_malloc() or sqlite3_free().
93411 **
93412 ** {F17310} The sqlite3_realloc() interface attempts to resize a
93413 ** prior memory allocation to be at least N bytes, where N is the
93414 ** second parameter.  The memory allocation to be resized is the first
93415 ** parameter.  {F17311} If the first parameter to sqlite3_realloc()
93416 ** is a NULL pointer then its behavior is identical to calling
93417 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
93418 ** {F17312} If the second parameter to sqlite3_realloc() is zero or
93419 ** negative then the behavior is exactly the same as calling
93420 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
93421 ** {F17313} Sqlite3_realloc() returns a pointer to a memory allocation
93422 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
93423 ** {F17314} If M is the size of the prior allocation, then min(N,M) bytes
93424 ** of the prior allocation are copied into the beginning of buffer returned
93425 ** by sqlite3_realloc() and the prior allocation is freed.
93426 ** {F17315} If sqlite3_realloc() returns NULL, then the prior allocation
93427 ** is not freed.
93428 **
93429 ** {F17316} The memory returned by sqlite3_malloc() and sqlite3_realloc()
93430 ** is always aligned to at least an 8 byte boundary. {END}
93431 **
93432 ** {F17381} The default implementation
93433 ** of the memory allocation subsystem uses the malloc(), realloc()
93434 ** and free() provided by the standard C library. {F17382} However, if 
93435 ** SQLite is compiled with the following C preprocessor macro
93436 **
93437 ** <blockquote> SQLITE_MEMORY_SIZE=<i>NNN</i> </blockquote>
93438 **
93439 ** where <i>NNN</i> is an integer, then SQLite create a static
93440 ** array of at least <i>NNN</i> bytes in size and use that array
93441 ** for all of its dynamic memory allocation needs. {END}  Additional
93442 ** memory allocator options may be added in future releases.
93443 **
93444 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
93445 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
93446 ** implementation of these routines to be omitted.  That capability
93447 ** is no longer provided.  Only built-in memory allocators can be
93448 ** used.
93449 **
93450 ** The windows OS interface layer calls
93451 ** the system malloc() and free() directly when converting
93452 ** filenames between the UTF-8 encoding used by SQLite
93453 ** and whatever filename encoding is used by the particular windows
93454 ** installation.  Memory allocation errors are detected, but
93455 ** they are reported back as [SQLITE_CANTOPEN] or
93456 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
93457 */
93458 void *sqlite3_malloc(int);
93459 void *sqlite3_realloc(void*, int);
93460 void sqlite3_free(void*);
93461
93462 /*
93463 ** CAPI3REF: Memory Allocator Statistics {F17370}
93464 **
93465 ** In addition to the basic three allocation routines 
93466 ** [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()],
93467 ** the memory allocation subsystem included with the SQLite
93468 ** sources provides the interfaces shown here.
93469 **
93470 ** {F17371} The sqlite3_memory_used() routine returns the
93471 ** number of bytes of memory currently outstanding (malloced but not freed).
93472 ** {F17372} The value returned by sqlite3_memory_used() includes
93473 ** any overhead added by SQLite, but not overhead added by the
93474 ** library malloc() that backs the sqlite3_malloc() implementation.
93475 ** {F17373} The sqlite3_memory_highwater() routines returns the
93476 ** maximum number of bytes that have been outstanding at any time
93477 ** since the highwater mark was last reset.
93478 ** {F17374} The byte count returned by sqlite3_memory_highwater()
93479 ** uses the same byte counting rules as sqlite3_memory_used(). {END}
93480 ** In other words, overhead added internally by SQLite is counted,
93481 ** but overhead from the underlying system malloc is not.
93482 ** {F17375} If the parameter to sqlite3_memory_highwater() is true,
93483 ** then the highwater mark is reset to the current value of
93484 ** sqlite3_memory_used() and the prior highwater mark (before the
93485 ** reset) is returned.  {F17376}  If the parameter to 
93486 ** sqlite3_memory_highwater() is zero, then the highwater mark is
93487 ** unchanged.
93488 */
93489 sqlite3_int64 sqlite3_memory_used(void);
93490 sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
93491
93492 /*
93493 ** CAPI3REF: Compile-Time Authorization Callbacks {F12500}
93494 **
93495 ** {F12501} This routine registers a authorizer callback with a particular
93496 ** database connection, supplied in the first argument. {F12502}
93497 ** The authorizer callback is invoked as SQL statements are being compiled
93498 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
93499 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  {F12503} At various
93500 ** points during the compilation process, as logic is being created
93501 ** to perform various actions, the authorizer callback is invoked to
93502 ** see if those actions are allowed.  The authorizer callback should
93503 ** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the
93504 ** specific action but allow the SQL statement to continue to be
93505 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
93506 ** rejected with an error.  {F12504} If the authorizer callback returns
93507 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
93508 ** then [sqlite3_prepare_v2()] or equivalent call that triggered
93509 ** the authorizer shall
93510 ** fail with an SQLITE_ERROR error code and an appropriate error message. {END}
93511 **
93512 ** When the callback returns [SQLITE_OK], that means the operation
93513 ** requested is ok.  {F12505} When the callback returns [SQLITE_DENY], the
93514 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
93515 ** authorizer shall fail
93516 ** with an SQLITE_ERROR error code and an error message explaining that
93517 ** access is denied. {F12506} If the authorizer code (the 2nd parameter
93518 ** to the authorizer callback is anything other than [SQLITE_READ], then
93519 ** a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. 
93520 ** If the authorizer code is [SQLITE_READ] and the callback returns
93521 ** [SQLITE_IGNORE] then the prepared statement is constructed to
93522 ** insert a NULL value in place of the table column that would have
93523 ** been read if [SQLITE_OK] had been returned. {END}
93524 **
93525 ** {F12510} The first parameter to the authorizer callback is a copy of
93526 ** the third parameter to the sqlite3_set_authorizer() interface.
93527 ** {F12511} The second parameter to the callback is an integer 
93528 ** [SQLITE_COPY | action code] that specifies the particular action
93529 ** to be authorized. {END} The available action codes are
93530 ** [SQLITE_COPY | documented separately].  {F12512} The third through sixth
93531 ** parameters to the callback are zero-terminated strings that contain 
93532 ** additional details about the action to be authorized. {END}
93533 **
93534 ** An authorizer is used when preparing SQL statements from an untrusted
93535 ** source, to ensure that the SQL statements do not try to access data
93536 ** that they are not allowed to see, or that they do not try to
93537 ** execute malicious statements that damage the database.  For
93538 ** example, an application may allow a user to enter arbitrary
93539 ** SQL queries for evaluation by a database.  But the application does
93540 ** not want the user to be able to make arbitrary changes to the
93541 ** database.  An authorizer could then be put in place while the
93542 ** user-entered SQL is being prepared that disallows everything
93543 ** except SELECT statements.  
93544 **
93545 ** {F12520} Only a single authorizer can be in place on a database connection
93546 ** at a time.  Each call to sqlite3_set_authorizer overrides the
93547 ** previous call. {F12521}  A NULL authorizer means that no authorization
93548 ** callback is invoked.  {F12522} The default authorizer is NULL. {END}
93549 **
93550 ** Note that the authorizer callback is invoked only during 
93551 ** [sqlite3_prepare()] or its variants.  {F12523} Authorization is not
93552 ** performed during statement evaluation in [sqlite3_step()]. {END}
93553 */
93554 int sqlite3_set_authorizer(
93555   sqlite3*,
93556   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
93557   void *pUserData
93558 );
93559
93560 /*
93561 ** CAPI3REF: Authorizer Return Codes {F12590}
93562 **
93563 ** The [sqlite3_set_authorizer | authorizer callback function] must
93564 ** return either [SQLITE_OK] or one of these two constants in order
93565 ** to signal SQLite whether or not the action is permitted.  See the
93566 ** [sqlite3_set_authorizer | authorizer documentation] for additional
93567 ** information.
93568 */
93569 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
93570 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
93571
93572 /*
93573 ** CAPI3REF: Authorizer Action Codes {F12550}
93574 **
93575 ** The [sqlite3_set_authorizer()] interface registers a callback function
93576 ** that is invoked to authorizer certain SQL statement actions.  {F12551} The
93577 ** second parameter to the callback is an integer code that specifies
93578 ** what action is being authorized.  These are the integer action codes that
93579 ** the authorizer callback may be passed. {END}
93580 **
93581 ** These action code values signify what kind of operation is to be 
93582 ** authorized.  {F12552} The 3rd and 4th parameters to the authorization
93583 ** callback function will be parameters or NULL depending on which of these
93584 ** codes is used as the second parameter. {F12553} The 5th parameter to the
93585 ** authorizer callback is the name of the database ("main", "temp", 
93586 ** etc.) if applicable. {F12554} The 6th parameter to the authorizer callback
93587 ** is the name of the inner-most trigger or view that is responsible for
93588 ** the access attempt or NULL if this access attempt is directly from 
93589 ** top-level SQL code.
93590 */
93591 /******************************************* 3rd ************ 4th ***********/
93592 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
93593 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
93594 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
93595 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
93596 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
93597 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
93598 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
93599 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
93600 #define SQLITE_DELETE                9   /* Table Name      NULL            */
93601 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
93602 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
93603 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
93604 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
93605 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
93606 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
93607 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
93608 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
93609 #define SQLITE_INSERT               18   /* Table Name      NULL            */
93610 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
93611 #define SQLITE_READ                 20   /* Table Name      Column Name     */
93612 #define SQLITE_SELECT               21   /* NULL            NULL            */
93613 #define SQLITE_TRANSACTION          22   /* NULL            NULL            */
93614 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
93615 #define SQLITE_ATTACH               24   /* Filename        NULL            */
93616 #define SQLITE_DETACH               25   /* Database Name   NULL            */
93617 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
93618 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
93619 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
93620 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
93621 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
93622 #define SQLITE_FUNCTION             31   /* Function Name   NULL            */
93623 #define SQLITE_COPY                  0   /* No longer used */
93624
93625 /*
93626 ** CAPI3REF: Tracing And Profiling Functions {F12280}
93627 **
93628 ** These routines register callback functions that can be used for
93629 ** tracing and profiling the execution of SQL statements.
93630 **
93631 ** {F12281} The callback function registered by sqlite3_trace() is invoked
93632 ** at the first [sqlite3_step()] for the evaluation of an SQL statement.
93633 ** {F12282} Only a single trace callback can be registered at a time.
93634 ** Each call to sqlite3_trace() overrides the previous.  {F12283} A
93635 ** NULL callback for sqlite3_trace() disables tracing.  {F12284} The
93636 ** first argument to the trace callback is a copy of the pointer which
93637 ** was the 3rd argument to sqlite3_trace.  {F12285} The second argument
93638 ** to the trace callback is a zero-terminated UTF8 string containing
93639 ** the original text of the SQL statement as it was passed into
93640 ** [sqlite3_prepare_v2()] or the equivalent. {END}  Note that the
93641 ** host parameter are not expanded in the SQL statement text.
93642 **
93643 ** {F12287} The callback function registered by sqlite3_profile() is invoked
93644 ** as each SQL statement finishes.  {F12288} The first parameter to the
93645 ** profile callback is a copy of the 3rd parameter to sqlite3_profile().
93646 ** {F12289} The second parameter to the profile callback is a
93647 ** zero-terminated UTF-8 string that contains the complete text of
93648 ** the SQL statement as it was processed by [sqlite3_prepare_v2()] or
93649 ** the equivalent.  {F12290} The third parameter to the profile 
93650 ** callback is an estimate of the number of nanoseconds of
93651 ** wall-clock time required to run the SQL statement from start
93652 ** to finish. {END}  
93653 **
93654 ** The sqlite3_profile() API is currently considered experimental and
93655 ** is subject to change.
93656 */
93657 void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
93658 void *sqlite3_profile(sqlite3*,
93659    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
93660
93661 /*
93662 ** CAPI3REF: Query Progress Callbacks {F12910}
93663 **
93664 ** {F12911} This routine configures a callback function - the
93665 ** progress callback - that is invoked periodically during long
93666 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
93667 ** [sqlite3_get_table()]. {END}  An example use for this 
93668 ** interface is to keep a GUI updated during a large query.
93669 **
93670 ** {F12912} The progress callback is invoked once for every N virtual
93671 ** machine opcodes, where N is the second argument to this function.
93672 ** {F12913} The progress callback itself is identified by the third
93673 ** argument to this function. {F12914} The fourth argument to this
93674 ** function is a void pointer passed to the progress callback
93675 ** function each time it is invoked. {END}
93676 **
93677 ** {F12915} If a call to [sqlite3_exec()], [sqlite3_step()], or
93678 ** [sqlite3_get_table()] results in fewer than N opcodes being executed,
93679 ** then the progress callback is never invoked. {END}
93680 ** 
93681 ** {F12916} Only a single progress callback function may be registered for each
93682 ** open database connection.  Every call to sqlite3_progress_handler()
93683 ** overwrites the results of the previous call. {F12917}
93684 ** To remove the progress callback altogether, pass NULL as the third
93685 ** argument to this function. {END}
93686 **
93687 ** {F12918} If the progress callback returns a result other than 0, then
93688 ** the current query is immediately terminated and any database changes
93689 ** rolled back. {F12919}
93690 ** The containing [sqlite3_exec()], [sqlite3_step()], or
93691 ** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. {END}  This feature
93692 ** can be used, for example, to implement the "Cancel" button on a
93693 ** progress dialog box in a GUI.
93694 */
93695 void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
93696
93697 /*
93698 ** CAPI3REF: Opening A New Database Connection {F12700}
93699 **
93700 ** {F12701} These routines open an SQLite database file whose name
93701 ** is given by the filename argument.
93702 ** {F12702} The filename argument is interpreted as UTF-8
93703 ** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16
93704 ** in the native byte order for [sqlite3_open16()].
93705 ** {F12703} An [sqlite3*] handle is returned in *ppDb, even
93706 ** if an error occurs.  {F12723} (Exception: if SQLite is unable
93707 ** to allocate memory to hold the [sqlite3] object, a NULL will
93708 ** be written into *ppDb instead of a pointer to the [sqlite3] object.)
93709 ** {F12704} If the database is opened (and/or created)
93710 ** successfully, then [SQLITE_OK] is returned.  {F12705} Otherwise an
93711 ** error code is returned.  {F12706} The
93712 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()]  routines can be used to obtain
93713 ** an English language description of the error.
93714 **
93715 ** {F12707} The default encoding for the database will be UTF-8 if
93716 ** [sqlite3_open()] or [sqlite3_open_v2()] is called and
93717 ** UTF-16 in the native byte order if [sqlite3_open16()] is used.
93718 **
93719 ** {F12708} Whether or not an error occurs when it is opened, resources
93720 ** associated with the [sqlite3*] handle should be released by passing it
93721 ** to [sqlite3_close()] when it is no longer required.
93722 **
93723 ** {F12709} The [sqlite3_open_v2()] interface works like [sqlite3_open()] 
93724 ** except that it acccepts two additional parameters for additional control
93725 ** over the new database connection.  {F12710} The flags parameter can be
93726 ** one of:
93727 **
93728 ** <ol>
93729 ** <li>  [SQLITE_OPEN_READONLY]
93730 ** <li>  [SQLITE_OPEN_READWRITE]
93731 ** <li>  [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
93732 ** </ol>
93733 **
93734 ** {F12711} The first value opens the database read-only. 
93735 ** {F12712} If the database does not previously exist, an error is returned.
93736 ** {F12713} The second option opens
93737 ** the database for reading and writing if possible, or reading only if
93738 ** if the file is write protected.  {F12714} In either case the database
93739 ** must already exist or an error is returned.  {F12715} The third option
93740 ** opens the database for reading and writing and creates it if it does
93741 ** not already exist. {F12716}
93742 ** The third options is behavior that is always used for [sqlite3_open()]
93743 ** and [sqlite3_open16()].
93744 **
93745 ** {F12717} If the filename is ":memory:", then an private
93746 ** in-memory database is created for the connection. {F12718} This in-memory
93747 ** database will vanish when the database connection is closed. {END}  Future
93748 ** version of SQLite might make use of additional special filenames
93749 ** that begin with the ":" character.  It is recommended that 
93750 ** when a database filename really does begin with
93751 ** ":" that you prefix the filename with a pathname like "./" to
93752 ** avoid ambiguity.
93753 **
93754 ** {F12719} If the filename is an empty string, then a private temporary
93755 ** on-disk database will be created.  {F12720} This private database will be
93756 ** automatically deleted as soon as the database connection is closed.
93757 **
93758 ** {F12721} The fourth parameter to sqlite3_open_v2() is the name of the
93759 ** [sqlite3_vfs] object that defines the operating system 
93760 ** interface that the new database connection should use.  {F12722} If the
93761 ** fourth parameter is a NULL pointer then the default [sqlite3_vfs]
93762 ** object is used. {END}
93763 **
93764 ** <b>Note to windows users:</b>  The encoding used for the filename argument
93765 ** of [sqlite3_open()] and [sqlite3_open_v2()] must be UTF-8, not whatever
93766 ** codepage is currently defined.  Filenames containing international
93767 ** characters must be converted to UTF-8 prior to passing them into
93768 ** [sqlite3_open()] or [sqlite3_open_v2()].
93769 */
93770 int sqlite3_open(
93771   const char *filename,   /* Database filename (UTF-8) */
93772   sqlite3 **ppDb          /* OUT: SQLite db handle */
93773 );
93774 int sqlite3_open16(
93775   const void *filename,   /* Database filename (UTF-16) */
93776   sqlite3 **ppDb          /* OUT: SQLite db handle */
93777 );
93778 int sqlite3_open_v2(
93779   const char *filename,   /* Database filename (UTF-8) */
93780   sqlite3 **ppDb,         /* OUT: SQLite db handle */
93781   int flags,              /* Flags */
93782   const char *zVfs        /* Name of VFS module to use */
93783 );
93784
93785 /*
93786 ** CAPI3REF: Error Codes And Messages {F12800}
93787 **
93788 ** {F12801} The sqlite3_errcode() interface returns the numeric
93789 ** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code]
93790 ** for the most recent failed sqlite3_* API call associated
93791 ** with [sqlite3] handle 'db'. {U12802} If a prior API call failed but the
93792 ** most recent API call succeeded, the return value from sqlite3_errcode()
93793 ** is undefined. {END}
93794 **
93795 ** {F12803} The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
93796 ** text that describes the error, as either UTF8 or UTF16 respectively.
93797 ** {F12804} Memory to hold the error message string is managed internally.
93798 ** {U12805} The 
93799 ** string may be overwritten or deallocated by subsequent calls to SQLite
93800 ** interface functions. {END}
93801 **
93802 ** {F12806} Calls to many sqlite3_* functions set the error code and
93803 ** string returned by [sqlite3_errcode()], [sqlite3_errmsg()], and
93804 ** [sqlite3_errmsg16()] overwriting the previous values.  {F12807}
93805 ** Except, calls to [sqlite3_errcode()],
93806 ** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the
93807 ** results of future invocations.  {F12808} Calls to API routines that
93808 ** do not return an error code (example: [sqlite3_data_count()]) do not
93809 ** change the error code returned by this routine.  {F12809} Interfaces that
93810 ** are not associated with a specific database connection (examples:
93811 ** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change
93812 ** the return code. {END}
93813 **
93814 ** {F12810} Assuming no other intervening sqlite3_* API calls are made,
93815 ** the error code returned by this function is associated with the same
93816 ** error as the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()].
93817 */
93818 int sqlite3_errcode(sqlite3 *db);
93819 const char *sqlite3_errmsg(sqlite3*);
93820 const void *sqlite3_errmsg16(sqlite3*);
93821
93822 /*
93823 ** CAPI3REF: SQL Statement Object {F13000}
93824 **
93825 ** An instance of this object represent single SQL statements.  This
93826 ** object is variously known as a "prepared statement" or a 
93827 ** "compiled SQL statement" or simply as a "statement".
93828 ** 
93829 ** The life of a statement object goes something like this:
93830 **
93831 ** <ol>
93832 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
93833 **      function.
93834 ** <li> Bind values to host parameters using
93835 **      [sqlite3_bind_blob | sqlite3_bind_* interfaces].
93836 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
93837 ** <li> Reset the statement using [sqlite3_reset()] then go back
93838 **      to step 2.  Do this zero or more times.
93839 ** <li> Destroy the object using [sqlite3_finalize()].
93840 ** </ol>
93841 **
93842 ** Refer to documentation on individual methods above for additional
93843 ** information.
93844 */
93845 typedef struct sqlite3_stmt sqlite3_stmt;
93846
93847 /*
93848 ** CAPI3REF: Compiling An SQL Statement {F13010}
93849 **
93850 ** To execute an SQL query, it must first be compiled into a byte-code
93851 ** program using one of these routines. 
93852 **
93853 ** {F13011} The first argument "db" is an [sqlite3 | SQLite database handle] 
93854 ** obtained from a prior call to [sqlite3_open()], [sqlite3_open_v2()]
93855 ** or [sqlite3_open16()]. {F13012}
93856 ** The second argument "zSql" is the statement to be compiled, encoded
93857 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
93858 ** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2()
93859 ** use UTF-16. {END}
93860 **
93861 ** {F13013} If the nByte argument is less
93862 ** than zero, then zSql is read up to the first zero terminator.
93863 ** {F13014} If nByte is non-negative, then it is the maximum number of 
93864 ** bytes read from zSql.  When nByte is non-negative, the
93865 ** zSql string ends at either the first '\000' or '\u0000' character or 
93866 ** until the nByte-th byte, whichever comes first. {END}
93867 **
93868 ** {F13015} *pzTail is made to point to the first byte past the end of the
93869 ** first SQL statement in zSql.  These routines only compiles the first
93870 ** statement in zSql, so *pzTail is left pointing to what remains
93871 ** uncompiled. {END}
93872 **
93873 ** {F13016} *ppStmt is left pointing to a compiled 
93874 ** [sqlite3_stmt | SQL statement structure] that can be
93875 ** executed using [sqlite3_step()].  Or if there is an error, *ppStmt may be
93876 ** set to NULL.  {F13017} If the input text contains no SQL (if the input
93877 ** is and empty string or a comment) then *ppStmt is set to NULL.
93878 ** {U13018} The calling procedure is responsible for deleting the
93879 ** compiled SQL statement
93880 ** using [sqlite3_finalize()] after it has finished with it.
93881 **
93882 ** {F13019} On success, [SQLITE_OK] is returned.  Otherwise an 
93883 ** [SQLITE_ERROR | error code] is returned. {END}
93884 **
93885 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
93886 ** recommended for all new programs. The two older interfaces are retained
93887 ** for backwards compatibility, but their use is discouraged.
93888 ** {F13020} In the "v2" interfaces, the prepared statement
93889 ** that is returned (the [sqlite3_stmt] object) contains a copy of the 
93890 ** original SQL text. {END} This causes the [sqlite3_step()] interface to
93891 ** behave a differently in two ways:
93892 **
93893 ** <ol>
93894 ** <li>{F13022}
93895 ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
93896 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
93897 ** statement and try to run it again. {F12023} If the schema has changed in
93898 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
93899 ** return [SQLITE_SCHEMA].  {END} But unlike the legacy behavior, 
93900 ** [SQLITE_SCHEMA] is now a fatal error.  {F12024} Calling
93901 ** [sqlite3_prepare_v2()] again will not make the
93902 ** error go away.  {F12025} Note: use [sqlite3_errmsg()] to find the text
93903 ** of the parsing error that results in an [SQLITE_SCHEMA] return. {END}
93904 ** </li>
93905 **
93906 ** <li>
93907 ** {F13030} When an error occurs, 
93908 ** [sqlite3_step()] will return one of the detailed 
93909 ** [SQLITE_ERROR | result codes] or
93910 ** [SQLITE_IOERR_READ | extended result codes].  {F13031}
93911 ** The legacy behavior was that [sqlite3_step()] would only return a generic
93912 ** [SQLITE_ERROR] result code and you would have to make a second call to
93913 ** [sqlite3_reset()] in order to find the underlying cause of the problem.
93914 ** {F13032}
93915 ** With the "v2" prepare interfaces, the underlying reason for the error is
93916 ** returned immediately. {END}
93917 ** </li>
93918 ** </ol>
93919 */
93920 int sqlite3_prepare(
93921   sqlite3 *db,            /* Database handle */
93922   const char *zSql,       /* SQL statement, UTF-8 encoded */
93923   int nByte,              /* Maximum length of zSql in bytes. */
93924   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
93925   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
93926 );
93927 int sqlite3_prepare_v2(
93928   sqlite3 *db,            /* Database handle */
93929   const char *zSql,       /* SQL statement, UTF-8 encoded */
93930   int nByte,              /* Maximum length of zSql in bytes. */
93931   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
93932   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
93933 );
93934 int sqlite3_prepare16(
93935   sqlite3 *db,            /* Database handle */
93936   const void *zSql,       /* SQL statement, UTF-16 encoded */
93937   int nByte,              /* Maximum length of zSql in bytes. */
93938   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
93939   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
93940 );
93941 int sqlite3_prepare16_v2(
93942   sqlite3 *db,            /* Database handle */
93943   const void *zSql,       /* SQL statement, UTF-16 encoded */
93944   int nByte,              /* Maximum length of zSql in bytes. */
93945   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
93946   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
93947 );
93948
93949 /*
93950 ** CAPIREF: Retrieving Statement SQL {F13100}
93951 **
93952 ** {F13101} If the compiled SQL statement passed as an argument was
93953 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()],
93954 ** then this function returns a pointer to a zero-terminated string
93955 ** containing a copy of the original SQL statement. {F13102} The
93956 ** pointer is valid until the statement
93957 ** is deleted using sqlite3_finalize().
93958 ** {F13103} The string returned by sqlite3_sql() is always UTF8 even
93959 ** if a UTF16 string was originally entered using [sqlite3_prepare16_v2()]
93960 ** or the equivalent.
93961 **
93962 ** {F13104} If the statement was compiled using either of the legacy
93963 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this
93964 ** function returns NULL.
93965 */
93966 const char *sqlite3_sql(sqlite3_stmt *pStmt);
93967
93968 /*
93969 ** CAPI3REF:  Dynamically Typed Value Object  {F15000}
93970 **
93971 ** {F15001} SQLite uses the sqlite3_value object to represent all values
93972 ** that are or can be stored in a database table. {END}
93973 ** SQLite uses dynamic typing for the values it stores.  
93974 ** {F15002} Values stored in sqlite3_value objects can be
93975 ** be integers, floating point values, strings, BLOBs, or NULL.
93976 */
93977 typedef struct Mem sqlite3_value;
93978
93979 /*
93980 ** CAPI3REF:  SQL Function Context Object {F16001}
93981 **
93982 ** The context in which an SQL function executes is stored in an
93983 ** sqlite3_context object.  {F16002} A pointer to an sqlite3_context
93984 ** object is always first parameter to application-defined SQL functions.
93985 */
93986 typedef struct sqlite3_context sqlite3_context;
93987
93988 /*
93989 ** CAPI3REF:  Binding Values To Prepared Statements {F13500}
93990 **
93991 ** {F13501} In the SQL strings input to [sqlite3_prepare_v2()] and its
93992 ** variants, literals may be replace by a parameter in one
93993 ** of these forms:
93994 **
93995 ** <ul>
93996 ** <li>  ?
93997 ** <li>  ?NNN
93998 ** <li>  :AAA
93999 ** <li>  @AAA
94000 ** <li>  $VVV
94001 ** </ul>
94002 **
94003 ** In the parameter forms shown above NNN is an integer literal,
94004 ** AAA is an alphanumeric identifier and VVV is a variable name according
94005 ** to the syntax rules of the TCL programming language. {END}
94006 ** The values of these parameters (also called "host parameter names")
94007 ** can be set using the sqlite3_bind_*() routines defined here.
94008 **
94009 ** {F13502} The first argument to the sqlite3_bind_*() routines always
94010 ** is a pointer to the [sqlite3_stmt] object returned from
94011 ** [sqlite3_prepare_v2()] or its variants.  {F13503} The second
94012 ** argument is the index of the parameter to be set.  {F13504} The
94013 ** first parameter has an index of 1.  {F13505} When the same named
94014 ** parameter is used more than once, second and subsequent
94015 ** occurrences have the same index as the first occurrence. 
94016 ** {F13506} The index for named parameters can be looked up using the
94017 ** [sqlite3_bind_parameter_name()] API if desired.  {F13507} The index
94018 ** for "?NNN" parameters is the value of NNN.
94019 ** {F13508} The NNN value must be between 1 and the compile-time
94020 ** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). {END}
94021 ** See <a href="limits.html">limits.html</a> for additional information.
94022 **
94023 ** {F13509} The third argument is the value to bind to the parameter. {END}
94024 **
94025 ** {F13510} In those
94026 ** routines that have a fourth argument, its value is the number of bytes
94027 ** in the parameter.  To be clear: the value is the number of bytes in the
94028 ** string, not the number of characters. {F13511}  The number
94029 ** of bytes does not include the zero-terminator at the end of strings.
94030 ** {F13512}
94031 ** If the fourth parameter is negative, the length of the string is
94032 ** number of bytes up to the first zero terminator. {END}
94033 **
94034 ** {F13513}
94035 ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
94036 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
94037 ** text after SQLite has finished with it. {F13514} If the fifth argument is
94038 ** the special value [SQLITE_STATIC], then the library assumes that the
94039 ** information is in static, unmanaged space and does not need to be freed.
94040 ** {F13515} If the fifth argument has the value [SQLITE_TRANSIENT], then
94041 ** SQLite makes its own private copy of the data immediately, before
94042 ** the sqlite3_bind_*() routine returns. {END}
94043 **
94044 ** {F13520} The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
94045 ** is filled with zeros.  {F13521} A zeroblob uses a fixed amount of memory
94046 ** (just an integer to hold it size) while it is being processed. {END}
94047 ** Zeroblobs are intended to serve as place-holders for BLOBs whose
94048 ** content is later written using 
94049 ** [sqlite3_blob_open | increment BLOB I/O] routines. {F13522} A negative
94050 ** value for the zeroblob results in a zero-length BLOB. {END}
94051 **
94052 ** {F13530} The sqlite3_bind_*() routines must be called after
94053 ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and
94054 ** before [sqlite3_step()]. {F13531}
94055 ** Bindings are not cleared by the [sqlite3_reset()] routine.
94056 ** {F13532} Unbound parameters are interpreted as NULL. {END}
94057 **
94058 ** {F13540} These routines return [SQLITE_OK] on success or an error code if
94059 ** anything goes wrong.  {F13541} [SQLITE_RANGE] is returned if the parameter
94060 ** index is out of range.  {F13542} [SQLITE_NOMEM] is returned if malloc fails.
94061 ** {F13543} [SQLITE_MISUSE] is returned if these routines are called on a
94062 ** virtual machine that is the wrong state or which has already been finalized.
94063 */
94064 int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
94065 int sqlite3_bind_double(sqlite3_stmt*, int, double);
94066 int sqlite3_bind_int(sqlite3_stmt*, int, int);
94067 int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
94068 int sqlite3_bind_null(sqlite3_stmt*, int);
94069 int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
94070 int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
94071 int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
94072 int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
94073
94074 /*
94075 ** CAPI3REF: Number Of Host Parameters {F13600}
94076 **
94077 ** {F13601} Return the largest host parameter index in the precompiled
94078 ** statement given as the argument. {F13602} When the host parameters
94079 ** are of the forms like ":AAA", "$VVV", "@AAA", or "?",
94080 ** then they are assigned sequential increasing numbers beginning
94081 ** with one, so the value returned is the number of parameters.
94082 ** {F13603} However
94083 ** if the same host parameter name is used multiple times, each occurrance
94084 ** is given the same number, so the value returned in that case is the number
94085 ** of unique host parameter names. {F13604} If host parameters of the
94086 ** form "?NNN" are used (where NNN is an integer) then there might be
94087 ** gaps in the numbering and the value returned by this interface is
94088 ** the index of the host parameter with the largest index value. {END}
94089 **
94090 ** {U13605} The prepared statement must not be [sqlite3_finalize | finalized]
94091 ** prior to this routine returning.  Otherwise the results are undefined
94092 ** and probably undesirable.
94093 */
94094 int sqlite3_bind_parameter_count(sqlite3_stmt*);
94095
94096 /*
94097 ** CAPI3REF: Name Of A Host Parameter {F13620}
94098 **
94099 ** {F13621} This routine returns a pointer to the name of the n-th
94100 ** parameter in a [sqlite3_stmt | prepared statement]. {F13622}
94101 ** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name
94102 ** which is the string ":AAA" or "@AAA" or "$VVV". 
94103 ** In other words, the initial ":" or "$" or "@"
94104 ** is included as part of the name.  {F13626}
94105 ** Parameters of the form "?" or "?NNN" have no name.
94106 **
94107 ** {F13623} The first host parameter has an index of 1, not 0.
94108 **
94109 ** {F13624} If the value n is out of range or if the n-th parameter is
94110 ** nameless, then NULL is returned.  {F13625} The returned string is
94111 ** always in the UTF-8 encoding even if the named parameter was
94112 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
94113 ** [sqlite3_prepare16_v2()].
94114 */
94115 const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
94116
94117 /*
94118 ** CAPI3REF: Index Of A Parameter With A Given Name {F13640}
94119 **
94120 ** {F13641} This routine returns the index of a host parameter with the
94121 ** given name.  {F13642} The name must match exactly.  {F13643}
94122 ** If no parameter with the given name is found, return 0.
94123 ** {F13644} Parameter names must be UTF8.
94124 */
94125 int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
94126
94127 /*
94128 ** CAPI3REF: Reset All Bindings On A Prepared Statement {F13660}
94129 **
94130 ** {F13661} Contrary to the intuition of many, [sqlite3_reset()] does not
94131 ** reset the [sqlite3_bind_blob | bindings] on a 
94132 ** [sqlite3_stmt | prepared statement]. {F13662} Use this routine to
94133 ** reset all host parameters to NULL.
94134 */
94135 int sqlite3_clear_bindings(sqlite3_stmt*);
94136
94137 /*
94138 ** CAPI3REF: Number Of Columns In A Result Set {F13710}
94139 **
94140 ** {F13711} Return the number of columns in the result set returned by the 
94141 ** [sqlite3_stmt | compiled SQL statement]. {F13712} This routine returns 0
94142 ** if pStmt is an SQL statement that does not return data (for 
94143 ** example an UPDATE).
94144 */
94145 int sqlite3_column_count(sqlite3_stmt *pStmt);
94146
94147 /*
94148 ** CAPI3REF: Column Names In A Result Set {F13720}
94149 **
94150 ** {F13721} These routines return the name assigned to a particular column
94151 ** in the result set of a SELECT statement.  {F13722} The sqlite3_column_name()
94152 ** interface returns a pointer to a zero-terminated UTF8 string
94153 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
94154 ** UTF16 string. {F13723}  The first parameter is the
94155 ** [sqlite3_stmt | prepared statement] that implements the SELECT statement.
94156 ** The second parameter is the column number.  The left-most column is
94157 ** number 0.
94158 **
94159 ** {F13724} The returned string pointer is valid until either the 
94160 ** [sqlite3_stmt | prepared statement] is destroyed by [sqlite3_finalize()]
94161 ** or until the next call sqlite3_column_name() or sqlite3_column_name16()
94162 ** on the same column.
94163 **
94164 ** {F13725} If sqlite3_malloc() fails during the processing of either routine
94165 ** (for example during a conversion from UTF-8 to UTF-16) then a
94166 ** NULL pointer is returned.
94167 */
94168 const char *sqlite3_column_name(sqlite3_stmt*, int N);
94169 const void *sqlite3_column_name16(sqlite3_stmt*, int N);
94170
94171 /*
94172 ** CAPI3REF: Source Of Data In A Query Result {F13740}
94173 **
94174 ** {F13741} These routines provide a means to determine what column of what
94175 ** table in which database a result of a SELECT statement comes from.
94176 ** {F13742} The name of the database or table or column can be returned as
94177 ** either a UTF8 or UTF16 string.  {F13743} The _database_ routines return
94178 ** the database name, the _table_ routines return the table name, and
94179 ** the origin_ routines return the column name. {F13744}
94180 ** The returned string is valid until
94181 ** the [sqlite3_stmt | prepared statement] is destroyed using
94182 ** [sqlite3_finalize()] or until the same information is requested
94183 ** again in a different encoding.
94184 **
94185 ** {F13745} The names returned are the original un-aliased names of the
94186 ** database, table, and column.
94187 **
94188 ** {F13746} The first argument to the following calls is a 
94189 ** [sqlite3_stmt | compiled SQL statement].
94190 ** {F13747} These functions return information about the Nth column returned by 
94191 ** the statement, where N is the second function argument.
94192 **
94193 ** {F13748} If the Nth column returned by the statement is an expression
94194 ** or subquery and is not a column value, then all of these functions
94195 ** return NULL.  {F13749} Otherwise, they return the 
94196 ** name of the attached database, table and column that query result
94197 ** column was extracted from.
94198 **
94199 ** {F13750} As with all other SQLite APIs, those postfixed with "16" return
94200 ** UTF-16 encoded strings, the other functions return UTF-8. {END}
94201 **
94202 ** These APIs are only available if the library was compiled with the 
94203 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
94204 **
94205 ** {U13751}
94206 ** If two or more threads call one or more of these routines against the same
94207 ** prepared statement and column at the same time then the results are
94208 ** undefined.
94209 */
94210 const char *sqlite3_column_database_name(sqlite3_stmt*,int);
94211 const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
94212 const char *sqlite3_column_table_name(sqlite3_stmt*,int);
94213 const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
94214 const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
94215 const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
94216
94217 /*
94218 ** CAPI3REF: Declared Datatype Of A Query Result {F13760}
94219 **
94220 ** The first parameter is a [sqlite3_stmt | compiled SQL statement]. 
94221 ** {F13761} If this statement is a SELECT statement and the Nth column of the 
94222 ** returned result set of that SELECT is a table column (not an
94223 ** expression or subquery) then the declared type of the table
94224 ** column is returned.  {F13762} If the Nth column of the result set is an
94225 ** expression or subquery, then a NULL pointer is returned.
94226 ** {F13763} The returned string is always UTF-8 encoded.  {END} 
94227 ** For example, in the database schema:
94228 **
94229 ** CREATE TABLE t1(c1 VARIANT);
94230 **
94231 ** And the following statement compiled:
94232 **
94233 ** SELECT c1 + 1, c1 FROM t1;
94234 **
94235 ** Then this routine would return the string "VARIANT" for the second
94236 ** result column (i==1), and a NULL pointer for the first result column
94237 ** (i==0).
94238 **
94239 ** SQLite uses dynamic run-time typing.  So just because a column
94240 ** is declared to contain a particular type does not mean that the
94241 ** data stored in that column is of the declared type.  SQLite is
94242 ** strongly typed, but the typing is dynamic not static.  Type
94243 ** is associated with individual values, not with the containers
94244 ** used to hold those values.
94245 */
94246 const char *sqlite3_column_decltype(sqlite3_stmt *, int i);
94247 const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
94248
94249 /* 
94250 ** CAPI3REF:  Evaluate An SQL Statement {F13200}
94251 **
94252 ** After an [sqlite3_stmt | SQL statement] has been prepared with a call
94253 ** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of
94254 ** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()],
94255 ** then this function must be called one or more times to evaluate the 
94256 ** statement.
94257 **
94258 ** The details of the behavior of this sqlite3_step() interface depend
94259 ** on whether the statement was prepared using the newer "v2" interface
94260 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
94261 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
94262 ** new "v2" interface is recommended for new applications but the legacy
94263 ** interface will continue to be supported.
94264 **
94265 ** In the lagacy interface, the return value will be either [SQLITE_BUSY], 
94266 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
94267 ** With the "v2" interface, any of the other [SQLITE_OK | result code]
94268 ** or [SQLITE_IOERR_READ | extended result code] might be returned as
94269 ** well.
94270 **
94271 ** [SQLITE_BUSY] means that the database engine was unable to acquire the
94272 ** database locks it needs to do its job.  If the statement is a COMMIT
94273 ** or occurs outside of an explicit transaction, then you can retry the
94274 ** statement.  If the statement is not a COMMIT and occurs within a
94275 ** explicit transaction then you should rollback the transaction before
94276 ** continuing.
94277 **
94278 ** [SQLITE_DONE] means that the statement has finished executing
94279 ** successfully.  sqlite3_step() should not be called again on this virtual
94280 ** machine without first calling [sqlite3_reset()] to reset the virtual
94281 ** machine back to its initial state.
94282 **
94283 ** If the SQL statement being executed returns any data, then 
94284 ** [SQLITE_ROW] is returned each time a new row of data is ready
94285 ** for processing by the caller. The values may be accessed using
94286 ** the [sqlite3_column_int | column access functions].
94287 ** sqlite3_step() is called again to retrieve the next row of data.
94288 ** 
94289 ** [SQLITE_ERROR] means that a run-time error (such as a constraint
94290 ** violation) has occurred.  sqlite3_step() should not be called again on
94291 ** the VM. More information may be found by calling [sqlite3_errmsg()].
94292 ** With the legacy interface, a more specific error code (example:
94293 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
94294 ** can be obtained by calling [sqlite3_reset()] on the
94295 ** [sqlite3_stmt | prepared statement].  In the "v2" interface,
94296 ** the more specific error code is returned directly by sqlite3_step().
94297 **
94298 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
94299 ** Perhaps it was called on a [sqlite3_stmt | prepared statement] that has
94300 ** already been [sqlite3_finalize | finalized] or on one that had 
94301 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
94302 ** be the case that the same database connection is being used by two or
94303 ** more threads at the same moment in time.
94304 **
94305 ** <b>Goofy Interface Alert:</b>
94306 ** In the legacy interface, 
94307 ** the sqlite3_step() API always returns a generic error code,
94308 ** [SQLITE_ERROR], following any error other than [SQLITE_BUSY]
94309 ** and [SQLITE_MISUSE].  You must call [sqlite3_reset()] or
94310 ** [sqlite3_finalize()] in order to find one of the specific
94311 ** [SQLITE_ERROR | result codes] that better describes the error.
94312 ** We admit that this is a goofy design.  The problem has been fixed
94313 ** with the "v2" interface.  If you prepare all of your SQL statements
94314 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
94315 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the 
94316 ** more specific [SQLITE_ERROR | result codes] are returned directly
94317 ** by sqlite3_step().  The use of the "v2" interface is recommended.
94318 */
94319 int sqlite3_step(sqlite3_stmt*);
94320
94321 /*
94322 ** CAPI3REF: Number of columns in a result set {F13770}
94323 **
94324 ** Return the number of values in the current row of the result set.
94325 **
94326 ** {F13771} After a call to [sqlite3_step()] that returns [SQLITE_ROW],
94327 ** this routine
94328 ** will return the same value as the [sqlite3_column_count()] function.
94329 ** {F13772}
94330 ** After [sqlite3_step()] has returned an [SQLITE_DONE], [SQLITE_BUSY], or
94331 ** a [SQLITE_ERROR | error code], or before [sqlite3_step()] has been 
94332 ** called on the [sqlite3_stmt | prepared statement] for the first time,
94333 ** this routine returns zero.
94334 */
94335 int sqlite3_data_count(sqlite3_stmt *pStmt);
94336
94337 /*
94338 ** CAPI3REF: Fundamental Datatypes {F10265}
94339 **
94340 ** {F10266}Every value in SQLite has one of five fundamental datatypes:
94341 **
94342 ** <ul>
94343 ** <li> 64-bit signed integer
94344 ** <li> 64-bit IEEE floating point number
94345 ** <li> string
94346 ** <li> BLOB
94347 ** <li> NULL
94348 ** </ul> {END}
94349 **
94350 ** These constants are codes for each of those types.
94351 **
94352 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
94353 ** for a completely different meaning.  Software that links against both
94354 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not
94355 ** SQLITE_TEXT.
94356 */
94357 #define SQLITE_INTEGER  1
94358 #define SQLITE_FLOAT    2
94359 #define SQLITE_BLOB     4
94360 #define SQLITE_NULL     5
94361 #ifdef SQLITE_TEXT
94362 # undef SQLITE_TEXT
94363 #else
94364 # define SQLITE_TEXT     3
94365 #endif
94366 #define SQLITE3_TEXT     3
94367
94368 /*
94369 ** CAPI3REF: Results Values From A Query {F13800}
94370 **
94371 ** These routines return information about
94372 ** a single column of the current result row of a query.  In every
94373 ** case the first argument is a pointer to the 
94374 ** [sqlite3_stmt | SQL statement] that is being
94375 ** evaluated (the [sqlite3_stmt*] that was returned from 
94376 ** [sqlite3_prepare_v2()] or one of its variants) and
94377 ** the second argument is the index of the column for which information 
94378 ** should be returned.  The left-most column of the result set
94379 ** has an index of 0.
94380 **
94381 ** If the SQL statement is not currently point to a valid row, or if the
94382 ** the column index is out of range, the result is undefined. 
94383 ** These routines may only be called when the most recent call to
94384 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
94385 ** [sqlite3_reset()] nor [sqlite3_finalize()] has been call subsequently.
94386 ** If any of these routines are called after [sqlite3_reset()] or
94387 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
94388 ** something other than [SQLITE_ROW], the results are undefined.
94389 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
94390 ** are called from a different thread while any of these routines
94391 ** are pending, then the results are undefined.  
94392 **
94393 ** The sqlite3_column_type() routine returns 
94394 ** [SQLITE_INTEGER | datatype code] for the initial data type
94395 ** of the result column.  The returned value is one of [SQLITE_INTEGER],
94396 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
94397 ** returned by sqlite3_column_type() is only meaningful if no type
94398 ** conversions have occurred as described below.  After a type conversion,
94399 ** the value returned by sqlite3_column_type() is undefined.  Future
94400 ** versions of SQLite may change the behavior of sqlite3_column_type()
94401 ** following a type conversion.
94402 **
94403 ** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() 
94404 ** routine returns the number of bytes in that BLOB or string.
94405 ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
94406 ** the string to UTF-8 and then returns the number of bytes.
94407 ** If the result is a numeric value then sqlite3_column_bytes() uses
94408 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
94409 ** the number of bytes in that string.
94410 ** The value returned does not include the zero terminator at the end
94411 ** of the string.  For clarity: the value returned is the number of
94412 ** bytes in the string, not the number of characters.
94413 **
94414 ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
94415 ** even zero-length strings, are always zero terminated.  The return
94416 ** value from sqlite3_column_blob() for a zero-length blob is an arbitrary
94417 ** pointer, possibly even a NULL pointer.
94418 **
94419 ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
94420 ** but leaves the result in UTF-16 instead of UTF-8.  
94421 ** The zero terminator is not included in this count.
94422 **
94423 ** These routines attempt to convert the value where appropriate.  For
94424 ** example, if the internal representation is FLOAT and a text result
94425 ** is requested, [sqlite3_snprintf()] is used internally to do the conversion
94426 ** automatically.  The following table details the conversions that
94427 ** are applied:
94428 **
94429 ** <blockquote>
94430 ** <table border="1">
94431 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
94432 **
94433 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
94434 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
94435 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
94436 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
94437 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
94438 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
94439 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as for INTEGER->TEXT
94440 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
94441 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
94442 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
94443 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
94444 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
94445 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
94446 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
94447 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
94448 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
94449 ** </table>
94450 ** </blockquote>
94451 **
94452 ** The table above makes reference to standard C library functions atoi()
94453 ** and atof().  SQLite does not really use these functions.  It has its
94454 ** on equavalent internal routines.  The atoi() and atof() names are
94455 ** used in the table for brevity and because they are familiar to most
94456 ** C programmers.
94457 **
94458 ** Note that when type conversions occur, pointers returned by prior
94459 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
94460 ** sqlite3_column_text16() may be invalidated. 
94461 ** Type conversions and pointer invalidations might occur
94462 ** in the following cases:
94463 **
94464 ** <ul>
94465 ** <li><p>  The initial content is a BLOB and sqlite3_column_text() 
94466 **          or sqlite3_column_text16() is called.  A zero-terminator might
94467 **          need to be added to the string.</p></li>
94468 **
94469 ** <li><p>  The initial content is UTF-8 text and sqlite3_column_bytes16() or
94470 **          sqlite3_column_text16() is called.  The content must be converted
94471 **          to UTF-16.</p></li>
94472 **
94473 ** <li><p>  The initial content is UTF-16 text and sqlite3_column_bytes() or
94474 **          sqlite3_column_text() is called.  The content must be converted
94475 **          to UTF-8.</p></li>
94476 ** </ul>
94477 **
94478 ** Conversions between UTF-16be and UTF-16le are always done in place and do
94479 ** not invalidate a prior pointer, though of course the content of the buffer
94480 ** that the prior pointer points to will have been modified.  Other kinds
94481 ** of conversion are done in place when it is possible, but sometime it is
94482 ** not possible and in those cases prior pointers are invalidated.  
94483 **
94484 ** The safest and easiest to remember policy is to invoke these routines
94485 ** in one of the following ways:
94486 **
94487 **  <ul>
94488 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
94489 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
94490 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
94491 **  </ul>
94492 **
94493 ** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(),
94494 ** or sqlite3_column_text16() first to force the result into the desired
94495 ** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to
94496 ** find the size of the result.  Do not mix call to sqlite3_column_text() or
94497 ** sqlite3_column_blob() with calls to sqlite3_column_bytes16().  And do not
94498 ** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes().
94499 **
94500 ** The pointers returned are valid until a type conversion occurs as
94501 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
94502 ** [sqlite3_finalize()] is called.  The memory space used to hold strings
94503 ** and blobs is freed automatically.  Do <b>not</b> pass the pointers returned
94504 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into 
94505 ** [sqlite3_free()].
94506 **
94507 ** If a memory allocation error occurs during the evaluation of any
94508 ** of these routines, a default value is returned.  The default value
94509 ** is either the integer 0, the floating point number 0.0, or a NULL
94510 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
94511 ** [SQLITE_NOMEM].
94512 */
94513 const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
94514 int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
94515 int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
94516 double sqlite3_column_double(sqlite3_stmt*, int iCol);
94517 int sqlite3_column_int(sqlite3_stmt*, int iCol);
94518 sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
94519 const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
94520 const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
94521 int sqlite3_column_type(sqlite3_stmt*, int iCol);
94522 sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
94523
94524 /*
94525 ** CAPI3REF: Destroy A Prepared Statement Object {F13300}
94526 **
94527 ** The sqlite3_finalize() function is called to delete a 
94528 ** [sqlite3_stmt | compiled SQL statement]. If the statement was
94529 ** executed successfully, or not executed at all, then SQLITE_OK is returned.
94530 ** If execution of the statement failed then an 
94531 ** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code]
94532 ** is returned. 
94533 **
94534 ** This routine can be called at any point during the execution of the
94535 ** [sqlite3_stmt | virtual machine].  If the virtual machine has not 
94536 ** completed execution when this routine is called, that is like
94537 ** encountering an error or an interrupt.  (See [sqlite3_interrupt()].) 
94538 ** Incomplete updates may be rolled back and transactions cancelled,  
94539 ** depending on the circumstances, and the 
94540 ** [SQLITE_ERROR | result code] returned will be [SQLITE_ABORT].
94541 */
94542 int sqlite3_finalize(sqlite3_stmt *pStmt);
94543
94544 /*
94545 ** CAPI3REF: Reset A Prepared Statement Object {F13330}
94546 **
94547 ** The sqlite3_reset() function is called to reset a 
94548 ** [sqlite3_stmt | compiled SQL statement] object.
94549 ** back to its initial state, ready to be re-executed.
94550 ** Any SQL statement variables that had values bound to them using
94551 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
94552 ** Use [sqlite3_clear_bindings()] to reset the bindings.
94553 */
94554 int sqlite3_reset(sqlite3_stmt *pStmt);
94555
94556 /*
94557 ** CAPI3REF: Create Or Redefine SQL Functions {F16100}
94558 **
94559 ** The following two functions are used to add SQL functions or aggregates
94560 ** or to redefine the behavior of existing SQL functions or aggregates.  The
94561 ** difference only between the two is that the second parameter, the
94562 ** name of the (scalar) function or aggregate, is encoded in UTF-8 for
94563 ** sqlite3_create_function() and UTF-16 for sqlite3_create_function16().
94564 **
94565 ** The first argument is the [sqlite3 | database handle] that holds the
94566 ** SQL function or aggregate is to be added or redefined. If a single
94567 ** program uses more than one database handle internally, then SQL
94568 ** functions or aggregates must be added individually to each database
94569 ** handle with which they will be used.
94570 **
94571 ** The second parameter is the name of the SQL function to be created
94572 ** or redefined.
94573 ** The length of the name is limited to 255 bytes, exclusive of the 
94574 ** zero-terminator.  Note that the name length limit is in bytes, not
94575 ** characters.  Any attempt to create a function with a longer name
94576 ** will result in an SQLITE_ERROR error.
94577 **
94578 ** The third parameter is the number of arguments that the SQL function or
94579 ** aggregate takes. If this parameter is negative, then the SQL function or
94580 ** aggregate may take any number of arguments.
94581 **
94582 ** The fourth parameter, eTextRep, specifies what 
94583 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
94584 ** its parameters.  Any SQL function implementation should be able to work
94585 ** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
94586 ** more efficient with one encoding than another.  It is allowed to
94587 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
94588 ** times with the same function but with different values of eTextRep.
94589 ** When multiple implementations of the same function are available, SQLite
94590 ** will pick the one that involves the least amount of data conversion.
94591 ** If there is only a single implementation which does not care what
94592 ** text encoding is used, then the fourth argument should be
94593 ** [SQLITE_ANY].
94594 **
94595 ** The fifth parameter is an arbitrary pointer.  The implementation
94596 ** of the function can gain access to this pointer using
94597 ** [sqlite3_user_data()].
94598 **
94599 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
94600 ** pointers to C-language functions that implement the SQL
94601 ** function or aggregate. A scalar SQL function requires an implementation of
94602 ** the xFunc callback only, NULL pointers should be passed as the xStep
94603 ** and xFinal parameters. An aggregate SQL function requires an implementation
94604 ** of xStep and xFinal and NULL should be passed for xFunc. To delete an
94605 ** existing SQL function or aggregate, pass NULL for all three function
94606 ** callback.
94607 **
94608 ** It is permitted to register multiple implementations of the same
94609 ** functions with the same name but with either differing numbers of
94610 ** arguments or differing perferred text encodings.  SQLite will use
94611 ** the implementation most closely matches the way in which the
94612 ** SQL function is used.
94613 */
94614 int sqlite3_create_function(
94615   sqlite3 *,
94616   const char *zFunctionName,
94617   int nArg,
94618   int eTextRep,
94619   void*,
94620   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
94621   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
94622   void (*xFinal)(sqlite3_context*)
94623 );
94624 int sqlite3_create_function16(
94625   sqlite3*,
94626   const void *zFunctionName,
94627   int nArg,
94628   int eTextRep,
94629   void*,
94630   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
94631   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
94632   void (*xFinal)(sqlite3_context*)
94633 );
94634
94635 /*
94636 ** CAPI3REF: Text Encodings {F10267}
94637 **
94638 ** These constant define integer codes that represent the various
94639 ** text encodings supported by SQLite.
94640 */
94641 #define SQLITE_UTF8           1
94642 #define SQLITE_UTF16LE        2
94643 #define SQLITE_UTF16BE        3
94644 #define SQLITE_UTF16          4    /* Use native byte order */
94645 #define SQLITE_ANY            5    /* sqlite3_create_function only */
94646 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
94647
94648 /*
94649 ** CAPI3REF: Obsolete Functions
94650 **
94651 ** These functions are all now obsolete.  In order to maintain
94652 ** backwards compatibility with older code, we continue to support
94653 ** these functions.  However, new development projects should avoid
94654 ** the use of these functions.  To help encourage people to avoid
94655 ** using these functions, we are not going to tell you want they do.
94656 */
94657 int sqlite3_aggregate_count(sqlite3_context*);
94658 int sqlite3_expired(sqlite3_stmt*);
94659 int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
94660 int sqlite3_global_recover(void);
94661 void sqlite3_thread_cleanup(void);
94662 int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
94663
94664 /*
94665 ** CAPI3REF: Obtaining SQL Function Parameter Values {F15100}
94666 **
94667 ** The C-language implementation of SQL functions and aggregates uses
94668 ** this set of interface routines to access the parameter values on
94669 ** the function or aggregate.
94670 **
94671 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
94672 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
94673 ** define callbacks that implement the SQL functions and aggregates.
94674 ** The 4th parameter to these callbacks is an array of pointers to
94675 ** [sqlite3_value] objects.  There is one [sqlite3_value] object for
94676 ** each parameter to the SQL function.  These routines are used to
94677 ** extract values from the [sqlite3_value] objects.
94678 **
94679 ** These routines work just like the corresponding 
94680 ** [sqlite3_column_blob | sqlite3_column_* routines] except that 
94681 ** these routines take a single [sqlite3_value*] pointer instead
94682 ** of an [sqlite3_stmt*] pointer and an integer column number.
94683 **
94684 ** The sqlite3_value_text16() interface extracts a UTF16 string
94685 ** in the native byte-order of the host machine.  The
94686 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
94687 ** extract UTF16 strings as big-endian and little-endian respectively.
94688 **
94689 ** The sqlite3_value_numeric_type() interface attempts to apply
94690 ** numeric affinity to the value.  This means that an attempt is
94691 ** made to convert the value to an integer or floating point.  If
94692 ** such a conversion is possible without loss of information (in other
94693 ** words if the value is a string that looks like a number)
94694 ** then the conversion is done.  Otherwise no conversion occurs.  The 
94695 ** [SQLITE_INTEGER | datatype] after conversion is returned.
94696 **
94697 ** Please pay particular attention to the fact that the pointer that
94698 ** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or
94699 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
94700 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
94701 ** or [sqlite3_value_text16()].  
94702 **
94703 ** These routines must be called from the same thread as
94704 ** the SQL function that supplied the sqlite3_value* parameters.
94705 ** Or, if the sqlite3_value* argument comes from the [sqlite3_column_value()]
94706 ** interface, then these routines should be called from the same thread
94707 ** that ran [sqlite3_column_value()].
94708 **
94709 */
94710 const void *sqlite3_value_blob(sqlite3_value*);
94711 int sqlite3_value_bytes(sqlite3_value*);
94712 int sqlite3_value_bytes16(sqlite3_value*);
94713 double sqlite3_value_double(sqlite3_value*);
94714 int sqlite3_value_int(sqlite3_value*);
94715 sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
94716 const unsigned char *sqlite3_value_text(sqlite3_value*);
94717 const void *sqlite3_value_text16(sqlite3_value*);
94718 const void *sqlite3_value_text16le(sqlite3_value*);
94719 const void *sqlite3_value_text16be(sqlite3_value*);
94720 int sqlite3_value_type(sqlite3_value*);
94721 int sqlite3_value_numeric_type(sqlite3_value*);
94722
94723 /*
94724 ** CAPI3REF: Obtain Aggregate Function Context {F16210}
94725 **
94726 ** The implementation of aggregate SQL functions use this routine to allocate
94727 ** a structure for storing their state.  
94728 ** {F16211} The first time the sqlite3_aggregate_context() routine is
94729 ** is called for a particular aggregate, SQLite allocates nBytes of memory
94730 ** zeros that memory, and returns a pointer to it.
94731 ** {F16212} On second and subsequent calls to sqlite3_aggregate_context()
94732 ** for the same aggregate function index, the same buffer is returned. {END}
94733 ** The implementation
94734 ** of the aggregate can use the returned buffer to accumulate data.
94735 **
94736 ** {F16213} SQLite automatically frees the allocated buffer when the aggregate
94737 ** query concludes. {END}
94738 **
94739 ** The first parameter should be a copy of the 
94740 ** [sqlite3_context | SQL function context] that is the first
94741 ** parameter to the callback routine that implements the aggregate
94742 ** function.
94743 **
94744 ** This routine must be called from the same thread in which
94745 ** the aggregate SQL function is running.
94746 */
94747 void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
94748
94749 /*
94750 ** CAPI3REF: User Data For Functions {F16240}
94751 **
94752 ** {F16241} The sqlite3_user_data() interface returns a copy of
94753 ** the pointer that was the pUserData parameter (the 5th parameter)
94754 ** of the the [sqlite3_create_function()]
94755 ** and [sqlite3_create_function16()] routines that originally
94756 ** registered the application defined function. {END}
94757 **
94758 ** {U16243} This routine must be called from the same thread in which
94759 ** the application-defined function is running.
94760 */
94761 void *sqlite3_user_data(sqlite3_context*);
94762
94763 /*
94764 ** CAPI3REF: Function Auxiliary Data {F16270}
94765 **
94766 ** The following two functions may be used by scalar SQL functions to
94767 ** associate meta-data with argument values. If the same value is passed to
94768 ** multiple invocations of the same SQL function during query execution, under
94769 ** some circumstances the associated meta-data may be preserved. This may
94770 ** be used, for example, to add a regular-expression matching scalar
94771 ** function. The compiled version of the regular expression is stored as
94772 ** meta-data associated with the SQL value passed as the regular expression
94773 ** pattern.  The compiled regular expression can be reused on multiple
94774 ** invocations of the same function so that the original pattern string
94775 ** does not need to be recompiled on each invocation.
94776 **
94777 ** {F16271}
94778 ** The sqlite3_get_auxdata() interface returns a pointer to the meta-data
94779 ** associated by the sqlite3_set_auxdata() function with the Nth argument
94780 ** value to the application-defined function.
94781 ** {F16272} If no meta-data has been ever been set for the Nth
94782 ** argument of the function, or if the cooresponding function parameter
94783 ** has changed since the meta-data was set, then sqlite3_get_auxdata()
94784 ** returns a NULL pointer.
94785 **
94786 ** {F16275} The sqlite3_set_auxdata() interface saves the meta-data
94787 ** pointed to by its 3rd parameter as the meta-data for the N-th
94788 ** argument of the application-defined function. {END} Subsequent
94789 ** calls to sqlite3_get_auxdata() might return this data, if it has
94790 ** not been destroyed. 
94791 ** {F16277} If it is not NULL, SQLite will invoke the destructor 
94792 ** function given by the 4th parameter to sqlite3_set_auxdata() on
94793 ** the meta-data when the corresponding function parameter changes
94794 ** or when the SQL statement completes, whichever comes first. {END}
94795 **
94796 ** In practice, meta-data is preserved between function calls for
94797 ** expressions that are constant at compile time. This includes literal
94798 ** values and SQL variables.
94799 **
94800 ** These routines must be called from the same thread in which
94801 ** the SQL function is running.
94802 */
94803 void *sqlite3_get_auxdata(sqlite3_context*, int N);
94804 void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
94805
94806
94807 /*
94808 ** CAPI3REF: Constants Defining Special Destructor Behavior {F10280}
94809 **
94810 ** These are special value for the destructor that is passed in as the
94811 ** final argument to routines like [sqlite3_result_blob()].  If the destructor
94812 ** argument is SQLITE_STATIC, it means that the content pointer is constant
94813 ** and will never change.  It does not need to be destroyed.  The 
94814 ** SQLITE_TRANSIENT value means that the content will likely change in
94815 ** the near future and that SQLite should make its own private copy of
94816 ** the content before returning.
94817 **
94818 ** The typedef is necessary to work around problems in certain
94819 ** C++ compilers.  See ticket #2191.
94820 */
94821 typedef void (*sqlite3_destructor_type)(void*);
94822 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
94823 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
94824
94825 /*
94826 ** CAPI3REF: Setting The Result Of An SQL Function {F16400}
94827 **
94828 ** These routines are used by the xFunc or xFinal callbacks that
94829 ** implement SQL functions and aggregates.  See
94830 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
94831 ** for additional information.
94832 **
94833 ** These functions work very much like the 
94834 ** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used
94835 ** to bind values to host parameters in prepared statements.
94836 ** Refer to the
94837 ** [sqlite3_bind_blob | sqlite3_bind_* documentation] for
94838 ** additional information.
94839 **
94840 ** {F16402} The sqlite3_result_blob() interface sets the result from
94841 ** an application defined function to be the BLOB whose content is pointed
94842 ** to by the second parameter and which is N bytes long where N is the
94843 ** third parameter. 
94844 ** {F16403} The sqlite3_result_zeroblob() inerfaces set the result of
94845 ** the application defined function to be a BLOB containing all zero
94846 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
94847 **
94848 ** {F16407} The sqlite3_result_double() interface sets the result from
94849 ** an application defined function to be a floating point value specified
94850 ** by its 2nd argument.
94851 **
94852 ** {F16409} The sqlite3_result_error() and sqlite3_result_error16() functions
94853 ** cause the implemented SQL function to throw an exception.
94854 ** {F16411} SQLite uses the string pointed to by the
94855 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
94856 ** as the text of an error message. {F16412} SQLite interprets the error
94857 ** message string from sqlite3_result_error() as UTF8.  {F16413} SQLite
94858 ** interprets the string from sqlite3_result_error16() as UTF16 in native
94859 ** byte order.  {F16414} If the third parameter to sqlite3_result_error()
94860 ** or sqlite3_result_error16() is negative then SQLite takes as the error
94861 ** message all text up through the first zero character.
94862 ** {F16415} If the third parameter to sqlite3_result_error() or
94863 ** sqlite3_result_error16() is non-negative then SQLite takes that many
94864 ** bytes (not characters) from the 2nd parameter as the error message.
94865 ** {F16417} The sqlite3_result_error() and sqlite3_result_error16()
94866 ** routines make a copy private copy of the error message text before
94867 ** they return.  {END} Hence, the calling function can deallocate or
94868 ** modify the text after they return without harm.
94869 **
94870 ** {F16421} The sqlite3_result_toobig() interface causes SQLite
94871 ** to throw an error indicating that a string or BLOB is to long
94872 ** to represent.  {F16422} The sqlite3_result_nomem() interface
94873 ** causes SQLite to throw an exception indicating that the a
94874 ** memory allocation failed.
94875 **
94876 ** {F16431} The sqlite3_result_int() interface sets the return value
94877 ** of the application-defined function to be the 32-bit signed integer
94878 ** value given in the 2nd argument.
94879 ** {F16432} The sqlite3_result_int64() interface sets the return value
94880 ** of the application-defined function to be the 64-bit signed integer
94881 ** value given in the 2nd argument.
94882 **
94883 ** {F16437} The sqlite3_result_null() interface sets the return value
94884 ** of the application-defined function to be NULL.
94885 **
94886 ** {F16441} The sqlite3_result_text(), sqlite3_result_text16(), 
94887 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
94888 ** set the return value of the application-defined function to be
94889 ** a text string which is represented as UTF-8, UTF-16 native byte order,
94890 ** UTF-16 little endian, or UTF-16 big endian, respectively.
94891 ** {F16442} SQLite takes the text result from the application from
94892 ** the 2nd parameter of the sqlite3_result_text* interfaces.
94893 ** {F16444} If the 3rd parameter to the sqlite3_result_text* interfaces
94894 ** is negative, then SQLite takes result text from the 2nd parameter 
94895 ** through the first zero character.
94896 ** {F16447} If the 3rd parameter to the sqlite3_result_text* interfaces
94897 ** is non-negative, then as many bytes (not characters) of the text
94898 ** pointed to by the 2nd parameter are taken as the application-defined
94899 ** function result.
94900 ** {F16451} If the 4th parameter to the sqlite3_result_text* interfaces
94901 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
94902 ** function as the destructor on the text or blob result when it has
94903 ** finished using that result.
94904 ** {F16453} If the 4th parameter to the sqlite3_result_text* interfaces
94905 ** or sqlite3_result_blob is the special constant SQLITE_STATIC, then
94906 ** SQLite assumes that the text or blob result is constant space and
94907 ** does not copy the space or call a destructor when it has
94908 ** finished using that result.
94909 ** {F16454} If the 4th parameter to the sqlite3_result_text* interfaces
94910 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
94911 ** then SQLite makes a copy of the result into space obtained from
94912 ** from [sqlite3_malloc()] before it returns.
94913 **
94914 ** {F16461} The sqlite3_result_value() interface sets the result of
94915 ** the application-defined function to be a copy the [sqlite3_value]
94916 ** object specified by the 2nd parameter.  {F16463} The
94917 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
94918 ** so that [sqlite3_value] specified in the parameter may change or
94919 ** be deallocated after sqlite3_result_value() returns without harm.
94920 **
94921 ** {U16491} These routines are called from within the different thread 
94922 ** than the one containing the application-defined function that recieved
94923 ** the [sqlite3_context] pointer, the results are undefined.
94924 */
94925 void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
94926 void sqlite3_result_double(sqlite3_context*, double);
94927 void sqlite3_result_error(sqlite3_context*, const char*, int);
94928 void sqlite3_result_error16(sqlite3_context*, const void*, int);
94929 void sqlite3_result_error_toobig(sqlite3_context*);
94930 void sqlite3_result_error_nomem(sqlite3_context*);
94931 void sqlite3_result_int(sqlite3_context*, int);
94932 void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
94933 void sqlite3_result_null(sqlite3_context*);
94934 void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
94935 void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
94936 void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
94937 void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
94938 void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
94939 void sqlite3_result_zeroblob(sqlite3_context*, int n);
94940
94941 /*
94942 ** CAPI3REF: Define New Collating Sequences {F16600}
94943 **
94944 ** {F16601}
94945 ** These functions are used to add new collation sequences to the
94946 ** [sqlite3*] handle specified as the first argument. 
94947 **
94948 ** {F16602}
94949 ** The name of the new collation sequence is specified as a UTF-8 string
94950 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
94951 ** and a UTF-16 string for sqlite3_create_collation16(). {F16603} In all cases
94952 ** the name is passed as the second function argument.
94953 **
94954 ** {F16604}
94955 ** The third argument may be one of the constants [SQLITE_UTF8],
94956 ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
94957 ** routine expects to be passed pointers to strings encoded using UTF-8,
94958 ** UTF-16 little-endian or UTF-16 big-endian respectively. {F16605} The
94959 ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that
94960 ** the routine expects pointers to 16-bit word aligned strings
94961 ** of UTF16 in the native byte order of the host computer.
94962 **
94963 ** {F16607}
94964 ** A pointer to the user supplied routine must be passed as the fifth
94965 ** argument. {F16609} If it is NULL, this is the same as deleting the collation
94966 ** sequence (so that SQLite cannot call it anymore).
94967 ** {F16611} Each time the application
94968 ** supplied function is invoked, it is passed a copy of the void* passed as
94969 ** the fourth argument to sqlite3_create_collation() or
94970 ** sqlite3_create_collation16() as its first parameter.
94971 **
94972 ** {F16612}
94973 ** The remaining arguments to the application-supplied routine are two strings,
94974 ** each represented by a [length, data] pair and encoded in the encoding
94975 ** that was passed as the third argument when the collation sequence was
94976 ** registered. {END} The application defined collation routine should
94977 ** return negative, zero or positive if
94978 ** the first string is less than, equal to, or greater than the second
94979 ** string. i.e. (STRING1 - STRING2).
94980 **
94981 ** {F16615}
94982 ** The sqlite3_create_collation_v2() works like sqlite3_create_collation()
94983 ** excapt that it takes an extra argument which is a destructor for
94984 ** the collation.  {F16617} The destructor is called when the collation is
94985 ** destroyed and is passed a copy of the fourth parameter void* pointer
94986 ** of the sqlite3_create_collation_v2().
94987 ** {F16618}  Collations are destroyed when
94988 ** they are overridden by later calls to the collation creation functions
94989 ** or when the [sqlite3*] database handle is closed using [sqlite3_close()].
94990 */
94991 int sqlite3_create_collation(
94992   sqlite3*, 
94993   const char *zName, 
94994   int eTextRep, 
94995   void*,
94996   int(*xCompare)(void*,int,const void*,int,const void*)
94997 );
94998 int sqlite3_create_collation_v2(
94999   sqlite3*, 
95000   const char *zName, 
95001   int eTextRep, 
95002   void*,
95003   int(*xCompare)(void*,int,const void*,int,const void*),
95004   void(*xDestroy)(void*)
95005 );
95006 int sqlite3_create_collation16(
95007   sqlite3*, 
95008   const char *zName, 
95009   int eTextRep, 
95010   void*,
95011   int(*xCompare)(void*,int,const void*,int,const void*)
95012 );
95013
95014 /*
95015 ** CAPI3REF: Collation Needed Callbacks {F16700}
95016 **
95017 ** {F16701}
95018 ** To avoid having to register all collation sequences before a database
95019 ** can be used, a single callback function may be registered with the
95020 ** database handle to be called whenever an undefined collation sequence is
95021 ** required.
95022 **
95023 ** {F16702}
95024 ** If the function is registered using the sqlite3_collation_needed() API,
95025 ** then it is passed the names of undefined collation sequences as strings
95026 ** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, the names
95027 ** are passed as UTF-16 in machine native byte order. {F16704} A call to either
95028 ** function replaces any existing callback.
95029 **
95030 ** {F16705} When the callback is invoked, the first argument passed is a copy
95031 ** of the second argument to sqlite3_collation_needed() or
95032 ** sqlite3_collation_needed16(). {F16706} The second argument is the database
95033 ** handle.  {F16707} The third argument is one of [SQLITE_UTF8],
95034 ** [SQLITE_UTF16BE], or [SQLITE_UTF16LE], indicating the most
95035 ** desirable form of the collation sequence function required.
95036 ** {F16708} The fourth parameter is the name of the
95037 ** required collation sequence. {END}
95038 **
95039 ** The callback function should register the desired collation using
95040 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
95041 ** [sqlite3_create_collation_v2()].
95042 */
95043 int sqlite3_collation_needed(
95044   sqlite3*, 
95045   void*, 
95046   void(*)(void*,sqlite3*,int eTextRep,const char*)
95047 );
95048 int sqlite3_collation_needed16(
95049   sqlite3*, 
95050   void*,
95051   void(*)(void*,sqlite3*,int eTextRep,const void*)
95052 );
95053
95054 /*
95055 ** Specify the key for an encrypted database.  This routine should be
95056 ** called right after sqlite3_open().
95057 **
95058 ** The code to implement this API is not available in the public release
95059 ** of SQLite.
95060 */
95061 int sqlite3_key(
95062   sqlite3 *db,                   /* Database to be rekeyed */
95063   const void *pKey, int nKey     /* The key */
95064 );
95065
95066 /*
95067 ** Change the key on an open database.  If the current database is not
95068 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
95069 ** database is decrypted.
95070 **
95071 ** The code to implement this API is not available in the public release
95072 ** of SQLite.
95073 */
95074 int sqlite3_rekey(
95075   sqlite3 *db,                   /* Database to be rekeyed */
95076   const void *pKey, int nKey     /* The new key */
95077 );
95078
95079 /*
95080 ** CAPI3REF:  Suspend Execution For A Short Time {F10530}
95081 **
95082 ** {F10531} The sqlite3_sleep() function
95083 ** causes the current thread to suspend execution
95084 ** for at least a number of milliseconds specified in its parameter.
95085 **
95086 ** {F10532} If the operating system does not support sleep requests with 
95087 ** millisecond time resolution, then the time will be rounded up to 
95088 ** the nearest second. {F10533} The number of milliseconds of sleep actually 
95089 ** requested from the operating system is returned.
95090 **
95091 ** {F10534} SQLite implements this interface by calling the xSleep()
95092 ** method of the default [sqlite3_vfs] object. {END}
95093 */
95094 int sqlite3_sleep(int);
95095
95096 /*
95097 ** CAPI3REF:  Name Of The Folder Holding Temporary Files {F10310}
95098 **
95099 ** If this global variable is made to point to a string which is
95100 ** the name of a folder (a.ka. directory), then all temporary files
95101 ** created by SQLite will be placed in that directory.  If this variable
95102 ** is NULL pointer, then SQLite does a search for an appropriate temporary
95103 ** file directory.
95104 **
95105 ** It is not safe to modify this variable once a database connection
95106 ** has been opened.  It is intended that this variable be set once
95107 ** as part of process initialization and before any SQLite interface
95108 ** routines have been call and remain unchanged thereafter.
95109 */
95110 SQLITE_EXTERN char *sqlite3_temp_directory;
95111
95112 /*
95113 ** CAPI3REF:  Test To See If The Database Is In Auto-Commit Mode {F12930}
95114 **
95115 ** {F12931} The sqlite3_get_autocommit() interfaces returns non-zero or
95116 ** zero if the given database connection is or is not in autocommit mode,
95117 ** respectively. {F12932}  Autocommit mode is on
95118 ** by default.  {F12933} Autocommit mode is disabled by a BEGIN statement.
95119 ** {F12934} Autocommit mode is reenabled by a COMMIT or ROLLBACK. {END}
95120 **
95121 ** If certain kinds of errors occur on a statement within a multi-statement
95122 ** transactions (errors including [SQLITE_FULL], [SQLITE_IOERR], 
95123 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
95124 ** transaction might be rolled back automatically.  {F12935} The only way to
95125 ** find out if SQLite automatically rolled back the transaction after
95126 ** an error is to use this function. {END}
95127 **
95128 ** {U12936} If another thread changes the autocommit status of the database
95129 ** connection while this routine is running, then the return value
95130 ** is undefined. {END}
95131 */
95132 int sqlite3_get_autocommit(sqlite3*);
95133
95134 /*
95135 ** CAPI3REF:  Find The Database Handle Of A Prepared Statement {F13120}
95136 **
95137 ** {F13121} The sqlite3_db_handle interface
95138 ** returns the [sqlite3*] database handle to which a
95139 ** [sqlite3_stmt | prepared statement] belongs.
95140 ** {F13122} the database handle returned by sqlite3_db_handle
95141 ** is the same database handle that was
95142 ** the first argument to the [sqlite3_prepare_v2()] or its variants
95143 ** that was used to create the statement in the first place.
95144 */
95145 sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
95146
95147
95148 /*
95149 ** CAPI3REF: Commit And Rollback Notification Callbacks {F12950}
95150 **
95151 ** {F12951} The sqlite3_commit_hook() interface registers a callback
95152 ** function to be invoked whenever a transaction is committed.
95153 ** {F12952} Any callback set by a previous call to sqlite3_commit_hook()
95154 ** for the same database connection is overridden.
95155 ** {F12953} The sqlite3_rollback_hook() interface registers a callback
95156 ** function to be invoked whenever a transaction is committed.
95157 ** {F12954} Any callback set by a previous call to sqlite3_commit_hook()
95158 ** for the same database connection is overridden.
95159 ** {F12956} The pArg argument is passed through
95160 ** to the callback.  {F12957} If the callback on a commit hook function 
95161 ** returns non-zero, then the commit is converted into a rollback.
95162 **
95163 ** {F12958} If another function was previously registered, its
95164 ** pArg value is returned.  Otherwise NULL is returned.
95165 **
95166 ** {F12959} Registering a NULL function disables the callback.
95167 **
95168 ** {F12961} For the purposes of this API, a transaction is said to have been 
95169 ** rolled back if an explicit "ROLLBACK" statement is executed, or
95170 ** an error or constraint causes an implicit rollback to occur.
95171 ** {F12962} The rollback callback is not invoked if a transaction is
95172 ** automatically rolled back because the database connection is closed.
95173 ** {F12964} The rollback callback is not invoked if a transaction is
95174 ** rolled back because a commit callback returned non-zero.
95175 ** <todo> Check on this </todo> {END}
95176 **
95177 ** These are experimental interfaces and are subject to change.
95178 */
95179 void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
95180 void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
95181
95182 /*
95183 ** CAPI3REF: Data Change Notification Callbacks {F12970}
95184 **
95185 ** {F12971} The sqlite3_update_hook() interface
95186 ** registers a callback function with the database connection identified by the 
95187 ** first argument to be invoked whenever a row is updated, inserted or deleted.
95188 ** {F12972} Any callback set by a previous call to this function for the same 
95189 ** database connection is overridden.
95190 **
95191 ** {F12974} The second argument is a pointer to the function to invoke when a 
95192 ** row is updated, inserted or deleted. 
95193 ** {F12976} The first argument to the callback is
95194 ** a copy of the third argument to sqlite3_update_hook().
95195 ** {F12977} The second callback 
95196 ** argument is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
95197 ** depending on the operation that caused the callback to be invoked.
95198 ** {F12978} The third and 
95199 ** fourth arguments to the callback contain pointers to the database and 
95200 ** table name containing the affected row.
95201 ** {F12979} The final callback parameter is 
95202 ** the rowid of the row.
95203 ** {F12981} In the case of an update, this is the rowid after 
95204 ** the update takes place.
95205 **
95206 ** {F12983} The update hook is not invoked when internal system tables are
95207 ** modified (i.e. sqlite_master and sqlite_sequence).
95208 **
95209 ** {F12984} If another function was previously registered, its pArg value
95210 ** is returned.  {F12985} Otherwise NULL is returned.
95211 */
95212 void *sqlite3_update_hook(
95213   sqlite3*, 
95214   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
95215   void*
95216 );
95217
95218 /*
95219 ** CAPI3REF:  Enable Or Disable Shared Pager Cache {F10330}
95220 **
95221 ** {F10331}
95222 ** This routine enables or disables the sharing of the database cache
95223 ** and schema data structures between connections to the same database.
95224 ** {F10332}
95225 ** Sharing is enabled if the argument is true and disabled if the argument
95226 ** is false.
95227 **
95228 ** {F10333} Cache sharing is enabled and disabled
95229 ** for an entire process. {END} This is a change as of SQLite version 3.5.0.
95230 ** In prior versions of SQLite, sharing was
95231 ** enabled or disabled for each thread separately.
95232 **
95233 ** {F10334}
95234 ** The cache sharing mode set by this interface effects all subsequent
95235 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
95236 ** {F10335} Existing database connections continue use the sharing mode
95237 ** that was in effect at the time they were opened. {END}
95238 **
95239 ** Virtual tables cannot be used with a shared cache.  {F10336} When shared
95240 ** cache is enabled, the [sqlite3_create_module()] API used to register
95241 ** virtual tables will always return an error. {END}
95242 **
95243 ** {F10337} This routine returns [SQLITE_OK] if shared cache was
95244 ** enabled or disabled successfully.  {F10338} An [SQLITE_ERROR | error code]
95245 ** is returned otherwise. {END}
95246 **
95247 ** {F10339} Shared cache is disabled by default. {END} But this might change in
95248 ** future releases of SQLite.  Applications that care about shared
95249 ** cache setting should set it explicitly.
95250 */
95251 int sqlite3_enable_shared_cache(int);
95252
95253 /*
95254 ** CAPI3REF:  Attempt To Free Heap Memory {F17340}
95255 **
95256 ** {F17341} The sqlite3_release_memory() interface attempts to
95257 ** free N bytes of heap memory by deallocating non-essential memory
95258 ** allocations held by the database labrary. {END}  Memory used
95259 ** to cache database pages to improve performance is an example of
95260 ** non-essential memory.  {F16342} sqlite3_release_memory() returns
95261 ** the number of bytes actually freed, which might be more or less
95262 ** than the amount requested.
95263 */
95264 int sqlite3_release_memory(int);
95265
95266 /*
95267 ** CAPI3REF:  Impose A Limit On Heap Size {F17350}
95268 **
95269 ** {F16351} The sqlite3_soft_heap_limit() interface
95270 ** places a "soft" limit on the amount of heap memory that may be allocated
95271 ** by SQLite. {F16352} If an internal allocation is requested 
95272 ** that would exceed the soft heap limit, [sqlite3_release_memory()] is
95273 ** invoked one or more times to free up some space before the allocation
95274 ** is made. {END}
95275 **
95276 ** {F16353} The limit is called "soft", because if
95277 ** [sqlite3_release_memory()] cannot
95278 ** free sufficient memory to prevent the limit from being exceeded,
95279 ** the memory is allocated anyway and the current operation proceeds.
95280 **
95281 ** {F16354}
95282 ** A negative or zero value for N means that there is no soft heap limit and
95283 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
95284 ** {F16355} The default value for the soft heap limit is zero.
95285 **
95286 ** SQLite makes a best effort to honor the soft heap limit.  
95287 ** {F16356} But if the soft heap limit cannot honored, execution will
95288 ** continue without error or notification. {END}  This is why the limit is 
95289 ** called a "soft" limit.  It is advisory only.
95290 **
95291 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
95292 ** allocated by a single thread - the same thread in which this routine
95293 ** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
95294 ** applied to all threads. {F16357} The value specified for the soft heap limit
95295 ** is an upper bound on the total memory allocation for all threads. {END}  In
95296 ** version 3.5.0 there is no mechanism for limiting the heap usage for
95297 ** individual threads.
95298 */
95299 void sqlite3_soft_heap_limit(int);
95300
95301 /*
95302 ** CAPI3REF:  Extract Metadata About A Column Of A Table {F12850}
95303 **
95304 ** This routine
95305 ** returns meta-data about a specific column of a specific database
95306 ** table accessible using the connection handle passed as the first function 
95307 ** argument.
95308 **
95309 ** The column is identified by the second, third and fourth parameters to 
95310 ** this function. The second parameter is either the name of the database
95311 ** (i.e. "main", "temp" or an attached database) containing the specified
95312 ** table or NULL. If it is NULL, then all attached databases are searched
95313 ** for the table using the same algorithm as the database engine uses to 
95314 ** resolve unqualified table references.
95315 **
95316 ** The third and fourth parameters to this function are the table and column 
95317 ** name of the desired column, respectively. Neither of these parameters 
95318 ** may be NULL.
95319 **
95320 ** Meta information is returned by writing to the memory locations passed as
95321 ** the 5th and subsequent parameters to this function. Any of these 
95322 ** arguments may be NULL, in which case the corresponding element of meta 
95323 ** information is ommitted.
95324 **
95325 ** <pre>
95326 ** Parameter     Output Type      Description
95327 ** -----------------------------------
95328 **
95329 **   5th         const char*      Data type
95330 **   6th         const char*      Name of the default collation sequence 
95331 **   7th         int              True if the column has a NOT NULL constraint
95332 **   8th         int              True if the column is part of the PRIMARY KEY
95333 **   9th         int              True if the column is AUTOINCREMENT
95334 ** </pre>
95335 **
95336 **
95337 ** The memory pointed to by the character pointers returned for the 
95338 ** declaration type and collation sequence is valid only until the next 
95339 ** call to any sqlite API function.
95340 **
95341 ** If the specified table is actually a view, then an error is returned.
95342 **
95343 ** If the specified column is "rowid", "oid" or "_rowid_" and an 
95344 ** INTEGER PRIMARY KEY column has been explicitly declared, then the output 
95345 ** parameters are set for the explicitly declared column. If there is no
95346 ** explicitly declared IPK column, then the output parameters are set as 
95347 ** follows:
95348 **
95349 ** <pre>
95350 **     data type: "INTEGER"
95351 **     collation sequence: "BINARY"
95352 **     not null: 0
95353 **     primary key: 1
95354 **     auto increment: 0
95355 ** </pre>
95356 **
95357 ** This function may load one or more schemas from database files. If an
95358 ** error occurs during this process, or if the requested table or column
95359 ** cannot be found, an SQLITE error code is returned and an error message
95360 ** left in the database handle (to be retrieved using sqlite3_errmsg()).
95361 **
95362 ** This API is only available if the library was compiled with the
95363 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
95364 */
95365 int sqlite3_table_column_metadata(
95366   sqlite3 *db,                /* Connection handle */
95367   const char *zDbName,        /* Database name or NULL */
95368   const char *zTableName,     /* Table name */
95369   const char *zColumnName,    /* Column name */
95370   char const **pzDataType,    /* OUTPUT: Declared data type */
95371   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
95372   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
95373   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
95374   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
95375 );
95376
95377 /*
95378 ** CAPI3REF: Load An Extension {F12600}
95379 **
95380 ** {F12601} The sqlite3_load_extension() interface
95381 ** attempts to load an SQLite extension library contained in the file
95382 ** zFile. {F12602} The entry point is zProc. {F12603} zProc may be 0
95383 ** in which case the name of the entry point defaults
95384 ** to "sqlite3_extension_init".
95385 **
95386 ** {F12604} The sqlite3_load_extension() interface shall
95387 ** return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
95388 **
95389 ** {F12605}
95390 ** If an error occurs and pzErrMsg is not 0, then the
95391 ** sqlite3_load_extension() interface shall attempt to fill *pzErrMsg with 
95392 ** error message text stored in memory obtained from [sqlite3_malloc()].
95393 ** {END}  The calling function should free this memory
95394 ** by calling [sqlite3_free()].
95395 **
95396 ** {F12606}
95397 ** Extension loading must be enabled using [sqlite3_enable_load_extension()]
95398 ** prior to calling this API or an error will be returned.
95399 */
95400 int sqlite3_load_extension(
95401   sqlite3 *db,          /* Load the extension into this database connection */
95402   const char *zFile,    /* Name of the shared library containing extension */
95403   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
95404   char **pzErrMsg       /* Put error message here if not 0 */
95405 );
95406
95407 /*
95408 ** CAPI3REF:  Enable Or Disable Extension Loading {F12620}
95409 **
95410 ** So as not to open security holes in older applications that are
95411 ** unprepared to deal with extension loading, and as a means of disabling
95412 ** extension loading while evaluating user-entered SQL, the following
95413 ** API is provided to turn the [sqlite3_load_extension()] mechanism on and
95414 ** off.  {F12622} It is off by default. {END} See ticket #1863.
95415 **
95416 ** {F12621} Call the sqlite3_enable_load_extension() routine
95417 ** with onoff==1 to turn extension loading on
95418 ** and call it with onoff==0 to turn it back off again. {END}
95419 */
95420 int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
95421
95422 /*
95423 ** CAPI3REF: Make Arrangements To Automatically Load An Extension {F12640}
95424 **
95425 ** {F12641} This function
95426 ** registers an extension entry point that is automatically invoked
95427 ** whenever a new database connection is opened using
95428 ** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. {END}
95429 **
95430 ** This API can be invoked at program startup in order to register
95431 ** one or more statically linked extensions that will be available
95432 ** to all new database connections.
95433 **
95434 ** {F12642} Duplicate extensions are detected so calling this routine multiple
95435 ** times with the same extension is harmless.
95436 **
95437 ** {F12643} This routine stores a pointer to the extension in an array
95438 ** that is obtained from sqlite_malloc(). {END} If you run a memory leak
95439 ** checker on your program and it reports a leak because of this
95440 ** array, then invoke [sqlite3_reset_auto_extension()] prior
95441 ** to shutdown to free the memory.
95442 **
95443 ** {F12644} Automatic extensions apply across all threads. {END}
95444 **
95445 ** This interface is experimental and is subject to change or
95446 ** removal in future releases of SQLite.
95447 */
95448 int sqlite3_auto_extension(void *xEntryPoint);
95449
95450
95451 /*
95452 ** CAPI3REF: Reset Automatic Extension Loading {F12660}
95453 **
95454 ** {F12661} This function disables all previously registered
95455 ** automatic extensions. {END}  This
95456 ** routine undoes the effect of all prior [sqlite3_automatic_extension()]
95457 ** calls.
95458 **
95459 ** {F12662} This call disabled automatic extensions in all threads. {END}
95460 **
95461 ** This interface is experimental and is subject to change or
95462 ** removal in future releases of SQLite.
95463 */
95464 void sqlite3_reset_auto_extension(void);
95465
95466
95467 /*
95468 ****** EXPERIMENTAL - subject to change without notice **************
95469 **
95470 ** The interface to the virtual-table mechanism is currently considered
95471 ** to be experimental.  The interface might change in incompatible ways.
95472 ** If this is a problem for you, do not use the interface at this time.
95473 **
95474 ** When the virtual-table mechanism stablizes, we will declare the
95475 ** interface fixed, support it indefinitely, and remove this comment.
95476 */
95477
95478 /*
95479 ** Structures used by the virtual table interface
95480 */
95481 typedef struct sqlite3_vtab sqlite3_vtab;
95482 typedef struct sqlite3_index_info sqlite3_index_info;
95483 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
95484 typedef struct sqlite3_module sqlite3_module;
95485
95486 /*
95487 ** A module is a class of virtual tables.  Each module is defined
95488 ** by an instance of the following structure.  This structure consists
95489 ** mostly of methods for the module.
95490 */
95491 struct sqlite3_module {
95492   int iVersion;
95493   int (*xCreate)(sqlite3*, void *pAux,
95494                int argc, const char *const*argv,
95495                sqlite3_vtab **ppVTab, char**);
95496   int (*xConnect)(sqlite3*, void *pAux,
95497                int argc, const char *const*argv,
95498                sqlite3_vtab **ppVTab, char**);
95499   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
95500   int (*xDisconnect)(sqlite3_vtab *pVTab);
95501   int (*xDestroy)(sqlite3_vtab *pVTab);
95502   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
95503   int (*xClose)(sqlite3_vtab_cursor*);
95504   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
95505                 int argc, sqlite3_value **argv);
95506   int (*xNext)(sqlite3_vtab_cursor*);
95507   int (*xEof)(sqlite3_vtab_cursor*);
95508   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
95509   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
95510   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
95511   int (*xBegin)(sqlite3_vtab *pVTab);
95512   int (*xSync)(sqlite3_vtab *pVTab);
95513   int (*xCommit)(sqlite3_vtab *pVTab);
95514   int (*xRollback)(sqlite3_vtab *pVTab);
95515   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
95516                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
95517                        void **ppArg);
95518
95519   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
95520 };
95521
95522 /*
95523 ** The sqlite3_index_info structure and its substructures is used to
95524 ** pass information into and receive the reply from the xBestIndex
95525 ** method of an sqlite3_module.  The fields under **Inputs** are the
95526 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
95527 ** results into the **Outputs** fields.
95528 **
95529 ** The aConstraint[] array records WHERE clause constraints of the
95530 ** form:
95531 **
95532 **         column OP expr
95533 **
95534 ** Where OP is =, &lt;, &lt;=, &gt;, or &gt;=.  
95535 ** The particular operator is stored
95536 ** in aConstraint[].op.  The index of the column is stored in 
95537 ** aConstraint[].iColumn.  aConstraint[].usable is TRUE if the
95538 ** expr on the right-hand side can be evaluated (and thus the constraint
95539 ** is usable) and false if it cannot.
95540 **
95541 ** The optimizer automatically inverts terms of the form "expr OP column"
95542 ** and makes other simplifications to the WHERE clause in an attempt to
95543 ** get as many WHERE clause terms into the form shown above as possible.
95544 ** The aConstraint[] array only reports WHERE clause terms in the correct
95545 ** form that refer to the particular virtual table being queried.
95546 **
95547 ** Information about the ORDER BY clause is stored in aOrderBy[].
95548 ** Each term of aOrderBy records a column of the ORDER BY clause.
95549 **
95550 ** The xBestIndex method must fill aConstraintUsage[] with information
95551 ** about what parameters to pass to xFilter.  If argvIndex>0 then
95552 ** the right-hand side of the corresponding aConstraint[] is evaluated
95553 ** and becomes the argvIndex-th entry in argv.  If aConstraintUsage[].omit
95554 ** is true, then the constraint is assumed to be fully handled by the
95555 ** virtual table and is not checked again by SQLite.
95556 **
95557 ** The idxNum and idxPtr values are recorded and passed into xFilter.
95558 ** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
95559 **
95560 ** The orderByConsumed means that output from xFilter will occur in
95561 ** the correct order to satisfy the ORDER BY clause so that no separate
95562 ** sorting step is required.
95563 **
95564 ** The estimatedCost value is an estimate of the cost of doing the
95565 ** particular lookup.  A full scan of a table with N entries should have
95566 ** a cost of N.  A binary search of a table of N entries should have a
95567 ** cost of approximately log(N).
95568 */
95569 struct sqlite3_index_info {
95570   /* Inputs */
95571   int nConstraint;           /* Number of entries in aConstraint */
95572   struct sqlite3_index_constraint {
95573      int iColumn;              /* Column on left-hand side of constraint */
95574      unsigned char op;         /* Constraint operator */
95575      unsigned char usable;     /* True if this constraint is usable */
95576      int iTermOffset;          /* Used internally - xBestIndex should ignore */
95577   } *aConstraint;            /* Table of WHERE clause constraints */
95578   int nOrderBy;              /* Number of terms in the ORDER BY clause */
95579   struct sqlite3_index_orderby {
95580      int iColumn;              /* Column number */
95581      unsigned char desc;       /* True for DESC.  False for ASC. */
95582   } *aOrderBy;               /* The ORDER BY clause */
95583
95584   /* Outputs */
95585   struct sqlite3_index_constraint_usage {
95586     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
95587     unsigned char omit;      /* Do not code a test for this constraint */
95588   } *aConstraintUsage;
95589   int idxNum;                /* Number used to identify the index */
95590   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
95591   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
95592   int orderByConsumed;       /* True if output is already ordered */
95593   double estimatedCost;      /* Estimated cost of using this index */
95594 };
95595 #define SQLITE_INDEX_CONSTRAINT_EQ    2
95596 #define SQLITE_INDEX_CONSTRAINT_GT    4
95597 #define SQLITE_INDEX_CONSTRAINT_LE    8
95598 #define SQLITE_INDEX_CONSTRAINT_LT    16
95599 #define SQLITE_INDEX_CONSTRAINT_GE    32
95600 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
95601
95602 /*
95603 ** This routine is used to register a new module name with an SQLite
95604 ** connection.  Module names must be registered before creating new
95605 ** virtual tables on the module, or before using preexisting virtual
95606 ** tables of the module.
95607 */
95608 int sqlite3_create_module(
95609   sqlite3 *db,               /* SQLite connection to register module with */
95610   const char *zName,         /* Name of the module */
95611   const sqlite3_module *,    /* Methods for the module */
95612   void *                     /* Client data for xCreate/xConnect */
95613 );
95614
95615 /*
95616 ** This routine is identical to the sqlite3_create_module() method above,
95617 ** except that it allows a destructor function to be specified. It is
95618 ** even more experimental than the rest of the virtual tables API.
95619 */
95620 int sqlite3_create_module_v2(
95621   sqlite3 *db,               /* SQLite connection to register module with */
95622   const char *zName,         /* Name of the module */
95623   const sqlite3_module *,    /* Methods for the module */
95624   void *,                    /* Client data for xCreate/xConnect */
95625   void(*xDestroy)(void*)     /* Module destructor function */
95626 );
95627
95628 /*
95629 ** Every module implementation uses a subclass of the following structure
95630 ** to describe a particular instance of the module.  Each subclass will
95631 ** be tailored to the specific needs of the module implementation.   The
95632 ** purpose of this superclass is to define certain fields that are common
95633 ** to all module implementations.
95634 **
95635 ** Virtual tables methods can set an error message by assigning a
95636 ** string obtained from sqlite3_mprintf() to zErrMsg.  The method should
95637 ** take care that any prior string is freed by a call to sqlite3_free()
95638 ** prior to assigning a new string to zErrMsg.  After the error message
95639 ** is delivered up to the client application, the string will be automatically
95640 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.  Note
95641 ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
95642 ** since virtual tables are commonly implemented in loadable extensions which
95643 ** do not have access to sqlite3MPrintf() or sqlite3Free().
95644 */
95645 struct sqlite3_vtab {
95646   const sqlite3_module *pModule;  /* The module for this virtual table */
95647   int nRef;                       /* Used internally */
95648   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
95649   /* Virtual table implementations will typically add additional fields */
95650 };
95651
95652 /* Every module implementation uses a subclass of the following structure
95653 ** to describe cursors that point into the virtual table and are used
95654 ** to loop through the virtual table.  Cursors are created using the
95655 ** xOpen method of the module.  Each module implementation will define
95656 ** the content of a cursor structure to suit its own needs.
95657 **
95658 ** This superclass exists in order to define fields of the cursor that
95659 ** are common to all implementations.
95660 */
95661 struct sqlite3_vtab_cursor {
95662   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
95663   /* Virtual table implementations will typically add additional fields */
95664 };
95665
95666 /*
95667 ** The xCreate and xConnect methods of a module use the following API
95668 ** to declare the format (the names and datatypes of the columns) of
95669 ** the virtual tables they implement.
95670 */
95671 int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
95672
95673 /*
95674 ** Virtual tables can provide alternative implementations of functions
95675 ** using the xFindFunction method.  But global versions of those functions
95676 ** must exist in order to be overloaded.
95677 **
95678 ** This API makes sure a global version of a function with a particular
95679 ** name and number of parameters exists.  If no such function exists
95680 ** before this API is called, a new function is created.  The implementation
95681 ** of the new function always causes an exception to be thrown.  So
95682 ** the new function is not good for anything by itself.  Its only
95683 ** purpose is to be a place-holder function that can be overloaded
95684 ** by virtual tables.
95685 **
95686 ** This API should be considered part of the virtual table interface,
95687 ** which is experimental and subject to change.
95688 */
95689 int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
95690
95691 /*
95692 ** The interface to the virtual-table mechanism defined above (back up
95693 ** to a comment remarkably similar to this one) is currently considered
95694 ** to be experimental.  The interface might change in incompatible ways.
95695 ** If this is a problem for you, do not use the interface at this time.
95696 **
95697 ** When the virtual-table mechanism stabilizes, we will declare the
95698 ** interface fixed, support it indefinitely, and remove this comment.
95699 **
95700 ****** EXPERIMENTAL - subject to change without notice **************
95701 */
95702
95703 /*
95704 ** CAPI3REF: A Handle To An Open BLOB {F17800}
95705 **
95706 ** An instance of the following opaque structure is used to 
95707 ** represent an blob-handle.  A blob-handle is created by
95708 ** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()].
95709 ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
95710 ** can be used to read or write small subsections of the blob.
95711 ** The [sqlite3_blob_bytes()] interface returns the size of the
95712 ** blob in bytes.
95713 */
95714 typedef struct sqlite3_blob sqlite3_blob;
95715
95716 /*
95717 ** CAPI3REF: Open A BLOB For Incremental I/O {F17810}
95718 **
95719 ** {F17811} This interfaces opens a handle to the blob located
95720 ** in row iRow,, column zColumn, table zTable in database zDb;
95721 ** in other words,  the same blob that would be selected by:
95722 **
95723 ** <pre>
95724 **     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
95725 ** </pre> {END}
95726 **
95727 ** {F17812} If the flags parameter is non-zero, the blob is opened for 
95728 ** read and write access. If it is zero, the blob is opened for read 
95729 ** access. {END}
95730 **
95731 ** {F17813} On success, [SQLITE_OK] is returned and the new 
95732 ** [sqlite3_blob | blob handle] is written to *ppBlob. 
95733 ** {F17814} Otherwise an error code is returned and 
95734 ** any value written to *ppBlob should not be used by the caller.
95735 ** {F17815} This function sets the database-handle error code and message
95736 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()].
95737 ** <todo>We should go through and mark all interfaces that behave this
95738 ** way with a similar statement</todo>
95739 */
95740 int sqlite3_blob_open(
95741   sqlite3*,
95742   const char *zDb,
95743   const char *zTable,
95744   const char *zColumn,
95745   sqlite3_int64 iRow,
95746   int flags,
95747   sqlite3_blob **ppBlob
95748 );
95749
95750 /*
95751 ** CAPI3REF:  Close A BLOB Handle {F17830}
95752 **
95753 ** Close an open [sqlite3_blob | blob handle].
95754 **
95755 ** {F17831} Closing a BLOB shall cause the current transaction to commit
95756 ** if there are no other BLOBs, no pending prepared statements, and the
95757 ** database connection is in autocommit mode.
95758 ** {F17832} If any writes were made to the BLOB, they might be held in cache
95759 ** until the close operation if they will fit. {END}
95760 ** Closing the BLOB often forces the changes
95761 ** out to disk and so if any I/O errors occur, they will likely occur
95762 ** at the time when the BLOB is closed.  {F17833} Any errors that occur during
95763 ** closing are reported as a non-zero return value.
95764 **
95765 ** {F17839} The BLOB is closed unconditionally.  Even if this routine returns
95766 ** an error code, the BLOB is still closed.
95767 */
95768 int sqlite3_blob_close(sqlite3_blob *);
95769
95770 /*
95771 ** CAPI3REF:  Return The Size Of An Open BLOB {F17805}
95772 **
95773 ** {F16806} Return the size in bytes of the blob accessible via the open 
95774 ** [sqlite3_blob | blob-handle] passed as an argument.
95775 */
95776 int sqlite3_blob_bytes(sqlite3_blob *);
95777
95778 /*
95779 ** CAPI3REF:  Read Data From A BLOB Incrementally {F17850}
95780 **
95781 ** This function is used to read data from an open 
95782 ** [sqlite3_blob | blob-handle] into a caller supplied buffer.
95783 ** {F17851} n bytes of data are copied into buffer
95784 ** z from the open blob, starting at offset iOffset.
95785 **
95786 ** {F17852} If offset iOffset is less than n bytes from the end of the blob, 
95787 ** [SQLITE_ERROR] is returned and no data is read.  {F17853} If n is
95788 ** less than zero [SQLITE_ERROR] is returned and no data is read.
95789 **
95790 ** {F17854} On success, SQLITE_OK is returned. Otherwise, an 
95791 ** [SQLITE_ERROR | SQLite error code] or an
95792 ** [SQLITE_IOERR_READ | extended error code] is returned.
95793 */
95794 int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset);
95795
95796 /*
95797 ** CAPI3REF:  Write Data Into A BLOB Incrementally {F17870}
95798 **
95799 ** This function is used to write data into an open 
95800 ** [sqlite3_blob | blob-handle] from a user supplied buffer.
95801 ** {F17871} n bytes of data are copied from the buffer
95802 ** pointed to by z into the open blob, starting at offset iOffset.
95803 **
95804 ** {F17872} If the [sqlite3_blob | blob-handle] passed as the first argument
95805 ** was not opened for writing (the flags parameter to [sqlite3_blob_open()]
95806 *** was zero), this function returns [SQLITE_READONLY].
95807 **
95808 ** {F17873} This function may only modify the contents of the blob; it is
95809 ** not possible to increase the size of a blob using this API.
95810 ** {F17874} If offset iOffset is less than n bytes from the end of the blob, 
95811 ** [SQLITE_ERROR] is returned and no data is written.  {F17875} If n is
95812 ** less than zero [SQLITE_ERROR] is returned and no data is written.
95813 **
95814 ** {F17876} On success, SQLITE_OK is returned. Otherwise, an 
95815 ** [SQLITE_ERROR | SQLite error code] or an
95816 ** [SQLITE_IOERR_READ | extended error code] is returned.
95817 */
95818 int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
95819
95820 /*
95821 ** CAPI3REF:  Virtual File System Objects {F11200}
95822 **
95823 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
95824 ** that SQLite uses to interact
95825 ** with the underlying operating system.  Most builds come with a
95826 ** single default VFS that is appropriate for the host computer.
95827 ** New VFSes can be registered and existing VFSes can be unregistered.
95828 ** The following interfaces are provided.
95829 **
95830 ** {F11201} The sqlite3_vfs_find() interface returns a pointer to 
95831 ** a VFS given its name.  {F11202} Names are case sensitive.
95832 ** {F11203} Names are zero-terminated UTF-8 strings.
95833 ** {F11204} If there is no match, a NULL
95834 ** pointer is returned. {F11205} If zVfsName is NULL then the default 
95835 ** VFS is returned. {END}
95836 **
95837 ** {F11210} New VFSes are registered with sqlite3_vfs_register().
95838 ** {F11211} Each new VFS becomes the default VFS if the makeDflt flag is set.
95839 ** {F11212} The same VFS can be registered multiple times without injury.
95840 ** {F11213} To make an existing VFS into the default VFS, register it again
95841 ** with the makeDflt flag set. {U11214} If two different VFSes with the
95842 ** same name are registered, the behavior is undefined.  {U11215} If a
95843 ** VFS is registered with a name that is NULL or an empty string,
95844 ** then the behavior is undefined.
95845 ** 
95846 ** {F11220} Unregister a VFS with the sqlite3_vfs_unregister() interface.
95847 ** {F11221} If the default VFS is unregistered, another VFS is chosen as
95848 ** the default.  The choice for the new VFS is arbitrary.
95849 */
95850 sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
95851 int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
95852 int sqlite3_vfs_unregister(sqlite3_vfs*);
95853
95854 /*
95855 ** CAPI3REF: Mutexes {F17000}
95856 **
95857 ** The SQLite core uses these routines for thread
95858 ** synchronization.  Though they are intended for internal
95859 ** use by SQLite, code that links against SQLite is
95860 ** permitted to use any of these routines.
95861 **
95862 ** The SQLite source code contains multiple implementations 
95863 ** of these mutex routines.  An appropriate implementation
95864 ** is selected automatically at compile-time.  The following
95865 ** implementations are available in the SQLite core:
95866 **
95867 ** <ul>
95868 ** <li>   SQLITE_MUTEX_OS2
95869 ** <li>   SQLITE_MUTEX_PTHREAD
95870 ** <li>   SQLITE_MUTEX_W32
95871 ** <li>   SQLITE_MUTEX_NOOP
95872 ** </ul>
95873 **
95874 ** The SQLITE_MUTEX_NOOP implementation is a set of routines 
95875 ** that does no real locking and is appropriate for use in 
95876 ** a single-threaded application.  The SQLITE_MUTEX_OS2,
95877 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
95878 ** are appropriate for use on os/2, unix, and windows.
95879 ** 
95880 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
95881 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
95882 ** implementation is included with the library.  The
95883 ** mutex interface routines defined here become external
95884 ** references in the SQLite library for which implementations
95885 ** must be provided by the application.  This facility allows an
95886 ** application that links against SQLite to provide its own mutex
95887 ** implementation without having to modify the SQLite core.
95888 **
95889 ** {F17011} The sqlite3_mutex_alloc() routine allocates a new
95890 ** mutex and returns a pointer to it. {F17012} If it returns NULL
95891 ** that means that a mutex could not be allocated. {F17013} SQLite
95892 ** will unwind its stack and return an error. {F17014} The argument
95893 ** to sqlite3_mutex_alloc() is one of these integer constants:
95894 **
95895 ** <ul>
95896 ** <li>  SQLITE_MUTEX_FAST
95897 ** <li>  SQLITE_MUTEX_RECURSIVE
95898 ** <li>  SQLITE_MUTEX_STATIC_MASTER
95899 ** <li>  SQLITE_MUTEX_STATIC_MEM
95900 ** <li>  SQLITE_MUTEX_STATIC_MEM2
95901 ** <li>  SQLITE_MUTEX_STATIC_PRNG
95902 ** <li>  SQLITE_MUTEX_STATIC_LRU
95903 ** </ul> {END}
95904 **
95905 ** {F17015} The first two constants cause sqlite3_mutex_alloc() to create
95906 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
95907 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END}
95908 ** The mutex implementation does not need to make a distinction
95909 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
95910 ** not want to.  {F17016} But SQLite will only request a recursive mutex in
95911 ** cases where it really needs one.  {END} If a faster non-recursive mutex
95912 ** implementation is available on the host platform, the mutex subsystem
95913 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
95914 **
95915 ** {F17017} The other allowed parameters to sqlite3_mutex_alloc() each return
95916 ** a pointer to a static preexisting mutex. {END}  Four static mutexes are
95917 ** used by the current version of SQLite.  Future versions of SQLite
95918 ** may add additional static mutexes.  Static mutexes are for internal
95919 ** use by SQLite only.  Applications that use SQLite mutexes should
95920 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
95921 ** SQLITE_MUTEX_RECURSIVE.
95922 **
95923 ** {F17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
95924 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
95925 ** returns a different mutex on every call.  {F17034} But for the static 
95926 ** mutex types, the same mutex is returned on every call that has
95927 ** the same type number. {END}
95928 **
95929 ** {F17019} The sqlite3_mutex_free() routine deallocates a previously
95930 ** allocated dynamic mutex. {F17020} SQLite is careful to deallocate every
95931 ** dynamic mutex that it allocates. {U17021} The dynamic mutexes must not be in 
95932 ** use when they are deallocated. {U17022} Attempting to deallocate a static
95933 ** mutex results in undefined behavior. {F17023} SQLite never deallocates
95934 ** a static mutex. {END}
95935 **
95936 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
95937 ** to enter a mutex. {F17024} If another thread is already within the mutex,
95938 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
95939 ** SQLITE_BUSY. {F17025}  The sqlite3_mutex_try() interface returns SQLITE_OK
95940 ** upon successful entry.  {F17026} Mutexes created using
95941 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
95942 ** {F17027} In such cases the,
95943 ** mutex must be exited an equal number of times before another thread
95944 ** can enter.  {U17028} If the same thread tries to enter any other
95945 ** kind of mutex more than once, the behavior is undefined.
95946 ** {F17029} SQLite will never exhibit
95947 ** such behavior in its own use of mutexes. {END}
95948 **
95949 ** Some systems (ex: windows95) do not the operation implemented by
95950 ** sqlite3_mutex_try().  On those systems, sqlite3_mutex_try() will
95951 ** always return SQLITE_BUSY.  {F17030} The SQLite core only ever uses
95952 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior. {END}
95953 **
95954 ** {F17031} The sqlite3_mutex_leave() routine exits a mutex that was
95955 ** previously entered by the same thread.  {U17032} The behavior
95956 ** is undefined if the mutex is not currently entered by the
95957 ** calling thread or is not currently allocated.  {F17033} SQLite will
95958 ** never do either. {END}
95959 **
95960 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
95961 */
95962 sqlite3_mutex *sqlite3_mutex_alloc(int);
95963 void sqlite3_mutex_free(sqlite3_mutex*);
95964 void sqlite3_mutex_enter(sqlite3_mutex*);
95965 int sqlite3_mutex_try(sqlite3_mutex*);
95966 void sqlite3_mutex_leave(sqlite3_mutex*);
95967
95968 /*
95969 ** CAPI3REF: Mutex Verifcation Routines {F17080}
95970 **
95971 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
95972 ** are intended for use inside assert() statements. {F17081} The SQLite core
95973 ** never uses these routines except inside an assert() and applications
95974 ** are advised to follow the lead of the core.  {F17082} The core only
95975 ** provides implementations for these routines when it is compiled
95976 ** with the SQLITE_DEBUG flag.  {U17087} External mutex implementations
95977 ** are only required to provide these routines if SQLITE_DEBUG is
95978 ** defined and if NDEBUG is not defined.
95979 **
95980 ** {F17083} These routines should return true if the mutex in their argument
95981 ** is held or not held, respectively, by the calling thread. {END}
95982 **
95983 ** {X17084} The implementation is not required to provided versions of these
95984 ** routines that actually work.
95985 ** If the implementation does not provide working
95986 ** versions of these routines, it should at least provide stubs
95987 ** that always return true so that one does not get spurious
95988 ** assertion failures. {END}
95989 **
95990 ** {F17085} If the argument to sqlite3_mutex_held() is a NULL pointer then
95991 ** the routine should return 1.  {END} This seems counter-intuitive since
95992 ** clearly the mutex cannot be held if it does not exist.  But the
95993 ** the reason the mutex does not exist is because the build is not
95994 ** using mutexes.  And we do not want the assert() containing the
95995 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
95996 ** the appropriate thing to do.  {F17086} The sqlite3_mutex_notheld() 
95997 ** interface should also return 1 when given a NULL pointer.
95998 */
95999 int sqlite3_mutex_held(sqlite3_mutex*);
96000 int sqlite3_mutex_notheld(sqlite3_mutex*);
96001
96002 /*
96003 ** CAPI3REF: Mutex Types {F17001}
96004 **
96005 ** {F17002} The [sqlite3_mutex_alloc()] interface takes a single argument
96006 ** which is one of these integer constants. {END}
96007 */
96008 #define SQLITE_MUTEX_FAST             0
96009 #define SQLITE_MUTEX_RECURSIVE        1
96010 #define SQLITE_MUTEX_STATIC_MASTER    2
96011 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
96012 #define SQLITE_MUTEX_STATIC_MEM2      4  /* sqlite3_release_memory() */
96013 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
96014 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
96015
96016 /*
96017 ** CAPI3REF: Low-Level Control Of Database Files {F11300}
96018 **
96019 ** {F11301} The [sqlite3_file_control()] interface makes a direct call to the
96020 ** xFileControl method for the [sqlite3_io_methods] object associated
96021 ** with a particular database identified by the second argument. {F11302} The
96022 ** name of the database is the name assigned to the database by the
96023 ** <a href="lang_attach.html">ATTACH</a> SQL command that opened the
96024 ** database. {F11303} To control the main database file, use the name "main"
96025 ** or a NULL pointer. {F11304} The third and fourth parameters to this routine
96026 ** are passed directly through to the second and third parameters of
96027 ** the xFileControl method.  {F11305} The return value of the xFileControl
96028 ** method becomes the return value of this routine.
96029 **
96030 ** {F11306} If the second parameter (zDbName) does not match the name of any
96031 ** open database file, then SQLITE_ERROR is returned. {F11307} This error
96032 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
96033 ** or [sqlite3_errmsg()]. {U11308} The underlying xFileControl method might
96034 ** also return SQLITE_ERROR.  {U11309} There is no way to distinguish between
96035 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
96036 ** xFileControl method. {END}
96037 **
96038 ** See also: [SQLITE_FCNTL_LOCKSTATE]
96039 */
96040 int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
96041
96042 /*
96043 ** Undo the hack that converts floating point types to integer for
96044 ** builds on processors without floating point support.
96045 */
96046 #ifdef SQLITE_OMIT_FLOATING_POINT
96047 # undef double
96048 #endif
96049
96050 #if 0
96051 }  /* End of the 'extern "C"' block */
96052 #endif
96053 #endif
96054
96055 /************** End of sqlite3.h *********************************************/
96056 /************** Continuing where we left off in fts3_tokenizer.h *************/
96057
96058 /*
96059 ** Structures used by the tokenizer interface. When a new tokenizer
96060 ** implementation is registered, the caller provides a pointer to
96061 ** an sqlite3_tokenizer_module containing pointers to the callback
96062 ** functions that make up an implementation.
96063 **
96064 ** When an fts3 table is created, it passes any arguments passed to
96065 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
96066 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
96067 ** implementation. The xCreate() function in turn returns an 
96068 ** sqlite3_tokenizer structure representing the specific tokenizer to
96069 ** be used for the fts3 table (customized by the tokenizer clause arguments).
96070 **
96071 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
96072 ** method is called. It returns an sqlite3_tokenizer_cursor object
96073 ** that may be used to tokenize a specific input buffer based on
96074 ** the tokenization rules supplied by a specific sqlite3_tokenizer
96075 ** object.
96076 */
96077 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
96078 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
96079 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
96080
96081 struct sqlite3_tokenizer_module {
96082
96083   /*
96084   ** Structure version. Should always be set to 0.
96085   */
96086   int iVersion;
96087
96088   /*
96089   ** Create a new tokenizer. The values in the argv[] array are the
96090   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
96091   ** TABLE statement that created the fts3 table. For example, if
96092   ** the following SQL is executed:
96093   **
96094   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
96095   **
96096   ** then argc is set to 2, and the argv[] array contains pointers
96097   ** to the strings "arg1" and "arg2".
96098   **
96099   ** This method should return either SQLITE_OK (0), or an SQLite error 
96100   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
96101   ** to point at the newly created tokenizer structure. The generic
96102   ** sqlite3_tokenizer.pModule variable should not be initialised by
96103   ** this callback. The caller will do so.
96104   */
96105   int (*xCreate)(
96106     int argc,                           /* Size of argv array */
96107     const char *const*argv,             /* Tokenizer argument strings */
96108     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
96109   );
96110
96111   /*
96112   ** Destroy an existing tokenizer. The fts3 module calls this method
96113   ** exactly once for each successful call to xCreate().
96114   */
96115   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
96116
96117   /*
96118   ** Create a tokenizer cursor to tokenize an input buffer. The caller
96119   ** is responsible for ensuring that the input buffer remains valid
96120   ** until the cursor is closed (using the xClose() method). 
96121   */
96122   int (*xOpen)(
96123     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
96124     const char *pInput, int nBytes,      /* Input buffer */
96125     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
96126   );
96127
96128   /*
96129   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
96130   ** method exactly once for each successful call to xOpen().
96131   */
96132   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
96133
96134   /*
96135   ** Retrieve the next token from the tokenizer cursor pCursor. This
96136   ** method should either return SQLITE_OK and set the values of the
96137   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
96138   ** the end of the buffer has been reached, or an SQLite error code.
96139   **
96140   ** *ppToken should be set to point at a buffer containing the 
96141   ** normalized version of the token (i.e. after any case-folding and/or
96142   ** stemming has been performed). *pnBytes should be set to the length
96143   ** of this buffer in bytes. The input text that generated the token is
96144   ** identified by the byte offsets returned in *piStartOffset and
96145   ** *piEndOffset.
96146   **
96147   ** The buffer *ppToken is set to point at is managed by the tokenizer
96148   ** implementation. It is only required to be valid until the next call
96149   ** to xNext() or xClose(). 
96150   */
96151   /* TODO(shess) current implementation requires pInput to be
96152   ** nul-terminated.  This should either be fixed, or pInput/nBytes
96153   ** should be converted to zInput.
96154   */
96155   int (*xNext)(
96156     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
96157     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
96158     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
96159     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
96160     int *piPosition      /* OUT: Number of tokens returned before this one */
96161   );
96162 };
96163
96164 struct sqlite3_tokenizer {
96165   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
96166   /* Tokenizer implementations will typically add additional fields */
96167 };
96168
96169 struct sqlite3_tokenizer_cursor {
96170   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
96171   /* Tokenizer implementations will typically add additional fields */
96172 };
96173
96174 #endif /* _FTS3_TOKENIZER_H_ */
96175
96176 /************** End of fts3_tokenizer.h **************************************/
96177 /************** Continuing where we left off in fts3_porter.c ****************/
96178
96179 /*
96180 ** Class derived from sqlite3_tokenizer
96181 */
96182 typedef struct porter_tokenizer {
96183   sqlite3_tokenizer base;      /* Base class */
96184 } porter_tokenizer;
96185
96186 /*
96187 ** Class derived from sqlit3_tokenizer_cursor
96188 */
96189 typedef struct porter_tokenizer_cursor {
96190   sqlite3_tokenizer_cursor base;
96191   const char *zInput;          /* input we are tokenizing */
96192   int nInput;                  /* size of the input */
96193   int iOffset;                 /* current position in zInput */
96194   int iToken;                  /* index of next token to be returned */
96195   char *zToken;                /* storage for current token */
96196   int nAllocated;              /* space allocated to zToken buffer */
96197 } porter_tokenizer_cursor;
96198
96199
96200 /* Forward declaration */
96201 static const sqlite3_tokenizer_module porterTokenizerModule;
96202
96203
96204 /*
96205 ** Create a new tokenizer instance.
96206 */
96207 static int porterCreate(
96208   int argc, const char * const *argv,
96209   sqlite3_tokenizer **ppTokenizer
96210 ){
96211   porter_tokenizer *t;
96212   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
96213   if( t==NULL ) return SQLITE_NOMEM;
96214   memset(t, 0, sizeof(*t));
96215   *ppTokenizer = &t->base;
96216   return SQLITE_OK;
96217 }
96218
96219 /*
96220 ** Destroy a tokenizer
96221 */
96222 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
96223   sqlite3_free(pTokenizer);
96224   return SQLITE_OK;
96225 }
96226
96227 /*
96228 ** Prepare to begin tokenizing a particular string.  The input
96229 ** string to be tokenized is zInput[0..nInput-1].  A cursor
96230 ** used to incrementally tokenize this string is returned in 
96231 ** *ppCursor.
96232 */
96233 static int porterOpen(
96234   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
96235   const char *zInput, int nInput,        /* String to be tokenized */
96236   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
96237 ){
96238   porter_tokenizer_cursor *c;
96239
96240   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
96241   if( c==NULL ) return SQLITE_NOMEM;
96242
96243   c->zInput = zInput;
96244   if( zInput==0 ){
96245     c->nInput = 0;
96246   }else if( nInput<0 ){
96247     c->nInput = (int)strlen(zInput);
96248   }else{
96249     c->nInput = nInput;
96250   }
96251   c->iOffset = 0;                 /* start tokenizing at the beginning */
96252   c->iToken = 0;
96253   c->zToken = NULL;               /* no space allocated, yet. */
96254   c->nAllocated = 0;
96255
96256   *ppCursor = &c->base;
96257   return SQLITE_OK;
96258 }
96259
96260 /*
96261 ** Close a tokenization cursor previously opened by a call to
96262 ** porterOpen() above.
96263 */
96264 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
96265   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
96266   sqlite3_free(c->zToken);
96267   sqlite3_free(c);
96268   return SQLITE_OK;
96269 }
96270 /*
96271 ** Vowel or consonant
96272 */
96273 static const char cType[] = {
96274    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
96275    1, 1, 1, 2, 1
96276 };
96277
96278 /*
96279 ** isConsonant() and isVowel() determine if their first character in
96280 ** the string they point to is a consonant or a vowel, according
96281 ** to Porter ruls.  
96282 **
96283 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
96284 ** 'Y' is a consonant unless it follows another consonant,
96285 ** in which case it is a vowel.
96286 **
96287 ** In these routine, the letters are in reverse order.  So the 'y' rule
96288 ** is that 'y' is a consonant unless it is followed by another
96289 ** consonent.
96290 */
96291 static int isVowel(const char*);
96292 static int isConsonant(const char *z){
96293   int j;
96294   char x = *z;
96295   if( x==0 ) return 0;
96296   assert( x>='a' && x<='z' );
96297   j = cType[x-'a'];
96298   if( j<2 ) return j;
96299   return z[1]==0 || isVowel(z + 1);
96300 }
96301 static int isVowel(const char *z){
96302   int j;
96303   char x = *z;
96304   if( x==0 ) return 0;
96305   assert( x>='a' && x<='z' );
96306   j = cType[x-'a'];
96307   if( j<2 ) return 1-j;
96308   return isConsonant(z + 1);
96309 }
96310
96311 /*
96312 ** Let any sequence of one or more vowels be represented by V and let
96313 ** C be sequence of one or more consonants.  Then every word can be
96314 ** represented as:
96315 **
96316 **           [C] (VC){m} [V]
96317 **
96318 ** In prose:  A word is an optional consonant followed by zero or
96319 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
96320 ** number of vowel consonant pairs.  This routine computes the value
96321 ** of m for the first i bytes of a word.
96322 **
96323 ** Return true if the m-value for z is 1 or more.  In other words,
96324 ** return true if z contains at least one vowel that is followed
96325 ** by a consonant.
96326 **
96327 ** In this routine z[] is in reverse order.  So we are really looking
96328 ** for an instance of of a consonant followed by a vowel.
96329 */
96330 static int m_gt_0(const char *z){
96331   while( isVowel(z) ){ z++; }
96332   if( *z==0 ) return 0;
96333   while( isConsonant(z) ){ z++; }
96334   return *z!=0;
96335 }
96336
96337 /* Like mgt0 above except we are looking for a value of m which is
96338 ** exactly 1
96339 */
96340 static int m_eq_1(const char *z){
96341   while( isVowel(z) ){ z++; }
96342   if( *z==0 ) return 0;
96343   while( isConsonant(z) ){ z++; }
96344   if( *z==0 ) return 0;
96345   while( isVowel(z) ){ z++; }
96346   if( *z==0 ) return 1;
96347   while( isConsonant(z) ){ z++; }
96348   return *z==0;
96349 }
96350
96351 /* Like mgt0 above except we are looking for a value of m>1 instead
96352 ** or m>0
96353 */
96354 static int m_gt_1(const char *z){
96355   while( isVowel(z) ){ z++; }
96356   if( *z==0 ) return 0;
96357   while( isConsonant(z) ){ z++; }
96358   if( *z==0 ) return 0;
96359   while( isVowel(z) ){ z++; }
96360   if( *z==0 ) return 0;
96361   while( isConsonant(z) ){ z++; }
96362   return *z!=0;
96363 }
96364
96365 /*
96366 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
96367 */
96368 static int hasVowel(const char *z){
96369   while( isConsonant(z) ){ z++; }
96370   return *z!=0;
96371 }
96372
96373 /*
96374 ** Return TRUE if the word ends in a double consonant.
96375 **
96376 ** The text is reversed here. So we are really looking at
96377 ** the first two characters of z[].
96378 */
96379 static int doubleConsonant(const char *z){
96380   return isConsonant(z) && z[0]==z[1] && isConsonant(z+1);
96381 }
96382
96383 /*
96384 ** Return TRUE if the word ends with three letters which
96385 ** are consonant-vowel-consonent and where the final consonant
96386 ** is not 'w', 'x', or 'y'.
96387 **
96388 ** The word is reversed here.  So we are really checking the
96389 ** first three letters and the first one cannot be in [wxy].
96390 */
96391 static int star_oh(const char *z){
96392   return
96393     z[0]!=0 && isConsonant(z) &&
96394     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
96395     z[1]!=0 && isVowel(z+1) &&
96396     z[2]!=0 && isConsonant(z+2);
96397 }
96398
96399 /*
96400 ** If the word ends with zFrom and xCond() is true for the stem
96401 ** of the word that preceeds the zFrom ending, then change the 
96402 ** ending to zTo.
96403 **
96404 ** The input word *pz and zFrom are both in reverse order.  zTo
96405 ** is in normal order. 
96406 **
96407 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
96408 ** match.  Not that TRUE is returned even if xCond() fails and
96409 ** no substitution occurs.
96410 */
96411 static int stem(
96412   char **pz,             /* The word being stemmed (Reversed) */
96413   const char *zFrom,     /* If the ending matches this... (Reversed) */
96414   const char *zTo,       /* ... change the ending to this (not reversed) */
96415   int (*xCond)(const char*)   /* Condition that must be true */
96416 ){
96417   char *z = *pz;
96418   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
96419   if( *zFrom!=0 ) return 0;
96420   if( xCond && !xCond(z) ) return 1;
96421   while( *zTo ){
96422     *(--z) = *(zTo++);
96423   }
96424   *pz = z;
96425   return 1;
96426 }
96427
96428 /*
96429 ** This is the fallback stemmer used when the porter stemmer is
96430 ** inappropriate.  The input word is copied into the output with
96431 ** US-ASCII case folding.  If the input word is too long (more
96432 ** than 20 bytes if it contains no digits or more than 6 bytes if
96433 ** it contains digits) then word is truncated to 20 or 6 bytes
96434 ** by taking 10 or 3 bytes from the beginning and end.
96435 */
96436 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
96437   int i, mx, j;
96438   int hasDigit = 0;
96439   for(i=0; i<nIn; i++){
96440     int c = zIn[i];
96441     if( c>='A' && c<='Z' ){
96442       zOut[i] = c - 'A' + 'a';
96443     }else{
96444       if( c>='0' && c<='9' ) hasDigit = 1;
96445       zOut[i] = c;
96446     }
96447   }
96448   mx = hasDigit ? 3 : 10;
96449   if( nIn>mx*2 ){
96450     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
96451       zOut[j] = zOut[i];
96452     }
96453     i = j;
96454   }
96455   zOut[i] = 0;
96456   *pnOut = i;
96457 }
96458
96459
96460 /*
96461 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
96462 ** zOut is at least big enough to hold nIn bytes.  Write the actual
96463 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
96464 **
96465 ** Any upper-case characters in the US-ASCII character set ([A-Z])
96466 ** are converted to lower case.  Upper-case UTF characters are
96467 ** unchanged.
96468 **
96469 ** Words that are longer than about 20 bytes are stemmed by retaining
96470 ** a few bytes from the beginning and the end of the word.  If the
96471 ** word contains digits, 3 bytes are taken from the beginning and
96472 ** 3 bytes from the end.  For long words without digits, 10 bytes
96473 ** are taken from each end.  US-ASCII case folding still applies.
96474 ** 
96475 ** If the input word contains not digits but does characters not 
96476 ** in [a-zA-Z] then no stemming is attempted and this routine just 
96477 ** copies the input into the input into the output with US-ASCII
96478 ** case folding.
96479 **
96480 ** Stemming never increases the length of the word.  So there is
96481 ** no chance of overflowing the zOut buffer.
96482 */
96483 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
96484   int i, j, c;
96485   char zReverse[28];
96486   char *z, *z2;
96487   if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
96488     /* The word is too big or too small for the porter stemmer.
96489     ** Fallback to the copy stemmer */
96490     copy_stemmer(zIn, nIn, zOut, pnOut);
96491     return;
96492   }
96493   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
96494     c = zIn[i];
96495     if( c>='A' && c<='Z' ){
96496       zReverse[j] = c + 'a' - 'A';
96497     }else if( c>='a' && c<='z' ){
96498       zReverse[j] = c;
96499     }else{
96500       /* The use of a character not in [a-zA-Z] means that we fallback
96501       ** to the copy stemmer */
96502       copy_stemmer(zIn, nIn, zOut, pnOut);
96503       return;
96504     }
96505   }
96506   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
96507   z = &zReverse[j+1];
96508
96509
96510   /* Step 1a */
96511   if( z[0]=='s' ){
96512     if(
96513      !stem(&z, "sess", "ss", 0) &&
96514      !stem(&z, "sei", "i", 0)  &&
96515      !stem(&z, "ss", "ss", 0)
96516     ){
96517       z++;
96518     }
96519   }
96520
96521   /* Step 1b */  
96522   z2 = z;
96523   if( stem(&z, "dee", "ee", m_gt_0) ){
96524     /* Do nothing.  The work was all in the test */
96525   }else if( 
96526      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
96527       && z!=z2
96528   ){
96529      if( stem(&z, "ta", "ate", 0) ||
96530          stem(&z, "lb", "ble", 0) ||
96531          stem(&z, "zi", "ize", 0) ){
96532        /* Do nothing.  The work was all in the test */
96533      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
96534        z++;
96535      }else if( m_eq_1(z) && star_oh(z) ){
96536        *(--z) = 'e';
96537      }
96538   }
96539
96540   /* Step 1c */
96541   if( z[0]=='y' && hasVowel(z+1) ){
96542     z[0] = 'i';
96543   }
96544
96545   /* Step 2 */
96546   switch( z[1] ){
96547    case 'a':
96548      stem(&z, "lanoita", "ate", m_gt_0) ||
96549      stem(&z, "lanoit", "tion", m_gt_0);
96550      break;
96551    case 'c':
96552      stem(&z, "icne", "ence", m_gt_0) ||
96553      stem(&z, "icna", "ance", m_gt_0);
96554      break;
96555    case 'e':
96556      stem(&z, "rezi", "ize", m_gt_0);
96557      break;
96558    case 'g':
96559      stem(&z, "igol", "log", m_gt_0);
96560      break;
96561    case 'l':
96562      stem(&z, "ilb", "ble", m_gt_0) ||
96563      stem(&z, "illa", "al", m_gt_0) ||
96564      stem(&z, "iltne", "ent", m_gt_0) ||
96565      stem(&z, "ile", "e", m_gt_0) ||
96566      stem(&z, "ilsuo", "ous", m_gt_0);
96567      break;
96568    case 'o':
96569      stem(&z, "noitazi", "ize", m_gt_0) ||
96570      stem(&z, "noita", "ate", m_gt_0) ||
96571      stem(&z, "rota", "ate", m_gt_0);
96572      break;
96573    case 's':
96574      stem(&z, "msila", "al", m_gt_0) ||
96575      stem(&z, "ssenevi", "ive", m_gt_0) ||
96576      stem(&z, "ssenluf", "ful", m_gt_0) ||
96577      stem(&z, "ssensuo", "ous", m_gt_0);
96578      break;
96579    case 't':
96580      stem(&z, "itila", "al", m_gt_0) ||
96581      stem(&z, "itivi", "ive", m_gt_0) ||
96582      stem(&z, "itilib", "ble", m_gt_0);
96583      break;
96584   }
96585
96586   /* Step 3 */
96587   switch( z[0] ){
96588    case 'e':
96589      stem(&z, "etaci", "ic", m_gt_0) ||
96590      stem(&z, "evita", "", m_gt_0)   ||
96591      stem(&z, "ezila", "al", m_gt_0);
96592      break;
96593    case 'i':
96594      stem(&z, "itici", "ic", m_gt_0);
96595      break;
96596    case 'l':
96597      stem(&z, "laci", "ic", m_gt_0) ||
96598      stem(&z, "luf", "", m_gt_0);
96599      break;
96600    case 's':
96601      stem(&z, "ssen", "", m_gt_0);
96602      break;
96603   }
96604
96605   /* Step 4 */
96606   switch( z[1] ){
96607    case 'a':
96608      if( z[0]=='l' && m_gt_1(z+2) ){
96609        z += 2;
96610      }
96611      break;
96612    case 'c':
96613      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
96614        z += 4;
96615      }
96616      break;
96617    case 'e':
96618      if( z[0]=='r' && m_gt_1(z+2) ){
96619        z += 2;
96620      }
96621      break;
96622    case 'i':
96623      if( z[0]=='c' && m_gt_1(z+2) ){
96624        z += 2;
96625      }
96626      break;
96627    case 'l':
96628      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
96629        z += 4;
96630      }
96631      break;
96632    case 'n':
96633      if( z[0]=='t' ){
96634        if( z[2]=='a' ){
96635          if( m_gt_1(z+3) ){
96636            z += 3;
96637          }
96638        }else if( z[2]=='e' ){
96639          stem(&z, "tneme", "", m_gt_1) ||
96640          stem(&z, "tnem", "", m_gt_1) ||
96641          stem(&z, "tne", "", m_gt_1);
96642        }
96643      }
96644      break;
96645    case 'o':
96646      if( z[0]=='u' ){
96647        if( m_gt_1(z+2) ){
96648          z += 2;
96649        }
96650      }else if( z[3]=='s' || z[3]=='t' ){
96651        stem(&z, "noi", "", m_gt_1);
96652      }
96653      break;
96654    case 's':
96655      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
96656        z += 3;
96657      }
96658      break;
96659    case 't':
96660      stem(&z, "eta", "", m_gt_1) ||
96661      stem(&z, "iti", "", m_gt_1);
96662      break;
96663    case 'u':
96664      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
96665        z += 3;
96666      }
96667      break;
96668    case 'v':
96669    case 'z':
96670      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
96671        z += 3;
96672      }
96673      break;
96674   }
96675
96676   /* Step 5a */
96677   if( z[0]=='e' ){
96678     if( m_gt_1(z+1) ){
96679       z++;
96680     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
96681       z++;
96682     }
96683   }
96684
96685   /* Step 5b */
96686   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
96687     z++;
96688   }
96689
96690   /* z[] is now the stemmed word in reverse order.  Flip it back
96691   ** around into forward order and return.
96692   */
96693   *pnOut = i = strlen(z);
96694   zOut[i] = 0;
96695   while( *z ){
96696     zOut[--i] = *(z++);
96697   }
96698 }
96699
96700 /*
96701 ** Characters that can be part of a token.  We assume any character
96702 ** whose value is greater than 0x80 (any UTF character) can be
96703 ** part of a token.  In other words, delimiters all must have
96704 ** values of 0x7f or lower.
96705 */
96706 static const char porterIdChar[] = {
96707 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
96708     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
96709     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
96710     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
96711     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
96712     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
96713 };
96714 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
96715
96716 /*
96717 ** Extract the next token from a tokenization cursor.  The cursor must
96718 ** have been opened by a prior call to porterOpen().
96719 */
96720 static int porterNext(
96721   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
96722   const char **pzToken,               /* OUT: *pzToken is the token text */
96723   int *pnBytes,                       /* OUT: Number of bytes in token */
96724   int *piStartOffset,                 /* OUT: Starting offset of token */
96725   int *piEndOffset,                   /* OUT: Ending offset of token */
96726   int *piPosition                     /* OUT: Position integer of token */
96727 ){
96728   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
96729   const char *z = c->zInput;
96730
96731   while( c->iOffset<c->nInput ){
96732     int iStartOffset, ch;
96733
96734     /* Scan past delimiter characters */
96735     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
96736       c->iOffset++;
96737     }
96738
96739     /* Count non-delimiter characters. */
96740     iStartOffset = c->iOffset;
96741     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
96742       c->iOffset++;
96743     }
96744
96745     if( c->iOffset>iStartOffset ){
96746       int n = c->iOffset-iStartOffset;
96747       if( n>c->nAllocated ){
96748         c->nAllocated = n+20;
96749         c->zToken = sqlite3_realloc(c->zToken, c->nAllocated);
96750         if( c->zToken==NULL ) return SQLITE_NOMEM;
96751       }
96752       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
96753       *pzToken = c->zToken;
96754       *piStartOffset = iStartOffset;
96755       *piEndOffset = c->iOffset;
96756       *piPosition = c->iToken++;
96757       return SQLITE_OK;
96758     }
96759   }
96760   return SQLITE_DONE;
96761 }
96762
96763 /*
96764 ** The set of routines that implement the porter-stemmer tokenizer
96765 */
96766 static const sqlite3_tokenizer_module porterTokenizerModule = {
96767   0,
96768   porterCreate,
96769   porterDestroy,
96770   porterOpen,
96771   porterClose,
96772   porterNext,
96773 };
96774
96775 /*
96776 ** Allocate a new porter tokenizer.  Return a pointer to the new
96777 ** tokenizer in *ppModule
96778 */
96779 void sqlite3Fts3PorterTokenizerModule(
96780   sqlite3_tokenizer_module const**ppModule
96781 ){
96782   *ppModule = &porterTokenizerModule;
96783 }
96784
96785 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
96786
96787 /************** End of fts3_porter.c *****************************************/
96788 /************** Begin file fts3_tokenizer.c **********************************/
96789 /*
96790 ** 2007 June 22
96791 **
96792 ** The author disclaims copyright to this source code.  In place of
96793 ** a legal notice, here is a blessing:
96794 **
96795 **    May you do good and not evil.
96796 **    May you find forgiveness for yourself and forgive others.
96797 **    May you share freely, never taking more than you give.
96798 **
96799 ******************************************************************************
96800 **
96801 ** This is part of an SQLite module implementing full-text search.
96802 ** This particular file implements the generic tokenizer interface.
96803 */
96804
96805 /*
96806 ** The code in this file is only compiled if:
96807 **
96808 **     * The FTS3 module is being built as an extension
96809 **       (in which case SQLITE_CORE is not defined), or
96810 **
96811 **     * The FTS3 module is being built into the core of
96812 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
96813 */
96814 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
96815
96816 /************** Include sqlite3ext.h in the middle of fts3_tokenizer.c *******/
96817 /************** Begin file sqlite3ext.h **************************************/
96818 /*
96819 ** 2006 June 7
96820 **
96821 ** The author disclaims copyright to this source code.  In place of
96822 ** a legal notice, here is a blessing:
96823 **
96824 **    May you do good and not evil.
96825 **    May you find forgiveness for yourself and forgive others.
96826 **    May you share freely, never taking more than you give.
96827 **
96828 *************************************************************************
96829 ** This header file defines the SQLite interface for use by
96830 ** shared libraries that want to be imported as extensions into
96831 ** an SQLite instance.  Shared libraries that intend to be loaded
96832 ** as extensions by SQLite should #include this file instead of 
96833 ** sqlite3.h.
96834 **
96835 ** @(#) $Id: sqlite3ext.h,v 1.17 2007/08/31 16:11:36 drh Exp $
96836 */
96837 #ifndef _SQLITE3EXT_H_
96838 #define _SQLITE3EXT_H_
96839 /************** Include sqlite3.h in the middle of sqlite3ext.h **************/
96840 /************** Begin file sqlite3.h *****************************************/
96841 /*
96842 ** 2001 September 15
96843 **
96844 ** The author disclaims copyright to this source code.  In place of
96845 ** a legal notice, here is a blessing:
96846 **
96847 **    May you do good and not evil.
96848 **    May you find forgiveness for yourself and forgive others.
96849 **    May you share freely, never taking more than you give.
96850 **
96851 *************************************************************************
96852 ** This header file defines the interface that the SQLite library
96853 ** presents to client programs.  If a C-function, structure, datatype,
96854 ** or constant definition does not appear in this file, then it is
96855 ** not a published API of SQLite, is subject to change without
96856 ** notice, and should not be referenced by programs that use SQLite.
96857 **
96858 ** Some of the definitions that are in this file are marked as
96859 ** "experimental".  Experimental interfaces are normally new
96860 ** features recently added to SQLite.  We do not anticipate changes 
96861 ** to experimental interfaces but reserve to make minor changes if
96862 ** experience from use "in the wild" suggest such changes are prudent.
96863 **
96864 ** The official C-language API documentation for SQLite is derived
96865 ** from comments in this file.  This file is the authoritative source
96866 ** on how SQLite interfaces are suppose to operate.
96867 **
96868 ** The name of this file under configuration management is "sqlite.h.in".
96869 ** The makefile makes some minor changes to this file (such as inserting
96870 ** the version number) and changes its name to "sqlite3.h" as
96871 ** part of the build process.
96872 **
96873 ** @(#) $Id: sqlite.h.in,v 1.278 2007/12/13 21:54:11 drh Exp $
96874 */
96875 #ifndef _SQLITE3_H_
96876 #define _SQLITE3_H_
96877
96878 /*
96879 ** Make sure we can call this stuff from C++.
96880 */
96881 #if 0
96882 extern "C" {
96883 #endif
96884
96885
96886 /*
96887 ** Add the ability to override 'extern'
96888 */
96889 #ifndef SQLITE_EXTERN
96890 # define SQLITE_EXTERN extern
96891 #endif
96892
96893 /*
96894 ** Make sure these symbols where not defined by some previous header
96895 ** file.
96896 */
96897 #ifdef SQLITE_VERSION
96898 # undef SQLITE_VERSION
96899 #endif
96900 #ifdef SQLITE_VERSION_NUMBER
96901 # undef SQLITE_VERSION_NUMBER
96902 #endif
96903
96904 /*
96905 ** CAPI3REF: Compile-Time Library Version Numbers {F10010}
96906 **
96907 ** {F10011} The #define in the sqlite3.h header file named
96908 ** SQLITE_VERSION resolves to a string literal that identifies
96909 ** the version of the SQLite library in the format "X.Y.Z", where
96910 ** X is the major version number, Y is the minor version number and Z
96911 ** is the release number.  The X.Y.Z might be followed by "alpha" or "beta".
96912 ** {END} For example "3.1.1beta".
96913 **
96914 ** The X value is always 3 in SQLite.  The X value only changes when
96915 ** backwards compatibility is broken and we intend to never break
96916 ** backwards compatibility.  The Y value only changes when
96917 ** there are major feature enhancements that are forwards compatible
96918 ** but not backwards compatible.  The Z value is incremented with
96919 ** each release but resets back to 0 when Y is incremented.
96920 **
96921 ** {F10014} The SQLITE_VERSION_NUMBER #define resolves to an integer
96922 ** with the value  (X*1000000 + Y*1000 + Z) where X, Y, and Z are as
96923 ** with SQLITE_VERSION. {END} For example, for version "3.1.1beta", 
96924 ** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using 
96925 ** version 3.1.1 or greater at compile time, programs may use the test 
96926 ** (SQLITE_VERSION_NUMBER>=3001001).
96927 **
96928 ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
96929 */
96930 #define SQLITE_VERSION         "3.5.4"
96931 #define SQLITE_VERSION_NUMBER 3005004
96932
96933 /*
96934 ** CAPI3REF: Run-Time Library Version Numbers {F10020}
96935 **
96936 ** {F10021} The sqlite3_libversion_number() interface returns an integer
96937 ** equal to [SQLITE_VERSION_NUMBER].  {END} The value returned
96938 ** by this routine should only be different from the header values
96939 ** if the application is compiled using an sqlite3.h header from a
96940 ** different version of SQLite than library.  Cautious programmers might
96941 ** include a check in their application to verify that 
96942 ** sqlite3_libversion_number() always returns the value 
96943 ** [SQLITE_VERSION_NUMBER].
96944 **
96945 ** {F10022} The sqlite3_version[] string constant contains the text of the
96946 ** [SQLITE_VERSION] string. {F10023} The sqlite3_libversion() function returns
96947 ** a pointer to the sqlite3_version[] string constant. {END} The 
96948 ** sqlite3_libversion() function
96949 ** is provided for DLL users who can only access functions and not
96950 ** constants within the DLL.
96951 */
96952 SQLITE_EXTERN const char sqlite3_version[];
96953 const char *sqlite3_libversion(void);
96954 int sqlite3_libversion_number(void);
96955
96956 /*
96957 ** CAPI3REF: Test To See If The Library Is Threadsafe {F10100}
96958 **
96959 ** {F10101} The sqlite3_threadsafe() routine returns nonzero
96960 ** if SQLite was compiled with its mutexes enabled or zero if
96961 ** SQLite was compiled with mutexes disabled. {END}  If this
96962 ** routine returns false, then it is not safe for simultaneously
96963 ** running threads to both invoke SQLite interfaces.
96964 **
96965 ** Really all this routine does is return true if SQLite was
96966 ** compiled with the -DSQLITE_THREADSAFE=1 option and false if
96967 ** compiled with -DSQLITE_THREADSAFE=0.  If SQLite uses an
96968 ** application-defined mutex subsystem, malloc subsystem, collating
96969 ** sequence, VFS, SQL function, progress callback, commit hook,
96970 ** extension, or other accessories and these add-ons are not
96971 ** threadsafe, then clearly the combination will not be threadsafe
96972 ** either.  Hence, this routine never reports that the library
96973 ** is guaranteed to be threadsafe, only when it is guaranteed not
96974 ** to be.
96975 */
96976 int sqlite3_threadsafe(void);
96977
96978 /*
96979 ** CAPI3REF: Database Connection Handle {F12000}
96980 **
96981 ** Each open SQLite database is represented by pointer to an instance of the
96982 ** opaque structure named "sqlite3".  It is useful to think of an sqlite3
96983 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
96984 ** [sqlite3_open_v2()] interfaces are its constructors
96985 ** and [sqlite3_close()] is its destructor.  There are many other interfaces
96986 ** (such as [sqlite3_prepare_v2()], [sqlite3_create_function()], and
96987 ** [sqlite3_busy_timeout()] to name but three) that are methods on this
96988 ** object.
96989 */
96990 typedef struct sqlite3 sqlite3;
96991
96992
96993 /*
96994 ** CAPI3REF: 64-Bit Integer Types {F10200}
96995 **
96996 ** Because there is no cross-platform way to specify such types
96997 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
96998 ** {F10201} The sqlite_int64 and sqlite3_int64 types specify a
96999 ** 64-bit signed integer. {F10202} The sqlite_uint64 and
97000 ** sqlite3_uint64 types specify a 64-bit unsigned integer. {END}
97001 **
97002 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type
97003 ** definitions.  The sqlite_int64 and sqlite_uint64 types are
97004 ** supported for backwards compatibility only.
97005 */
97006 #ifdef SQLITE_INT64_TYPE
97007   typedef SQLITE_INT64_TYPE sqlite_int64;
97008   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
97009 #elif defined(_MSC_VER) || defined(__BORLANDC__)
97010   typedef __int64 sqlite_int64;
97011   typedef unsigned __int64 sqlite_uint64;
97012 #else
97013   typedef long long int sqlite_int64;
97014   typedef unsigned long long int sqlite_uint64;
97015 #endif
97016 typedef sqlite_int64 sqlite3_int64;
97017 typedef sqlite_uint64 sqlite3_uint64;
97018
97019 /*
97020 ** If compiling for a processor that lacks floating point support,
97021 ** substitute integer for floating-point
97022 */
97023 #ifdef SQLITE_OMIT_FLOATING_POINT
97024 # define double sqlite3_int64
97025 #endif
97026
97027 /*
97028 ** CAPI3REF: Closing A Database Connection {F12010}
97029 **
97030 ** {F12011} The sqlite3_close() interfaces destroys an [sqlite3] object
97031 ** allocated by a prior call to [sqlite3_open()], [sqlite3_open16()], or
97032 ** [sqlite3_open_v2()]. {F12012} Sqlite3_close() releases all
97033 ** memory used by the connection and closes all open files. {END}.
97034 **
97035 ** {F12013} If the database connection contains
97036 ** [sqlite3_stmt | prepared statements] that have not been finalized
97037 ** by [sqlite3_finalize()], then sqlite3_close() returns SQLITE_BUSY
97038 ** and leaves the connection open.  {F12014} Giving sqlite3_close()
97039 ** a NULL pointer is a harmless no-op. {END}
97040 **
97041 ** {U12015} Passing this routine a database connection that has already been
97042 ** closed results in undefined behavior. {U12016} If other interfaces that
97043 ** reference the same database connection are pending (either in the
97044 ** same thread or in different threads) when this routine is called,
97045 ** then the behavior is undefined and is almost certainly undesirable.
97046 */
97047 int sqlite3_close(sqlite3 *);
97048
97049 /*
97050 ** The type for a callback function.
97051 ** This is legacy and deprecated.  It is included for historical
97052 ** compatibility and is not documented.
97053 */
97054 typedef int (*sqlite3_callback)(void*,int,char**, char**);
97055
97056 /*
97057 ** CAPI3REF: One-Step Query Execution Interface {F12100}
97058 **
97059 ** {F12101} The sqlite3_exec() interface evaluates zero or more 
97060 ** UTF-8 encoded, semicolon-separated SQL statements in the zero-terminated
97061 ** string of its second argument.  {F12102} The SQL
97062 ** statements are evaluated in the context of the database connection
97063 ** specified by in the first argument.
97064 ** {F12103} SQL statements are prepared one by one using
97065 ** [sqlite3_prepare()] or the equivalent, evaluated
97066 ** using one or more calls to [sqlite3_step()], then destroyed
97067 ** using [sqlite3_finalize()]. {F12104} The return value of
97068 ** sqlite3_exec() is SQLITE_OK if all SQL statement run
97069 ** successfully.
97070 **
97071 ** {F12105} If one or more of the SQL statements handed to
97072 ** sqlite3_exec() are queries, then
97073 ** the callback function specified by the 3rd parameter is
97074 ** invoked once for each row of the query result. {F12106}
97075 ** If the callback returns a non-zero value then the query
97076 ** is aborted, all subsequent SQL statements
97077 ** are skipped and the sqlite3_exec() function returns the [SQLITE_ABORT].
97078 **
97079 ** {F12107} The 4th parameter to sqlite3_exec() is an arbitrary pointer
97080 ** that is passed through to the callback function as its first parameter.
97081 **
97082 ** {F12108} The 2nd parameter to the callback function is the number of
97083 ** columns in the query result.  {F12109} The 3rd parameter to the callback
97084 ** is an array of pointers to strings holding the values for each column
97085 ** as extracted using [sqlite3_column_text()].  NULL values in the result
97086 ** set result in a NULL pointer.  All other value are in their UTF-8
97087 ** string representation. {F12117}
97088 ** The 4th parameter to the callback is an array of strings
97089 ** obtained using [sqlite3_column_name()] and holding
97090 ** the names of each column, also in UTF-8.
97091 **
97092 ** {F12110} The callback function may be NULL, even for queries.  A NULL
97093 ** callback is not an error.  It just means that no callback
97094 ** will be invoked. 
97095 **
97096 ** {F12112} If an error occurs while parsing or evaluating the SQL
97097 ** then an appropriate error message is written into memory obtained
97098 ** from [sqlite3_malloc()] and *errmsg is made to point to that message
97099 ** assuming errmsg is not NULL.  
97100 ** {U12113} The calling function is responsible for freeing the memory
97101 ** using [sqlite3_free()].
97102 ** {F12116} If [sqlite3_malloc()] fails while attempting to generate
97103 ** the error message, *errmsg is set to NULL.
97104 ** {F12114} If errmsg is NULL then no attempt is made to generate an
97105 ** error message. <todo>Is the return code SQLITE_NOMEM or the original
97106 ** error code?</todo> <todo>What happens if there are multiple errors?
97107 ** Do we get code for the first error, or is the choice of reported
97108 ** error arbitrary?</todo>
97109 **
97110 ** {F12115} The return value is is SQLITE_OK if there are no errors and
97111 ** some other [SQLITE_OK | return code] if there is an error.  
97112 ** The particular return value depends on the type of error.  {END}
97113 */
97114 int sqlite3_exec(
97115   sqlite3*,                                  /* An open database */
97116   const char *sql,                           /* SQL to be evaluted */
97117   int (*callback)(void*,int,char**,char**),  /* Callback function */
97118   void *,                                    /* 1st argument to callback */
97119   char **errmsg                              /* Error msg written here */
97120 );
97121
97122 /*
97123 ** CAPI3REF: Result Codes {F10210}
97124 ** KEYWORDS: SQLITE_OK
97125 **
97126 ** Many SQLite functions return an integer result code from the set shown
97127 ** above in order to indicates success or failure.
97128 **
97129 ** {F10211} The result codes shown here are the only ones returned 
97130 ** by SQLite in its default configuration. {F10212} However, the
97131 ** [sqlite3_extended_result_codes()] API can be used to set a database
97132 ** connectoin to return more detailed result codes. {END}
97133 **
97134 ** See also: [SQLITE_IOERR_READ | extended result codes]
97135 **
97136 */
97137 #define SQLITE_OK           0   /* Successful result */
97138 /* beginning-of-error-codes */
97139 #define SQLITE_ERROR        1   /* SQL error or missing database */
97140 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
97141 #define SQLITE_PERM         3   /* Access permission denied */
97142 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
97143 #define SQLITE_BUSY         5   /* The database file is locked */
97144 #define SQLITE_LOCKED       6   /* A table in the database is locked */
97145 #define SQLITE_NOMEM        7   /* A malloc() failed */
97146 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
97147 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
97148 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
97149 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
97150 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
97151 #define SQLITE_FULL        13   /* Insertion failed because database is full */
97152 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
97153 #define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
97154 #define SQLITE_EMPTY       16   /* Database is empty */
97155 #define SQLITE_SCHEMA      17   /* The database schema changed */
97156 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
97157 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
97158 #define SQLITE_MISMATCH    20   /* Data type mismatch */
97159 #define SQLITE_MISUSE      21   /* Library used incorrectly */
97160 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
97161 #define SQLITE_AUTH        23   /* Authorization denied */
97162 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
97163 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
97164 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
97165 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
97166 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
97167 /* end-of-error-codes */
97168
97169 /*
97170 ** CAPI3REF: Extended Result Codes {F10220}
97171 **
97172 ** In its default configuration, SQLite API routines return one of 26 integer
97173 ** [SQLITE_OK | result codes].  However, experience has shown that
97174 ** many of these result codes are too course-grained.  They do not provide as
97175 ** much information about problems as programmers might like.  In an effort to
97176 ** address this, newer versions of SQLite (version 3.3.8 and later) include
97177 ** support for additional result codes that provide more detailed information
97178 ** about errors. {F10221} The extended result codes are enabled or disabled
97179 ** for each database connection using the [sqlite3_extended_result_codes()]
97180 ** API. {END}
97181 ** 
97182 ** Some of the available extended result codes are listed above.
97183 ** We expect the number of extended result codes will be expand
97184 ** over time.  {U10422} Software that uses extended result codes should expect
97185 ** to see new result codes in future releases of SQLite. {END}
97186 ** 
97187 ** {F10223} The symbolic name for an extended result code always contains
97188 ** a related primary result code as a prefix. {F10224} Primary result
97189 ** codes contain a single "_" character.  {F10225} Extended result codes
97190 ** contain two or more "_" characters. {F10226} The numeric value of an
97191 ** extended result code can be converted to its
97192 ** corresponding primary result code by masking off the lower 8 bytes. {END}
97193 **
97194 ** The SQLITE_OK result code will never be extended.  It will always
97195 ** be exactly zero.
97196 */
97197 #define SQLITE_IOERR_READ          (SQLITE_IOERR | (1<<8))
97198 #define SQLITE_IOERR_SHORT_READ    (SQLITE_IOERR | (2<<8))
97199 #define SQLITE_IOERR_WRITE         (SQLITE_IOERR | (3<<8))
97200 #define SQLITE_IOERR_FSYNC         (SQLITE_IOERR | (4<<8))
97201 #define SQLITE_IOERR_DIR_FSYNC     (SQLITE_IOERR | (5<<8))
97202 #define SQLITE_IOERR_TRUNCATE      (SQLITE_IOERR | (6<<8))
97203 #define SQLITE_IOERR_FSTAT         (SQLITE_IOERR | (7<<8))
97204 #define SQLITE_IOERR_UNLOCK        (SQLITE_IOERR | (8<<8))
97205 #define SQLITE_IOERR_RDLOCK        (SQLITE_IOERR | (9<<8))
97206 #define SQLITE_IOERR_DELETE        (SQLITE_IOERR | (10<<8))
97207 #define SQLITE_IOERR_BLOCKED       (SQLITE_IOERR | (11<<8))
97208 #define SQLITE_IOERR_NOMEM         (SQLITE_IOERR | (12<<8))
97209
97210 /*
97211 ** CAPI3REF: Flags For File Open Operations {F10230}
97212 **
97213 ** {F10231} Some combination of the these bit values are used as the
97214 ** third argument to the [sqlite3_open_v2()] interface and
97215 ** as fourth argument to the xOpen method of the
97216 ** [sqlite3_vfs] object.
97217 */
97218 #define SQLITE_OPEN_READONLY         0x00000001
97219 #define SQLITE_OPEN_READWRITE        0x00000002
97220 #define SQLITE_OPEN_CREATE           0x00000004
97221 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008
97222 #define SQLITE_OPEN_EXCLUSIVE        0x00000010
97223 #define SQLITE_OPEN_MAIN_DB          0x00000100
97224 #define SQLITE_OPEN_TEMP_DB          0x00000200
97225 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400
97226 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800
97227 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000
97228 #define SQLITE_OPEN_SUBJOURNAL       0x00002000
97229 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000
97230
97231 /*
97232 ** CAPI3REF: Device Characteristics {F10240}
97233 **
97234 ** {F10241} The xDeviceCapabilities method of the [sqlite3_io_methods]
97235 ** object returns an integer which is a vector of the these
97236 ** bit values expressing I/O characteristics of the mass storage
97237 ** device that holds the file that the [sqlite3_io_methods]
97238 ** refers to. {END}
97239 **
97240 ** {F10242} The SQLITE_IOCAP_ATOMIC property means that all writes of
97241 ** any size are atomic.  {F10243} The SQLITE_IOCAP_ATOMICnnn values
97242 ** mean that writes of blocks that are nnn bytes in size and
97243 ** are aligned to an address which is an integer multiple of
97244 ** nnn are atomic.  {F10244} The SQLITE_IOCAP_SAFE_APPEND value means
97245 ** that when data is appended to a file, the data is appended
97246 ** first then the size of the file is extended, never the other
97247 ** way around.  {F10245} The SQLITE_IOCAP_SEQUENTIAL property means that
97248 ** information is written to disk in the same order as calls
97249 ** to xWrite().
97250 */
97251 #define SQLITE_IOCAP_ATOMIC          0x00000001
97252 #define SQLITE_IOCAP_ATOMIC512       0x00000002
97253 #define SQLITE_IOCAP_ATOMIC1K        0x00000004
97254 #define SQLITE_IOCAP_ATOMIC2K        0x00000008
97255 #define SQLITE_IOCAP_ATOMIC4K        0x00000010
97256 #define SQLITE_IOCAP_ATOMIC8K        0x00000020
97257 #define SQLITE_IOCAP_ATOMIC16K       0x00000040
97258 #define SQLITE_IOCAP_ATOMIC32K       0x00000080
97259 #define SQLITE_IOCAP_ATOMIC64K       0x00000100
97260 #define SQLITE_IOCAP_SAFE_APPEND     0x00000200
97261 #define SQLITE_IOCAP_SEQUENTIAL      0x00000400
97262
97263 /*
97264 ** CAPI3REF: File Locking Levels {F10250}
97265 **
97266 ** {F10251} SQLite uses one of the following integer values as the second
97267 ** argument to calls it makes to the xLock() and xUnlock() methods
97268 ** of an [sqlite3_io_methods] object. {END}
97269 */
97270 #define SQLITE_LOCK_NONE          0
97271 #define SQLITE_LOCK_SHARED        1
97272 #define SQLITE_LOCK_RESERVED      2
97273 #define SQLITE_LOCK_PENDING       3
97274 #define SQLITE_LOCK_EXCLUSIVE     4
97275
97276 /*
97277 ** CAPI3REF: Synchronization Type Flags {F10260}
97278 **
97279 ** {F10261} When SQLite invokes the xSync() method of an
97280 ** [sqlite3_io_methods] object it uses a combination of the
97281 ** these integer values as the second argument.
97282 **
97283 ** {F10262} When the SQLITE_SYNC_DATAONLY flag is used, it means that the
97284 ** sync operation only needs to flush data to mass storage.  Inode
97285 ** information need not be flushed. {F10263} The SQLITE_SYNC_NORMAL means 
97286 ** to use normal fsync() semantics. {F10264} The SQLITE_SYNC_FULL flag means 
97287 ** to use Mac OS-X style fullsync instead of fsync().
97288 */
97289 #define SQLITE_SYNC_NORMAL        0x00002
97290 #define SQLITE_SYNC_FULL          0x00003
97291 #define SQLITE_SYNC_DATAONLY      0x00010
97292
97293
97294 /*
97295 ** CAPI3REF: OS Interface Open File Handle {F11110}
97296 **
97297 ** An [sqlite3_file] object represents an open file in the OS
97298 ** interface layer.  Individual OS interface implementations will
97299 ** want to subclass this object by appending additional fields
97300 ** for their own use.  The pMethods entry is a pointer to an
97301 ** [sqlite3_io_methods] object that defines methods for performing
97302 ** I/O operations on the open file.
97303 */
97304 typedef struct sqlite3_file sqlite3_file;
97305 struct sqlite3_file {
97306   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
97307 };
97308
97309 /*
97310 ** CAPI3REF: OS Interface File Virtual Methods Object {F11120}
97311 **
97312 ** Every file opened by the [sqlite3_vfs] xOpen method contains a pointer to
97313 ** an instance of the this object.  This object defines the
97314 ** methods used to perform various operations against the open file.
97315 **
97316 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
97317 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
97318 *  The second choice is an
97319 ** OS-X style fullsync.  The SQLITE_SYNC_DATA flag may be ORed in to
97320 ** indicate that only the data of the file and not its inode needs to be
97321 ** synced.
97322 ** 
97323 ** The integer values to xLock() and xUnlock() are one of
97324 ** <ul>
97325 ** <li> [SQLITE_LOCK_NONE],
97326 ** <li> [SQLITE_LOCK_SHARED],
97327 ** <li> [SQLITE_LOCK_RESERVED],
97328 ** <li> [SQLITE_LOCK_PENDING], or
97329 ** <li> [SQLITE_LOCK_EXCLUSIVE].
97330 ** </ul>
97331 ** xLock() increases the lock. xUnlock() decreases the lock.  
97332 ** The xCheckReservedLock() method looks
97333 ** to see if any database connection, either in this
97334 ** process or in some other process, is holding an RESERVED,
97335 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
97336 ** if such a lock exists and false if not.
97337 ** 
97338 ** The xFileControl() method is a generic interface that allows custom
97339 ** VFS implementations to directly control an open file using the
97340 ** [sqlite3_file_control()] interface.  The second "op" argument
97341 ** is an integer opcode.   The third
97342 ** argument is a generic pointer which is intended to be a pointer
97343 ** to a structure that may contain arguments or space in which to
97344 ** write return values.  Potential uses for xFileControl() might be
97345 ** functions to enable blocking locks with timeouts, to change the
97346 ** locking strategy (for example to use dot-file locks), to inquire
97347 ** about the status of a lock, or to break stale locks.  The SQLite
97348 ** core reserves opcodes less than 100 for its own use. 
97349 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
97350 ** Applications that define a custom xFileControl method should use opcodes 
97351 ** greater than 100 to avoid conflicts.
97352 **
97353 ** The xSectorSize() method returns the sector size of the
97354 ** device that underlies the file.  The sector size is the
97355 ** minimum write that can be performed without disturbing
97356 ** other bytes in the file.  The xDeviceCharacteristics()
97357 ** method returns a bit vector describing behaviors of the
97358 ** underlying device:
97359 **
97360 ** <ul>
97361 ** <li> [SQLITE_IOCAP_ATOMIC]
97362 ** <li> [SQLITE_IOCAP_ATOMIC512]
97363 ** <li> [SQLITE_IOCAP_ATOMIC1K]
97364 ** <li> [SQLITE_IOCAP_ATOMIC2K]
97365 ** <li> [SQLITE_IOCAP_ATOMIC4K]
97366 ** <li> [SQLITE_IOCAP_ATOMIC8K]
97367 ** <li> [SQLITE_IOCAP_ATOMIC16K]
97368 ** <li> [SQLITE_IOCAP_ATOMIC32K]
97369 ** <li> [SQLITE_IOCAP_ATOMIC64K]
97370 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
97371 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
97372 ** </ul>
97373 **
97374 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
97375 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
97376 ** mean that writes of blocks that are nnn bytes in size and
97377 ** are aligned to an address which is an integer multiple of
97378 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
97379 ** that when data is appended to a file, the data is appended
97380 ** first then the size of the file is extended, never the other
97381 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
97382 ** information is written to disk in the same order as calls
97383 ** to xWrite().
97384 */
97385 typedef struct sqlite3_io_methods sqlite3_io_methods;
97386 struct sqlite3_io_methods {
97387   int iVersion;
97388   int (*xClose)(sqlite3_file*);
97389   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
97390   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
97391   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
97392   int (*xSync)(sqlite3_file*, int flags);
97393   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
97394   int (*xLock)(sqlite3_file*, int);
97395   int (*xUnlock)(sqlite3_file*, int);
97396   int (*xCheckReservedLock)(sqlite3_file*);
97397   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
97398   int (*xSectorSize)(sqlite3_file*);
97399   int (*xDeviceCharacteristics)(sqlite3_file*);
97400   /* Additional methods may be added in future releases */
97401 };
97402
97403 /*
97404 ** CAPI3REF: Standard File Control Opcodes {F11310}
97405 **
97406 ** These integer constants are opcodes for the xFileControl method
97407 ** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()]
97408 ** interface.
97409 **
97410 ** {F11311} The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
97411 ** opcode cases the xFileControl method to write the current state of
97412 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
97413 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
97414 ** into an integer that the pArg argument points to. {F11312} This capability
97415 ** is used during testing and only needs to be supported when SQLITE_TEST
97416 ** is defined.
97417 */
97418 #define SQLITE_FCNTL_LOCKSTATE        1
97419
97420 /*
97421 ** CAPI3REF: Mutex Handle {F17110}
97422 **
97423 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
97424 ** abstract type for a mutex object.  {F17111} The SQLite core never looks
97425 ** at the internal representation of an [sqlite3_mutex]. {END} It only
97426 ** deals with pointers to the [sqlite3_mutex] object.
97427 **
97428 ** Mutexes are created using [sqlite3_mutex_alloc()].
97429 */
97430 typedef struct sqlite3_mutex sqlite3_mutex;
97431
97432 /*
97433 ** CAPI3REF: OS Interface Object {F11140}
97434 **
97435 ** An instance of this object defines the interface between the
97436 ** SQLite core and the underlying operating system.  The "vfs"
97437 ** in the name of the object stands for "virtual file system".
97438 **
97439 ** The iVersion field is initially 1 but may be larger for future
97440 ** versions of SQLite.  Additional fields may be appended to this
97441 ** object when the iVersion value is increased.
97442 **
97443 ** The szOsFile field is the size of the subclassed [sqlite3_file]
97444 ** structure used by this VFS.  mxPathname is the maximum length of
97445 ** a pathname in this VFS.
97446 **
97447 ** Registered vfs modules are kept on a linked list formed by
97448 ** the pNext pointer.  The [sqlite3_vfs_register()]
97449 ** and [sqlite3_vfs_unregister()] interfaces manage this list
97450 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
97451 ** searches the list.
97452 **
97453 ** The pNext field is the only fields in the sqlite3_vfs 
97454 ** structure that SQLite will ever modify.  SQLite will only access
97455 ** or modify this field while holding a particular static mutex.
97456 ** The application should never modify anything within the sqlite3_vfs
97457 ** object once the object has been registered.
97458 **
97459 ** The zName field holds the name of the VFS module.  The name must
97460 ** be unique across all VFS modules.
97461 **
97462 ** {F11141} SQLite will guarantee that the zFilename string passed to
97463 ** xOpen() is a full pathname as generated by xFullPathname() and
97464 ** that the string will be valid and unchanged until xClose() is
97465 ** called.  {END} So the [sqlite3_file] can store a pointer to the
97466 ** filename if it needs to remember the filename for some reason.
97467 **
97468 ** {F11142} The flags argument to xOpen() includes all bits set in
97469 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
97470 ** or [sqlite3_open16()] is used, then flags includes at least
97471 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END}
97472 ** If xOpen() opens a file read-only then it sets *pOutFlags to
97473 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be
97474 ** set.
97475 ** 
97476 ** {F11143} SQLite will also add one of the following flags to the xOpen()
97477 ** call, depending on the object being opened:
97478 ** 
97479 ** <ul>
97480 ** <li>  [SQLITE_OPEN_MAIN_DB]
97481 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
97482 ** <li>  [SQLITE_OPEN_TEMP_DB]
97483 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
97484 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
97485 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
97486 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
97487 ** </ul> {END}
97488 **
97489 ** The file I/O implementation can use the object type flags to
97490 ** changes the way it deals with files.  For example, an application
97491 ** that does not care about crash recovery or rollback, might make
97492 ** the open of a journal file a no-op.  Writes to this journal are
97493 ** also a no-op.  Any attempt to read the journal return SQLITE_IOERR.
97494 ** Or the implementation might recognize the a database file will
97495 ** be doing page-aligned sector reads and writes in a random order
97496 ** and set up its I/O subsystem accordingly.
97497 ** 
97498 ** {F11144} SQLite might also add one of the following flags to the xOpen
97499 ** method:
97500 ** 
97501 ** <ul>
97502 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
97503 ** <li> [SQLITE_OPEN_EXCLUSIVE]
97504 ** </ul>
97505 ** 
97506 ** {F11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
97507 ** deleted when it is closed.  {F11146} The [SQLITE_OPEN_DELETEONCLOSE]
97508 ** will be set for TEMP  databases, journals and for subjournals. 
97509 ** {F11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened
97510 ** for exclusive access.  This flag is set for all files except
97511 ** for the main database file. {END}
97512 ** 
97513 ** {F11148} At least szOsFile bytes of memory is allocated by SQLite 
97514 ** to hold the  [sqlite3_file] structure passed as the third 
97515 ** argument to xOpen.  {END}  The xOpen method does not have to
97516 ** allocate the structure; it should just fill it in.
97517 ** 
97518 ** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] 
97519 ** to test for the existance of a file,
97520 ** or [SQLITE_ACCESS_READWRITE] to test to see
97521 ** if a file is readable and writable, or [SQLITE_ACCESS_READ]
97522 ** to test to see if a file is at least readable.  {END} The file can be a 
97523 ** directory.
97524 ** 
97525 ** {F11150} SQLite will always allocate at least mxPathname+1 byte for
97526 ** the output buffers for xGetTempname and xFullPathname. {F11151} The exact
97527 ** size of the output buffer is also passed as a parameter to both 
97528 ** methods. {END} If the output buffer is not large enough, SQLITE_CANTOPEN
97529 ** should be returned. As this is handled as a fatal error by SQLite,
97530 ** vfs implementations should endeavor to prevent this by setting 
97531 ** mxPathname to a sufficiently large value.
97532 ** 
97533 ** The xRandomness(), xSleep(), and xCurrentTime() interfaces
97534 ** are not strictly a part of the filesystem, but they are
97535 ** included in the VFS structure for completeness.
97536 ** The xRandomness() function attempts to return nBytes bytes
97537 ** of good-quality randomness into zOut.  The return value is
97538 ** the actual number of bytes of randomness obtained.  The
97539 ** xSleep() method cause the calling thread to sleep for at
97540 ** least the number of microseconds given.  The xCurrentTime()
97541 ** method returns a Julian Day Number for the current date and
97542 ** time.
97543 */
97544 typedef struct sqlite3_vfs sqlite3_vfs;
97545 struct sqlite3_vfs {
97546   int iVersion;            /* Structure version number */
97547   int szOsFile;            /* Size of subclassed sqlite3_file */
97548   int mxPathname;          /* Maximum file pathname length */
97549   sqlite3_vfs *pNext;      /* Next registered VFS */
97550   const char *zName;       /* Name of this virtual file system */
97551   void *pAppData;          /* Pointer to application-specific data */
97552   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
97553                int flags, int *pOutFlags);
97554   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
97555   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags);
97556   int (*xGetTempname)(sqlite3_vfs*, int nOut, char *zOut);
97557   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
97558   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
97559   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
97560   void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol);
97561   void (*xDlClose)(sqlite3_vfs*, void*);
97562   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
97563   int (*xSleep)(sqlite3_vfs*, int microseconds);
97564   int (*xCurrentTime)(sqlite3_vfs*, double*);
97565   /* New fields may be appended in figure versions.  The iVersion
97566   ** value will increment whenever this happens. */
97567 };
97568
97569 /*
97570 ** CAPI3REF: Flags for the xAccess VFS method {F11190}
97571 **
97572 ** {F11191} These integer constants can be used as the third parameter to
97573 ** the xAccess method of an [sqlite3_vfs] object. {END}  They determine
97574 ** the kind of what kind of permissions the xAccess method is
97575 ** looking for.  {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method
97576 ** simply checks to see if the file exists. {F11193} With
97577 ** SQLITE_ACCESS_READWRITE, the xAccess method checks to see
97578 ** if the file is both readable and writable.  {F11194} With
97579 ** SQLITE_ACCESS_READ the xAccess method
97580 ** checks to see if the file is readable.
97581 */
97582 #define SQLITE_ACCESS_EXISTS    0
97583 #define SQLITE_ACCESS_READWRITE 1
97584 #define SQLITE_ACCESS_READ      2
97585
97586 /*
97587 ** CAPI3REF: Enable Or Disable Extended Result Codes {F12200}
97588 **
97589 ** {F12201} The sqlite3_extended_result_codes() routine enables or disables the
97590 ** [SQLITE_IOERR_READ | extended result codes] feature on a database
97591 ** connection if its 2nd parameter is
97592 ** non-zero or zero, respectively. {F12202}
97593 ** By default, SQLite API routines return one of only 26 integer
97594 ** [SQLITE_OK | result codes].  {F12203} When extended result codes
97595 ** are enabled by this routine, the repetoire of result codes can be
97596 ** much larger and can (hopefully) provide more detailed information
97597 ** about the cause of an error.
97598 **
97599 ** {F12204} The second argument is a boolean value that turns extended result
97600 ** codes on and off. {F12205} Extended result codes are off by default for
97601 ** backwards compatibility with older versions of SQLite.
97602 */
97603 int sqlite3_extended_result_codes(sqlite3*, int onoff);
97604
97605 /*
97606 ** CAPI3REF: Last Insert Rowid {F12220}
97607 **
97608 ** {F12221} Each entry in an SQLite table has a unique 64-bit signed
97609 ** integer key called the "rowid".  {F12222} The rowid is always available
97610 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
97611 ** names are not also used by explicitly declared columns. {F12223} If
97612 ** the table has a column of type INTEGER PRIMARY KEY then that column
97613 ** is another an alias for the rowid.
97614 **
97615 ** {F12224} This routine returns the rowid of the most recent
97616 ** successful INSERT into the database from the database connection
97617 ** shown in the first argument.  {F12225} If no successful inserts
97618 ** have ever occurred on this database connection, zero is returned.
97619 **
97620 ** {F12226} If an INSERT occurs within a trigger, then the rowid of the
97621 ** inserted row is returned by this routine as long as the trigger
97622 ** is running.  {F12227} But once the trigger terminates, the value returned
97623 ** by this routine reverts to the last value inserted before the
97624 ** trigger fired.
97625 **
97626 ** {F12228} An INSERT that fails due to a constraint violation is not a
97627 ** successful insert and does not change the value returned by this
97628 ** routine.  {F12229} Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
97629 ** and INSERT OR ABORT make no changes to the return value of this
97630 ** routine when their insertion fails.  {F12231} When INSERT OR REPLACE 
97631 ** encounters a constraint violation, it does not fail.  The
97632 ** INSERT continues to completion after deleting rows that caused
97633 ** the constraint problem so INSERT OR REPLACE will always change
97634 ** the return value of this interface. 
97635 **
97636 ** {UF12232} If another thread does a new insert on the same database connection
97637 ** while this routine is running and thus changes the last insert rowid,
97638 ** then the return value of this routine is undefined.
97639 */
97640 sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
97641
97642 /*
97643 ** CAPI3REF: Count The Number Of Rows Modified {F12240}
97644 **
97645 ** {F12241} This function returns the number of database rows that were changed
97646 ** or inserted or deleted by the most recently completed SQL statement
97647 ** on the connection specified by the first parameter. {F12242} Only
97648 ** changes that are directly specified by the INSERT, UPDATE, or
97649 ** DELETE statement are counted.  Auxiliary changes caused by
97650 ** triggers are not counted. {F12243} Use the [sqlite3_total_changes()] function
97651 ** to find the total number of changes including changes caused by triggers.
97652 **
97653 ** {F12244} Within the body of a trigger, the sqlite3_changes() interface
97654 ** can be called to find the number of
97655 ** changes in the most recently completed INSERT, UPDATE, or DELETE
97656 ** statement within the body of the same trigger.
97657 **
97658 ** {F12245} All changes are counted, even if they are later undone by a
97659 ** ROLLBACK or ABORT.  {F12246} Except, changes associated with creating and
97660 ** dropping tables are not counted.
97661 **
97662 ** {F12247} If a callback invokes [sqlite3_exec()] or [sqlite3_step()]
97663 ** recursively, then the changes in the inner, recursive call are
97664 ** counted together with the changes in the outer call.
97665 **
97666 ** {F12248} SQLite implements the command "DELETE FROM table" without
97667 ** a WHERE clause by dropping and recreating the table.  (This is much
97668 ** faster than going through and deleting individual elements from the
97669 ** table.)  Because of this optimization, the change count for 
97670 ** "DELETE FROM table" will be zero regardless of the number of elements
97671 ** that were originally in the table. {F12251} To get an accurate count
97672 ** of the number of rows deleted, use
97673 ** "DELETE FROM table WHERE 1" instead.
97674 **
97675 ** {UF12252} If another thread makes changes on the same database connection
97676 ** while this routine is running then the return value of this routine
97677 ** is undefined.
97678 */
97679 int sqlite3_changes(sqlite3*);
97680
97681 /*
97682 ** CAPI3REF: Total Number Of Rows Modified {F12260}
97683 ***
97684 ** {F12261} This function returns the number of database rows that have been
97685 ** modified by INSERT, UPDATE or DELETE statements since the database handle
97686 ** was opened. {F12262} The count includes UPDATE, INSERT and DELETE 
97687 ** statements executed as part of trigger programs.  {F12263} All changes
97688 ** are counted as soon as the statement that makes them is completed 
97689 ** (when the statement handle is passed to [sqlite3_reset()] or 
97690 ** [sqlite3_finalize()]). {END}
97691 **
97692 ** See also the [sqlite3_change()] interface.
97693 **
97694 ** {F12265} SQLite implements the command "DELETE FROM table" without
97695 ** a WHERE clause by dropping and recreating the table.  (This is much
97696 ** faster than going
97697 ** through and deleting individual elements form the table.)  Because of
97698 ** this optimization, the change count for "DELETE FROM table" will be
97699 ** zero regardless of the number of elements that were originally in the
97700 ** table. To get an accurate count of the number of rows deleted, use
97701 ** "DELETE FROM table WHERE 1" instead.
97702 **
97703 ** {U12264} If another thread makes changes on the same database connection
97704 ** while this routine is running then the return value of this routine
97705 ** is undefined. {END}
97706 */
97707 int sqlite3_total_changes(sqlite3*);
97708
97709 /*
97710 ** CAPI3REF: Interrupt A Long-Running Query {F12270}
97711 **
97712 ** {F12271} This function causes any pending database operation to abort and
97713 ** return at its earliest opportunity. {END} This routine is typically
97714 ** called in response to a user action such as pressing "Cancel"
97715 ** or Ctrl-C where the user wants a long query operation to halt
97716 ** immediately.
97717 **
97718 ** {F12272} It is safe to call this routine from a thread different from the
97719 ** thread that is currently running the database operation. {U12273} But it
97720 ** is not safe to call this routine with a database connection that
97721 ** is closed or might close before sqlite3_interrupt() returns.
97722 **
97723 ** If an SQL is very nearly finished at the time when sqlite3_interrupt()
97724 ** is called, then it might not have an opportunity to be interrupted.
97725 ** It might continue to completion.
97726 ** {F12274} The SQL operation that is interrupted will return
97727 ** [SQLITE_INTERRUPT].  {F12275} If the interrupted SQL operation is an
97728 ** INSERT, UPDATE, or DELETE that is inside an explicit transaction, 
97729 ** then the entire transaction will be rolled back automatically.
97730 ** {F12276} A call to sqlite3_interrupt() has no effect on SQL statements
97731 ** that are started after sqlite3_interrupt() returns.
97732 */
97733 void sqlite3_interrupt(sqlite3*);
97734
97735 /*
97736 ** CAPI3REF: Determine If An SQL Statement Is Complete {F10510}
97737 **
97738 ** These routines are useful for command-line input to determine if the
97739 ** currently entered text seems to form complete a SQL statement or
97740 ** if additional input is needed before sending the text into
97741 ** SQLite for parsing.  These routines return true if the input string
97742 ** appears to be a complete SQL statement.  A statement is judged to be
97743 ** complete if it ends with a semicolon and is not a fragment of a
97744 ** CREATE TRIGGER statement.  These routines do not parse the SQL and
97745 ** so will not detect syntactically incorrect SQL.
97746 **
97747 ** {F10511} These functions return true if the given input string 
97748 ** ends with a semicolon optionally followed by whitespace or
97749 ** comments. {F10512} For sqlite3_complete(),
97750 ** the parameter must be a zero-terminated UTF-8 string. {F10513} For
97751 ** sqlite3_complete16(), a zero-terminated machine byte order UTF-16 string
97752 ** is required.  {F10514} These routines return false if the terminal
97753 ** semicolon is within a comment, a string literal or a quoted identifier
97754 ** (in other words if the final semicolon is not really a separate token
97755 ** but part of a larger token) or if the final semicolon is
97756 ** in between the BEGIN and END keywords of a CREATE TRIGGER statement.
97757 ** {END}
97758 */
97759 int sqlite3_complete(const char *sql);
97760 int sqlite3_complete16(const void *sql);
97761
97762 /*
97763 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310}
97764 **
97765 ** {F12311} This routine identifies a callback function that might be
97766 ** invoked whenever an attempt is made to open a database table 
97767 ** that another thread or process has locked.
97768 ** {F12312} If the busy callback is NULL, then [SQLITE_BUSY]
97769 ** or [SQLITE_IOERR_BLOCKED]
97770 ** is returned immediately upon encountering the lock.
97771 ** {F12313} If the busy callback is not NULL, then the
97772 ** callback will be invoked with two arguments.  {F12314} The
97773 ** first argument to the handler is a copy of the void* pointer which
97774 ** is the third argument to this routine.  {F12315} The second argument to
97775 ** the handler is the number of times that the busy handler has
97776 ** been invoked for this locking event.  {F12316} If the
97777 ** busy callback returns 0, then no additional attempts are made to
97778 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
97779 ** {F12317} If the callback returns non-zero, then another attempt
97780 ** is made to open the database for reading and the cycle repeats.
97781 **
97782 ** The presence of a busy handler does not guarantee that
97783 ** it will be invoked when there is lock contention. {F12319}
97784 ** If SQLite determines that invoking the busy handler could result in
97785 ** a deadlock, it will go ahead and return [SQLITE_BUSY] or
97786 ** [SQLITE_IOERR_BLOCKED] instead of invoking the
97787 ** busy handler. {END}
97788 ** Consider a scenario where one process is holding a read lock that
97789 ** it is trying to promote to a reserved lock and
97790 ** a second process is holding a reserved lock that it is trying
97791 ** to promote to an exclusive lock.  The first process cannot proceed
97792 ** because it is blocked by the second and the second process cannot
97793 ** proceed because it is blocked by the first.  If both processes
97794 ** invoke the busy handlers, neither will make any progress.  Therefore,
97795 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
97796 ** will induce the first process to release its read lock and allow
97797 ** the second process to proceed.
97798 **
97799 ** {F12321} The default busy callback is NULL. {END}
97800 **
97801 ** {F12322} The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
97802 ** when SQLite is in the middle of a large transaction where all the
97803 ** changes will not fit into the in-memory cache.  {F12323} SQLite will
97804 ** already hold a RESERVED lock on the database file, but it needs
97805 ** to promote this lock to EXCLUSIVE so that it can spill cache
97806 ** pages into the database file without harm to concurrent
97807 ** readers.  {F12324} If it is unable to promote the lock, then the in-memory
97808 ** cache will be left in an inconsistent state and so the error
97809 ** code is promoted from the relatively benign [SQLITE_BUSY] to
97810 ** the more severe [SQLITE_IOERR_BLOCKED].  {F12325} This error code promotion
97811 ** forces an automatic rollback of the changes. {END} See the
97812 ** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError">
97813 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
97814 ** this is important.
97815 **      
97816 ** {F12326} Sqlite is re-entrant, so the busy handler may start a new
97817 ** query. {END} (It is not clear why anyone would every want to do this,
97818 ** but it is allowed, in theory.) {U12327} But the busy handler may not
97819 ** close the database.  Closing the database from a busy handler will delete 
97820 ** data structures out from under the executing query and will 
97821 ** probably result in a segmentation fault or other runtime error. {END}
97822 **
97823 ** {F12328} There can only be a single busy handler defined for each database
97824 ** connection.  Setting a new busy handler clears any previous one. 
97825 ** {F12329} Note that calling [sqlite3_busy_timeout()] will also set or clear
97826 ** the busy handler.
97827 **
97828 ** {F12331} When operating in [sqlite3_enable_shared_cache | shared cache mode],
97829 ** only a single busy handler can be defined for each database file.
97830 ** So if two database connections share a single cache, then changing
97831 ** the busy handler on one connection will also change the busy
97832 ** handler in the other connection.  {F12332} The busy handler is invoked
97833 ** in the thread that was running when the lock contention occurs.
97834 */
97835 int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
97836
97837 /*
97838 ** CAPI3REF: Set A Busy Timeout {F12340}
97839 **
97840 ** {F12341} This routine sets a [sqlite3_busy_handler | busy handler]
97841 ** that sleeps for a while when a
97842 ** table is locked.  {F12342} The handler will sleep multiple times until 
97843 ** at least "ms" milliseconds of sleeping have been done. {F12343} After
97844 ** "ms" milliseconds of sleeping, the handler returns 0 which
97845 ** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
97846 **
97847 ** {F12344} Calling this routine with an argument less than or equal to zero
97848 ** turns off all busy handlers.
97849 **
97850 ** {F12345} There can only be a single busy handler for a particular database
97851 ** connection.  If another busy handler was defined  
97852 ** (using [sqlite3_busy_handler()]) prior to calling
97853 ** this routine, that other busy handler is cleared.
97854 */
97855 int sqlite3_busy_timeout(sqlite3*, int ms);
97856
97857 /*
97858 ** CAPI3REF: Convenience Routines For Running Queries {F12370}
97859 **
97860 ** This next routine is a convenience wrapper around [sqlite3_exec()].
97861 ** {F12371} Instead of invoking a user-supplied callback for each row of the
97862 ** result, this routine remembers each row of the result in memory
97863 ** obtained from [sqlite3_malloc()], then returns all of the result after the
97864 ** query has finished. {F12372}
97865 **
97866 ** As an example, suppose the query result where this table:
97867 **
97868 ** <blockquote><pre>
97869 **        Name        | Age
97870 **        -----------------------
97871 **        Alice       | 43
97872 **        Bob         | 28
97873 **        Cindy       | 21
97874 ** </pre></blockquote>
97875 **
97876 ** If the 3rd argument were &azResult then after the function returns
97877 ** azResult will contain the following data:
97878 **
97879 ** <blockquote><pre>
97880 **        azResult&#91;0] = "Name";
97881 **        azResult&#91;1] = "Age";
97882 **        azResult&#91;2] = "Alice";
97883 **        azResult&#91;3] = "43";
97884 **        azResult&#91;4] = "Bob";
97885 **        azResult&#91;5] = "28";
97886 **        azResult&#91;6] = "Cindy";
97887 **        azResult&#91;7] = "21";
97888 ** </pre></blockquote>
97889 **
97890 ** Notice that there is an extra row of data containing the column
97891 ** headers.  But the *nrow return value is still 3.  *ncolumn is
97892 ** set to 2.  In general, the number of values inserted into azResult
97893 ** will be ((*nrow) + 1)*(*ncolumn).
97894 **
97895 ** {U12374} After the calling function has finished using the result, it should 
97896 ** pass the result data pointer to sqlite3_free_table() in order to 
97897 ** release the memory that was malloc-ed.  Because of the way the 
97898 ** [sqlite3_malloc()] happens, the calling function must not try to call 
97899 ** [sqlite3_free()] directly.  Only [sqlite3_free_table()] is able to release 
97900 ** the memory properly and safely. {END}
97901 **
97902 ** {F12373} The return value of this routine is the same as
97903 ** from [sqlite3_exec()].
97904 */
97905 int sqlite3_get_table(
97906   sqlite3*,              /* An open database */
97907   const char *sql,       /* SQL to be executed */
97908   char ***resultp,       /* Result written to a char *[]  that this points to */
97909   int *nrow,             /* Number of result rows written here */
97910   int *ncolumn,          /* Number of result columns written here */
97911   char **errmsg          /* Error msg written here */
97912 );
97913 void sqlite3_free_table(char **result);
97914
97915 /*
97916 ** CAPI3REF: Formatted String Printing Functions {F17400}
97917 **
97918 ** These routines are workalikes of the "printf()" family of functions
97919 ** from the standard C library.
97920 **
97921 ** {F17401} The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
97922 ** results into memory obtained from [sqlite3_malloc()].
97923 ** {U17402} The strings returned by these two routines should be
97924 ** released by [sqlite3_free()]. {F17403}  Both routines return a
97925 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
97926 ** memory to hold the resulting string.
97927 **
97928 ** {F17404} In sqlite3_snprintf() routine is similar to "snprintf()" from
97929 ** the standard C library.  The result is written into the
97930 ** buffer supplied as the second parameter whose size is given by
97931 ** the first parameter. {END} Note that the order of the
97932 ** first two parameters is reversed from snprintf().  This is an
97933 ** historical accident that cannot be fixed without breaking
97934 ** backwards compatibility.  {F17405} Note also that sqlite3_snprintf()
97935 ** returns a pointer to its buffer instead of the number of
97936 ** characters actually written into the buffer. {END} We admit that
97937 ** the number of characters written would be a more useful return
97938 ** value but we cannot change the implementation of sqlite3_snprintf()
97939 ** now without breaking compatibility.
97940 **
97941 ** {F17406} As long as the buffer size is greater than zero, sqlite3_snprintf()
97942 ** guarantees that the buffer is always zero-terminated. {F17407} The first
97943 ** parameter "n" is the total size of the buffer, including space for
97944 ** the zero terminator.  {END} So the longest string that can be completely
97945 ** written will be n-1 characters.
97946 **
97947 ** These routines all implement some additional formatting
97948 ** options that are useful for constructing SQL statements.
97949 ** All of the usual printf formatting options apply.  In addition, there
97950 ** is are "%q", "%Q", and "%z" options.
97951 **
97952 ** {F17410} The %q option works like %s in that it substitutes a null-terminated
97953 ** string from the argument list.  But %q also doubles every '\'' character.
97954 ** %q is designed for use inside a string literal. {END} By doubling each '\''
97955 ** character it escapes that character and allows it to be inserted into
97956 ** the string.
97957 **
97958 ** For example, so some string variable contains text as follows:
97959 **
97960 ** <blockquote><pre>
97961 **  char *zText = "It's a happy day!";
97962 ** </pre></blockquote>
97963 **
97964 ** One can use this text in an SQL statement as follows:
97965 **
97966 ** <blockquote><pre>
97967 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
97968 **  sqlite3_exec(db, zSQL, 0, 0, 0);
97969 **  sqlite3_free(zSQL);
97970 ** </pre></blockquote>
97971 **
97972 ** Because the %q format string is used, the '\'' character in zText
97973 ** is escaped and the SQL generated is as follows:
97974 **
97975 ** <blockquote><pre>
97976 **  INSERT INTO table1 VALUES('It''s a happy day!')
97977 ** </pre></blockquote>
97978 **
97979 ** This is correct.  Had we used %s instead of %q, the generated SQL
97980 ** would have looked like this:
97981 **
97982 ** <blockquote><pre>
97983 **  INSERT INTO table1 VALUES('It's a happy day!');
97984 ** </pre></blockquote>
97985 **
97986 ** This second example is an SQL syntax error.  As a general rule you
97987 ** should always use %q instead of %s when inserting text into a string 
97988 ** literal.
97989 **
97990 ** {F17411} The %Q option works like %q except it also adds single quotes around
97991 ** the outside of the total string.  Or if the parameter in the argument
97992 ** list is a NULL pointer, %Q substitutes the text "NULL" (without single
97993 ** quotes) in place of the %Q option. {END}  So, for example, one could say:
97994 **
97995 ** <blockquote><pre>
97996 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
97997 **  sqlite3_exec(db, zSQL, 0, 0, 0);
97998 **  sqlite3_free(zSQL);
97999 ** </pre></blockquote>
98000 **
98001 ** The code above will render a correct SQL statement in the zSQL
98002 ** variable even if the zText variable is a NULL pointer.
98003 **
98004 ** {F17412} The "%z" formatting option works exactly like "%s" with the
98005 ** addition that after the string has been read and copied into
98006 ** the result, [sqlite3_free()] is called on the input string. {END}
98007 */
98008 char *sqlite3_mprintf(const char*,...);
98009 char *sqlite3_vmprintf(const char*, va_list);
98010 char *sqlite3_snprintf(int,char*,const char*, ...);
98011
98012 /*
98013 ** CAPI3REF: Memory Allocation Subsystem {F17300}
98014 **
98015 ** {F17301} The SQLite core  uses these three routines for all of its own
98016 ** internal memory allocation needs. {END}  "Core" in the previous sentence
98017 ** does not include operating-system specific VFS implementation.  The
98018 ** windows VFS uses native malloc and free for some operations.
98019 **
98020 ** {F17302} The sqlite3_malloc() routine returns a pointer to a block
98021 ** of memory at least N bytes in length, where N is the parameter.
98022 ** {F17303} If sqlite3_malloc() is unable to obtain sufficient free
98023 ** memory, it returns a NULL pointer.  {F17304} If the parameter N to
98024 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
98025 ** a NULL pointer.
98026 **
98027 ** {F17305} Calling sqlite3_free() with a pointer previously returned
98028 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
98029 ** that it might be reused.  {F17306} The sqlite3_free() routine is
98030 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
98031 ** to sqlite3_free() is harmless.  {U17307} After being freed, memory
98032 ** should neither be read nor written.  Even reading previously freed
98033 ** memory might result in a segmentation fault or other severe error.
98034 ** {U17309} Memory corruption, a segmentation fault, or other severe error
98035 ** might result if sqlite3_free() is called with a non-NULL pointer that
98036 ** was not obtained from sqlite3_malloc() or sqlite3_free().
98037 **
98038 ** {F17310} The sqlite3_realloc() interface attempts to resize a
98039 ** prior memory allocation to be at least N bytes, where N is the
98040 ** second parameter.  The memory allocation to be resized is the first
98041 ** parameter.  {F17311} If the first parameter to sqlite3_realloc()
98042 ** is a NULL pointer then its behavior is identical to calling
98043 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
98044 ** {F17312} If the second parameter to sqlite3_realloc() is zero or
98045 ** negative then the behavior is exactly the same as calling
98046 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
98047 ** {F17313} Sqlite3_realloc() returns a pointer to a memory allocation
98048 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
98049 ** {F17314} If M is the size of the prior allocation, then min(N,M) bytes
98050 ** of the prior allocation are copied into the beginning of buffer returned
98051 ** by sqlite3_realloc() and the prior allocation is freed.
98052 ** {F17315} If sqlite3_realloc() returns NULL, then the prior allocation
98053 ** is not freed.
98054 **
98055 ** {F17316} The memory returned by sqlite3_malloc() and sqlite3_realloc()
98056 ** is always aligned to at least an 8 byte boundary. {END}
98057 **
98058 ** {F17381} The default implementation
98059 ** of the memory allocation subsystem uses the malloc(), realloc()
98060 ** and free() provided by the standard C library. {F17382} However, if 
98061 ** SQLite is compiled with the following C preprocessor macro
98062 **
98063 ** <blockquote> SQLITE_MEMORY_SIZE=<i>NNN</i> </blockquote>
98064 **
98065 ** where <i>NNN</i> is an integer, then SQLite create a static
98066 ** array of at least <i>NNN</i> bytes in size and use that array
98067 ** for all of its dynamic memory allocation needs. {END}  Additional
98068 ** memory allocator options may be added in future releases.
98069 **
98070 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
98071 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
98072 ** implementation of these routines to be omitted.  That capability
98073 ** is no longer provided.  Only built-in memory allocators can be
98074 ** used.
98075 **
98076 ** The windows OS interface layer calls
98077 ** the system malloc() and free() directly when converting
98078 ** filenames between the UTF-8 encoding used by SQLite
98079 ** and whatever filename encoding is used by the particular windows
98080 ** installation.  Memory allocation errors are detected, but
98081 ** they are reported back as [SQLITE_CANTOPEN] or
98082 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
98083 */
98084 void *sqlite3_malloc(int);
98085 void *sqlite3_realloc(void*, int);
98086 void sqlite3_free(void*);
98087
98088 /*
98089 ** CAPI3REF: Memory Allocator Statistics {F17370}
98090 **
98091 ** In addition to the basic three allocation routines 
98092 ** [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()],
98093 ** the memory allocation subsystem included with the SQLite
98094 ** sources provides the interfaces shown here.
98095 **
98096 ** {F17371} The sqlite3_memory_used() routine returns the
98097 ** number of bytes of memory currently outstanding (malloced but not freed).
98098 ** {F17372} The value returned by sqlite3_memory_used() includes
98099 ** any overhead added by SQLite, but not overhead added by the
98100 ** library malloc() that backs the sqlite3_malloc() implementation.
98101 ** {F17373} The sqlite3_memory_highwater() routines returns the
98102 ** maximum number of bytes that have been outstanding at any time
98103 ** since the highwater mark was last reset.
98104 ** {F17374} The byte count returned by sqlite3_memory_highwater()
98105 ** uses the same byte counting rules as sqlite3_memory_used(). {END}
98106 ** In other words, overhead added internally by SQLite is counted,
98107 ** but overhead from the underlying system malloc is not.
98108 ** {F17375} If the parameter to sqlite3_memory_highwater() is true,
98109 ** then the highwater mark is reset to the current value of
98110 ** sqlite3_memory_used() and the prior highwater mark (before the
98111 ** reset) is returned.  {F17376}  If the parameter to 
98112 ** sqlite3_memory_highwater() is zero, then the highwater mark is
98113 ** unchanged.
98114 */
98115 sqlite3_int64 sqlite3_memory_used(void);
98116 sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
98117
98118 /*
98119 ** CAPI3REF: Compile-Time Authorization Callbacks {F12500}
98120 **
98121 ** {F12501} This routine registers a authorizer callback with a particular
98122 ** database connection, supplied in the first argument. {F12502}
98123 ** The authorizer callback is invoked as SQL statements are being compiled
98124 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
98125 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  {F12503} At various
98126 ** points during the compilation process, as logic is being created
98127 ** to perform various actions, the authorizer callback is invoked to
98128 ** see if those actions are allowed.  The authorizer callback should
98129 ** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the
98130 ** specific action but allow the SQL statement to continue to be
98131 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
98132 ** rejected with an error.  {F12504} If the authorizer callback returns
98133 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
98134 ** then [sqlite3_prepare_v2()] or equivalent call that triggered
98135 ** the authorizer shall
98136 ** fail with an SQLITE_ERROR error code and an appropriate error message. {END}
98137 **
98138 ** When the callback returns [SQLITE_OK], that means the operation
98139 ** requested is ok.  {F12505} When the callback returns [SQLITE_DENY], the
98140 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
98141 ** authorizer shall fail
98142 ** with an SQLITE_ERROR error code and an error message explaining that
98143 ** access is denied. {F12506} If the authorizer code (the 2nd parameter
98144 ** to the authorizer callback is anything other than [SQLITE_READ], then
98145 ** a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. 
98146 ** If the authorizer code is [SQLITE_READ] and the callback returns
98147 ** [SQLITE_IGNORE] then the prepared statement is constructed to
98148 ** insert a NULL value in place of the table column that would have
98149 ** been read if [SQLITE_OK] had been returned. {END}
98150 **
98151 ** {F12510} The first parameter to the authorizer callback is a copy of
98152 ** the third parameter to the sqlite3_set_authorizer() interface.
98153 ** {F12511} The second parameter to the callback is an integer 
98154 ** [SQLITE_COPY | action code] that specifies the particular action
98155 ** to be authorized. {END} The available action codes are
98156 ** [SQLITE_COPY | documented separately].  {F12512} The third through sixth
98157 ** parameters to the callback are zero-terminated strings that contain 
98158 ** additional details about the action to be authorized. {END}
98159 **
98160 ** An authorizer is used when preparing SQL statements from an untrusted
98161 ** source, to ensure that the SQL statements do not try to access data
98162 ** that they are not allowed to see, or that they do not try to
98163 ** execute malicious statements that damage the database.  For
98164 ** example, an application may allow a user to enter arbitrary
98165 ** SQL queries for evaluation by a database.  But the application does
98166 ** not want the user to be able to make arbitrary changes to the
98167 ** database.  An authorizer could then be put in place while the
98168 ** user-entered SQL is being prepared that disallows everything
98169 ** except SELECT statements.  
98170 **
98171 ** {F12520} Only a single authorizer can be in place on a database connection
98172 ** at a time.  Each call to sqlite3_set_authorizer overrides the
98173 ** previous call. {F12521}  A NULL authorizer means that no authorization
98174 ** callback is invoked.  {F12522} The default authorizer is NULL. {END}
98175 **
98176 ** Note that the authorizer callback is invoked only during 
98177 ** [sqlite3_prepare()] or its variants.  {F12523} Authorization is not
98178 ** performed during statement evaluation in [sqlite3_step()]. {END}
98179 */
98180 int sqlite3_set_authorizer(
98181   sqlite3*,
98182   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
98183   void *pUserData
98184 );
98185
98186 /*
98187 ** CAPI3REF: Authorizer Return Codes {F12590}
98188 **
98189 ** The [sqlite3_set_authorizer | authorizer callback function] must
98190 ** return either [SQLITE_OK] or one of these two constants in order
98191 ** to signal SQLite whether or not the action is permitted.  See the
98192 ** [sqlite3_set_authorizer | authorizer documentation] for additional
98193 ** information.
98194 */
98195 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
98196 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
98197
98198 /*
98199 ** CAPI3REF: Authorizer Action Codes {F12550}
98200 **
98201 ** The [sqlite3_set_authorizer()] interface registers a callback function
98202 ** that is invoked to authorizer certain SQL statement actions.  {F12551} The
98203 ** second parameter to the callback is an integer code that specifies
98204 ** what action is being authorized.  These are the integer action codes that
98205 ** the authorizer callback may be passed. {END}
98206 **
98207 ** These action code values signify what kind of operation is to be 
98208 ** authorized.  {F12552} The 3rd and 4th parameters to the authorization
98209 ** callback function will be parameters or NULL depending on which of these
98210 ** codes is used as the second parameter. {F12553} The 5th parameter to the
98211 ** authorizer callback is the name of the database ("main", "temp", 
98212 ** etc.) if applicable. {F12554} The 6th parameter to the authorizer callback
98213 ** is the name of the inner-most trigger or view that is responsible for
98214 ** the access attempt or NULL if this access attempt is directly from 
98215 ** top-level SQL code.
98216 */
98217 /******************************************* 3rd ************ 4th ***********/
98218 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
98219 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
98220 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
98221 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
98222 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
98223 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
98224 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
98225 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
98226 #define SQLITE_DELETE                9   /* Table Name      NULL            */
98227 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
98228 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
98229 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
98230 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
98231 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
98232 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
98233 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
98234 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
98235 #define SQLITE_INSERT               18   /* Table Name      NULL            */
98236 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
98237 #define SQLITE_READ                 20   /* Table Name      Column Name     */
98238 #define SQLITE_SELECT               21   /* NULL            NULL            */
98239 #define SQLITE_TRANSACTION          22   /* NULL            NULL            */
98240 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
98241 #define SQLITE_ATTACH               24   /* Filename        NULL            */
98242 #define SQLITE_DETACH               25   /* Database Name   NULL            */
98243 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
98244 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
98245 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
98246 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
98247 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
98248 #define SQLITE_FUNCTION             31   /* Function Name   NULL            */
98249 #define SQLITE_COPY                  0   /* No longer used */
98250
98251 /*
98252 ** CAPI3REF: Tracing And Profiling Functions {F12280}
98253 **
98254 ** These routines register callback functions that can be used for
98255 ** tracing and profiling the execution of SQL statements.
98256 **
98257 ** {F12281} The callback function registered by sqlite3_trace() is invoked
98258 ** at the first [sqlite3_step()] for the evaluation of an SQL statement.
98259 ** {F12282} Only a single trace callback can be registered at a time.
98260 ** Each call to sqlite3_trace() overrides the previous.  {F12283} A
98261 ** NULL callback for sqlite3_trace() disables tracing.  {F12284} The
98262 ** first argument to the trace callback is a copy of the pointer which
98263 ** was the 3rd argument to sqlite3_trace.  {F12285} The second argument
98264 ** to the trace callback is a zero-terminated UTF8 string containing
98265 ** the original text of the SQL statement as it was passed into
98266 ** [sqlite3_prepare_v2()] or the equivalent. {END}  Note that the
98267 ** host parameter are not expanded in the SQL statement text.
98268 **
98269 ** {F12287} The callback function registered by sqlite3_profile() is invoked
98270 ** as each SQL statement finishes.  {F12288} The first parameter to the
98271 ** profile callback is a copy of the 3rd parameter to sqlite3_profile().
98272 ** {F12289} The second parameter to the profile callback is a
98273 ** zero-terminated UTF-8 string that contains the complete text of
98274 ** the SQL statement as it was processed by [sqlite3_prepare_v2()] or
98275 ** the equivalent.  {F12290} The third parameter to the profile 
98276 ** callback is an estimate of the number of nanoseconds of
98277 ** wall-clock time required to run the SQL statement from start
98278 ** to finish. {END}  
98279 **
98280 ** The sqlite3_profile() API is currently considered experimental and
98281 ** is subject to change.
98282 */
98283 void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
98284 void *sqlite3_profile(sqlite3*,
98285    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
98286
98287 /*
98288 ** CAPI3REF: Query Progress Callbacks {F12910}
98289 **
98290 ** {F12911} This routine configures a callback function - the
98291 ** progress callback - that is invoked periodically during long
98292 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
98293 ** [sqlite3_get_table()]. {END}  An example use for this 
98294 ** interface is to keep a GUI updated during a large query.
98295 **
98296 ** {F12912} The progress callback is invoked once for every N virtual
98297 ** machine opcodes, where N is the second argument to this function.
98298 ** {F12913} The progress callback itself is identified by the third
98299 ** argument to this function. {F12914} The fourth argument to this
98300 ** function is a void pointer passed to the progress callback
98301 ** function each time it is invoked. {END}
98302 **
98303 ** {F12915} If a call to [sqlite3_exec()], [sqlite3_step()], or
98304 ** [sqlite3_get_table()] results in fewer than N opcodes being executed,
98305 ** then the progress callback is never invoked. {END}
98306 ** 
98307 ** {F12916} Only a single progress callback function may be registered for each
98308 ** open database connection.  Every call to sqlite3_progress_handler()
98309 ** overwrites the results of the previous call. {F12917}
98310 ** To remove the progress callback altogether, pass NULL as the third
98311 ** argument to this function. {END}
98312 **
98313 ** {F12918} If the progress callback returns a result other than 0, then
98314 ** the current query is immediately terminated and any database changes
98315 ** rolled back. {F12919}
98316 ** The containing [sqlite3_exec()], [sqlite3_step()], or
98317 ** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. {END}  This feature
98318 ** can be used, for example, to implement the "Cancel" button on a
98319 ** progress dialog box in a GUI.
98320 */
98321 void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
98322
98323 /*
98324 ** CAPI3REF: Opening A New Database Connection {F12700}
98325 **
98326 ** {F12701} These routines open an SQLite database file whose name
98327 ** is given by the filename argument.
98328 ** {F12702} The filename argument is interpreted as UTF-8
98329 ** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16
98330 ** in the native byte order for [sqlite3_open16()].
98331 ** {F12703} An [sqlite3*] handle is returned in *ppDb, even
98332 ** if an error occurs.  {F12723} (Exception: if SQLite is unable
98333 ** to allocate memory to hold the [sqlite3] object, a NULL will
98334 ** be written into *ppDb instead of a pointer to the [sqlite3] object.)
98335 ** {F12704} If the database is opened (and/or created)
98336 ** successfully, then [SQLITE_OK] is returned.  {F12705} Otherwise an
98337 ** error code is returned.  {F12706} The
98338 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()]  routines can be used to obtain
98339 ** an English language description of the error.
98340 **
98341 ** {F12707} The default encoding for the database will be UTF-8 if
98342 ** [sqlite3_open()] or [sqlite3_open_v2()] is called and
98343 ** UTF-16 in the native byte order if [sqlite3_open16()] is used.
98344 **
98345 ** {F12708} Whether or not an error occurs when it is opened, resources
98346 ** associated with the [sqlite3*] handle should be released by passing it
98347 ** to [sqlite3_close()] when it is no longer required.
98348 **
98349 ** {F12709} The [sqlite3_open_v2()] interface works like [sqlite3_open()] 
98350 ** except that it acccepts two additional parameters for additional control
98351 ** over the new database connection.  {F12710} The flags parameter can be
98352 ** one of:
98353 **
98354 ** <ol>
98355 ** <li>  [SQLITE_OPEN_READONLY]
98356 ** <li>  [SQLITE_OPEN_READWRITE]
98357 ** <li>  [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
98358 ** </ol>
98359 **
98360 ** {F12711} The first value opens the database read-only. 
98361 ** {F12712} If the database does not previously exist, an error is returned.
98362 ** {F12713} The second option opens
98363 ** the database for reading and writing if possible, or reading only if
98364 ** if the file is write protected.  {F12714} In either case the database
98365 ** must already exist or an error is returned.  {F12715} The third option
98366 ** opens the database for reading and writing and creates it if it does
98367 ** not already exist. {F12716}
98368 ** The third options is behavior that is always used for [sqlite3_open()]
98369 ** and [sqlite3_open16()].
98370 **
98371 ** {F12717} If the filename is ":memory:", then an private
98372 ** in-memory database is created for the connection. {F12718} This in-memory
98373 ** database will vanish when the database connection is closed. {END}  Future
98374 ** version of SQLite might make use of additional special filenames
98375 ** that begin with the ":" character.  It is recommended that 
98376 ** when a database filename really does begin with
98377 ** ":" that you prefix the filename with a pathname like "./" to
98378 ** avoid ambiguity.
98379 **
98380 ** {F12719} If the filename is an empty string, then a private temporary
98381 ** on-disk database will be created.  {F12720} This private database will be
98382 ** automatically deleted as soon as the database connection is closed.
98383 **
98384 ** {F12721} The fourth parameter to sqlite3_open_v2() is the name of the
98385 ** [sqlite3_vfs] object that defines the operating system 
98386 ** interface that the new database connection should use.  {F12722} If the
98387 ** fourth parameter is a NULL pointer then the default [sqlite3_vfs]
98388 ** object is used. {END}
98389 **
98390 ** <b>Note to windows users:</b>  The encoding used for the filename argument
98391 ** of [sqlite3_open()] and [sqlite3_open_v2()] must be UTF-8, not whatever
98392 ** codepage is currently defined.  Filenames containing international
98393 ** characters must be converted to UTF-8 prior to passing them into
98394 ** [sqlite3_open()] or [sqlite3_open_v2()].
98395 */
98396 int sqlite3_open(
98397   const char *filename,   /* Database filename (UTF-8) */
98398   sqlite3 **ppDb          /* OUT: SQLite db handle */
98399 );
98400 int sqlite3_open16(
98401   const void *filename,   /* Database filename (UTF-16) */
98402   sqlite3 **ppDb          /* OUT: SQLite db handle */
98403 );
98404 int sqlite3_open_v2(
98405   const char *filename,   /* Database filename (UTF-8) */
98406   sqlite3 **ppDb,         /* OUT: SQLite db handle */
98407   int flags,              /* Flags */
98408   const char *zVfs        /* Name of VFS module to use */
98409 );
98410
98411 /*
98412 ** CAPI3REF: Error Codes And Messages {F12800}
98413 **
98414 ** {F12801} The sqlite3_errcode() interface returns the numeric
98415 ** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code]
98416 ** for the most recent failed sqlite3_* API call associated
98417 ** with [sqlite3] handle 'db'. {U12802} If a prior API call failed but the
98418 ** most recent API call succeeded, the return value from sqlite3_errcode()
98419 ** is undefined. {END}
98420 **
98421 ** {F12803} The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
98422 ** text that describes the error, as either UTF8 or UTF16 respectively.
98423 ** {F12804} Memory to hold the error message string is managed internally.
98424 ** {U12805} The 
98425 ** string may be overwritten or deallocated by subsequent calls to SQLite
98426 ** interface functions. {END}
98427 **
98428 ** {F12806} Calls to many sqlite3_* functions set the error code and
98429 ** string returned by [sqlite3_errcode()], [sqlite3_errmsg()], and
98430 ** [sqlite3_errmsg16()] overwriting the previous values.  {F12807}
98431 ** Except, calls to [sqlite3_errcode()],
98432 ** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the
98433 ** results of future invocations.  {F12808} Calls to API routines that
98434 ** do not return an error code (example: [sqlite3_data_count()]) do not
98435 ** change the error code returned by this routine.  {F12809} Interfaces that
98436 ** are not associated with a specific database connection (examples:
98437 ** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change
98438 ** the return code. {END}
98439 **
98440 ** {F12810} Assuming no other intervening sqlite3_* API calls are made,
98441 ** the error code returned by this function is associated with the same
98442 ** error as the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()].
98443 */
98444 int sqlite3_errcode(sqlite3 *db);
98445 const char *sqlite3_errmsg(sqlite3*);
98446 const void *sqlite3_errmsg16(sqlite3*);
98447
98448 /*
98449 ** CAPI3REF: SQL Statement Object {F13000}
98450 **
98451 ** An instance of this object represent single SQL statements.  This
98452 ** object is variously known as a "prepared statement" or a 
98453 ** "compiled SQL statement" or simply as a "statement".
98454 ** 
98455 ** The life of a statement object goes something like this:
98456 **
98457 ** <ol>
98458 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
98459 **      function.
98460 ** <li> Bind values to host parameters using
98461 **      [sqlite3_bind_blob | sqlite3_bind_* interfaces].
98462 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
98463 ** <li> Reset the statement using [sqlite3_reset()] then go back
98464 **      to step 2.  Do this zero or more times.
98465 ** <li> Destroy the object using [sqlite3_finalize()].
98466 ** </ol>
98467 **
98468 ** Refer to documentation on individual methods above for additional
98469 ** information.
98470 */
98471 typedef struct sqlite3_stmt sqlite3_stmt;
98472
98473 /*
98474 ** CAPI3REF: Compiling An SQL Statement {F13010}
98475 **
98476 ** To execute an SQL query, it must first be compiled into a byte-code
98477 ** program using one of these routines. 
98478 **
98479 ** {F13011} The first argument "db" is an [sqlite3 | SQLite database handle] 
98480 ** obtained from a prior call to [sqlite3_open()], [sqlite3_open_v2()]
98481 ** or [sqlite3_open16()]. {F13012}
98482 ** The second argument "zSql" is the statement to be compiled, encoded
98483 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
98484 ** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2()
98485 ** use UTF-16. {END}
98486 **
98487 ** {F13013} If the nByte argument is less
98488 ** than zero, then zSql is read up to the first zero terminator.
98489 ** {F13014} If nByte is non-negative, then it is the maximum number of 
98490 ** bytes read from zSql.  When nByte is non-negative, the
98491 ** zSql string ends at either the first '\000' or '\u0000' character or 
98492 ** until the nByte-th byte, whichever comes first. {END}
98493 **
98494 ** {F13015} *pzTail is made to point to the first byte past the end of the
98495 ** first SQL statement in zSql.  These routines only compiles the first
98496 ** statement in zSql, so *pzTail is left pointing to what remains
98497 ** uncompiled. {END}
98498 **
98499 ** {F13016} *ppStmt is left pointing to a compiled 
98500 ** [sqlite3_stmt | SQL statement structure] that can be
98501 ** executed using [sqlite3_step()].  Or if there is an error, *ppStmt may be
98502 ** set to NULL.  {F13017} If the input text contains no SQL (if the input
98503 ** is and empty string or a comment) then *ppStmt is set to NULL.
98504 ** {U13018} The calling procedure is responsible for deleting the
98505 ** compiled SQL statement
98506 ** using [sqlite3_finalize()] after it has finished with it.
98507 **
98508 ** {F13019} On success, [SQLITE_OK] is returned.  Otherwise an 
98509 ** [SQLITE_ERROR | error code] is returned. {END}
98510 **
98511 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
98512 ** recommended for all new programs. The two older interfaces are retained
98513 ** for backwards compatibility, but their use is discouraged.
98514 ** {F13020} In the "v2" interfaces, the prepared statement
98515 ** that is returned (the [sqlite3_stmt] object) contains a copy of the 
98516 ** original SQL text. {END} This causes the [sqlite3_step()] interface to
98517 ** behave a differently in two ways:
98518 **
98519 ** <ol>
98520 ** <li>{F13022}
98521 ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
98522 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
98523 ** statement and try to run it again. {F12023} If the schema has changed in
98524 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
98525 ** return [SQLITE_SCHEMA].  {END} But unlike the legacy behavior, 
98526 ** [SQLITE_SCHEMA] is now a fatal error.  {F12024} Calling
98527 ** [sqlite3_prepare_v2()] again will not make the
98528 ** error go away.  {F12025} Note: use [sqlite3_errmsg()] to find the text
98529 ** of the parsing error that results in an [SQLITE_SCHEMA] return. {END}
98530 ** </li>
98531 **
98532 ** <li>
98533 ** {F13030} When an error occurs, 
98534 ** [sqlite3_step()] will return one of the detailed 
98535 ** [SQLITE_ERROR | result codes] or
98536 ** [SQLITE_IOERR_READ | extended result codes].  {F13031}
98537 ** The legacy behavior was that [sqlite3_step()] would only return a generic
98538 ** [SQLITE_ERROR] result code and you would have to make a second call to
98539 ** [sqlite3_reset()] in order to find the underlying cause of the problem.
98540 ** {F13032}
98541 ** With the "v2" prepare interfaces, the underlying reason for the error is
98542 ** returned immediately. {END}
98543 ** </li>
98544 ** </ol>
98545 */
98546 int sqlite3_prepare(
98547   sqlite3 *db,            /* Database handle */
98548   const char *zSql,       /* SQL statement, UTF-8 encoded */
98549   int nByte,              /* Maximum length of zSql in bytes. */
98550   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
98551   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
98552 );
98553 int sqlite3_prepare_v2(
98554   sqlite3 *db,            /* Database handle */
98555   const char *zSql,       /* SQL statement, UTF-8 encoded */
98556   int nByte,              /* Maximum length of zSql in bytes. */
98557   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
98558   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
98559 );
98560 int sqlite3_prepare16(
98561   sqlite3 *db,            /* Database handle */
98562   const void *zSql,       /* SQL statement, UTF-16 encoded */
98563   int nByte,              /* Maximum length of zSql in bytes. */
98564   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
98565   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
98566 );
98567 int sqlite3_prepare16_v2(
98568   sqlite3 *db,            /* Database handle */
98569   const void *zSql,       /* SQL statement, UTF-16 encoded */
98570   int nByte,              /* Maximum length of zSql in bytes. */
98571   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
98572   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
98573 );
98574
98575 /*
98576 ** CAPIREF: Retrieving Statement SQL {F13100}
98577 **
98578 ** {F13101} If the compiled SQL statement passed as an argument was
98579 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()],
98580 ** then this function returns a pointer to a zero-terminated string
98581 ** containing a copy of the original SQL statement. {F13102} The
98582 ** pointer is valid until the statement
98583 ** is deleted using sqlite3_finalize().
98584 ** {F13103} The string returned by sqlite3_sql() is always UTF8 even
98585 ** if a UTF16 string was originally entered using [sqlite3_prepare16_v2()]
98586 ** or the equivalent.
98587 **
98588 ** {F13104} If the statement was compiled using either of the legacy
98589 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this
98590 ** function returns NULL.
98591 */
98592 const char *sqlite3_sql(sqlite3_stmt *pStmt);
98593
98594 /*
98595 ** CAPI3REF:  Dynamically Typed Value Object  {F15000}
98596 **
98597 ** {F15001} SQLite uses the sqlite3_value object to represent all values
98598 ** that are or can be stored in a database table. {END}
98599 ** SQLite uses dynamic typing for the values it stores.  
98600 ** {F15002} Values stored in sqlite3_value objects can be
98601 ** be integers, floating point values, strings, BLOBs, or NULL.
98602 */
98603 typedef struct Mem sqlite3_value;
98604
98605 /*
98606 ** CAPI3REF:  SQL Function Context Object {F16001}
98607 **
98608 ** The context in which an SQL function executes is stored in an
98609 ** sqlite3_context object.  {F16002} A pointer to an sqlite3_context
98610 ** object is always first parameter to application-defined SQL functions.
98611 */
98612 typedef struct sqlite3_context sqlite3_context;
98613
98614 /*
98615 ** CAPI3REF:  Binding Values To Prepared Statements {F13500}
98616 **
98617 ** {F13501} In the SQL strings input to [sqlite3_prepare_v2()] and its
98618 ** variants, literals may be replace by a parameter in one
98619 ** of these forms:
98620 **
98621 ** <ul>
98622 ** <li>  ?
98623 ** <li>  ?NNN
98624 ** <li>  :AAA
98625 ** <li>  @AAA
98626 ** <li>  $VVV
98627 ** </ul>
98628 **
98629 ** In the parameter forms shown above NNN is an integer literal,
98630 ** AAA is an alphanumeric identifier and VVV is a variable name according
98631 ** to the syntax rules of the TCL programming language. {END}
98632 ** The values of these parameters (also called "host parameter names")
98633 ** can be set using the sqlite3_bind_*() routines defined here.
98634 **
98635 ** {F13502} The first argument to the sqlite3_bind_*() routines always
98636 ** is a pointer to the [sqlite3_stmt] object returned from
98637 ** [sqlite3_prepare_v2()] or its variants.  {F13503} The second
98638 ** argument is the index of the parameter to be set.  {F13504} The
98639 ** first parameter has an index of 1.  {F13505} When the same named
98640 ** parameter is used more than once, second and subsequent
98641 ** occurrences have the same index as the first occurrence. 
98642 ** {F13506} The index for named parameters can be looked up using the
98643 ** [sqlite3_bind_parameter_name()] API if desired.  {F13507} The index
98644 ** for "?NNN" parameters is the value of NNN.
98645 ** {F13508} The NNN value must be between 1 and the compile-time
98646 ** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). {END}
98647 ** See <a href="limits.html">limits.html</a> for additional information.
98648 **
98649 ** {F13509} The third argument is the value to bind to the parameter. {END}
98650 **
98651 ** {F13510} In those
98652 ** routines that have a fourth argument, its value is the number of bytes
98653 ** in the parameter.  To be clear: the value is the number of bytes in the
98654 ** string, not the number of characters. {F13511}  The number
98655 ** of bytes does not include the zero-terminator at the end of strings.
98656 ** {F13512}
98657 ** If the fourth parameter is negative, the length of the string is
98658 ** number of bytes up to the first zero terminator. {END}
98659 **
98660 ** {F13513}
98661 ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
98662 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
98663 ** text after SQLite has finished with it. {F13514} If the fifth argument is
98664 ** the special value [SQLITE_STATIC], then the library assumes that the
98665 ** information is in static, unmanaged space and does not need to be freed.
98666 ** {F13515} If the fifth argument has the value [SQLITE_TRANSIENT], then
98667 ** SQLite makes its own private copy of the data immediately, before
98668 ** the sqlite3_bind_*() routine returns. {END}
98669 **
98670 ** {F13520} The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
98671 ** is filled with zeros.  {F13521} A zeroblob uses a fixed amount of memory
98672 ** (just an integer to hold it size) while it is being processed. {END}
98673 ** Zeroblobs are intended to serve as place-holders for BLOBs whose
98674 ** content is later written using 
98675 ** [sqlite3_blob_open | increment BLOB I/O] routines. {F13522} A negative
98676 ** value for the zeroblob results in a zero-length BLOB. {END}
98677 **
98678 ** {F13530} The sqlite3_bind_*() routines must be called after
98679 ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and
98680 ** before [sqlite3_step()]. {F13531}
98681 ** Bindings are not cleared by the [sqlite3_reset()] routine.
98682 ** {F13532} Unbound parameters are interpreted as NULL. {END}
98683 **
98684 ** {F13540} These routines return [SQLITE_OK] on success or an error code if
98685 ** anything goes wrong.  {F13541} [SQLITE_RANGE] is returned if the parameter
98686 ** index is out of range.  {F13542} [SQLITE_NOMEM] is returned if malloc fails.
98687 ** {F13543} [SQLITE_MISUSE] is returned if these routines are called on a
98688 ** virtual machine that is the wrong state or which has already been finalized.
98689 */
98690 int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
98691 int sqlite3_bind_double(sqlite3_stmt*, int, double);
98692 int sqlite3_bind_int(sqlite3_stmt*, int, int);
98693 int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
98694 int sqlite3_bind_null(sqlite3_stmt*, int);
98695 int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
98696 int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
98697 int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
98698 int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
98699
98700 /*
98701 ** CAPI3REF: Number Of Host Parameters {F13600}
98702 **
98703 ** {F13601} Return the largest host parameter index in the precompiled
98704 ** statement given as the argument. {F13602} When the host parameters
98705 ** are of the forms like ":AAA", "$VVV", "@AAA", or "?",
98706 ** then they are assigned sequential increasing numbers beginning
98707 ** with one, so the value returned is the number of parameters.
98708 ** {F13603} However
98709 ** if the same host parameter name is used multiple times, each occurrance
98710 ** is given the same number, so the value returned in that case is the number
98711 ** of unique host parameter names. {F13604} If host parameters of the
98712 ** form "?NNN" are used (where NNN is an integer) then there might be
98713 ** gaps in the numbering and the value returned by this interface is
98714 ** the index of the host parameter with the largest index value. {END}
98715 **
98716 ** {U13605} The prepared statement must not be [sqlite3_finalize | finalized]
98717 ** prior to this routine returning.  Otherwise the results are undefined
98718 ** and probably undesirable.
98719 */
98720 int sqlite3_bind_parameter_count(sqlite3_stmt*);
98721
98722 /*
98723 ** CAPI3REF: Name Of A Host Parameter {F13620}
98724 **
98725 ** {F13621} This routine returns a pointer to the name of the n-th
98726 ** parameter in a [sqlite3_stmt | prepared statement]. {F13622}
98727 ** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name
98728 ** which is the string ":AAA" or "@AAA" or "$VVV". 
98729 ** In other words, the initial ":" or "$" or "@"
98730 ** is included as part of the name.  {F13626}
98731 ** Parameters of the form "?" or "?NNN" have no name.
98732 **
98733 ** {F13623} The first host parameter has an index of 1, not 0.
98734 **
98735 ** {F13624} If the value n is out of range or if the n-th parameter is
98736 ** nameless, then NULL is returned.  {F13625} The returned string is
98737 ** always in the UTF-8 encoding even if the named parameter was
98738 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
98739 ** [sqlite3_prepare16_v2()].
98740 */
98741 const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
98742
98743 /*
98744 ** CAPI3REF: Index Of A Parameter With A Given Name {F13640}
98745 **
98746 ** {F13641} This routine returns the index of a host parameter with the
98747 ** given name.  {F13642} The name must match exactly.  {F13643}
98748 ** If no parameter with the given name is found, return 0.
98749 ** {F13644} Parameter names must be UTF8.
98750 */
98751 int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
98752
98753 /*
98754 ** CAPI3REF: Reset All Bindings On A Prepared Statement {F13660}
98755 **
98756 ** {F13661} Contrary to the intuition of many, [sqlite3_reset()] does not
98757 ** reset the [sqlite3_bind_blob | bindings] on a 
98758 ** [sqlite3_stmt | prepared statement]. {F13662} Use this routine to
98759 ** reset all host parameters to NULL.
98760 */
98761 int sqlite3_clear_bindings(sqlite3_stmt*);
98762
98763 /*
98764 ** CAPI3REF: Number Of Columns In A Result Set {F13710}
98765 **
98766 ** {F13711} Return the number of columns in the result set returned by the 
98767 ** [sqlite3_stmt | compiled SQL statement]. {F13712} This routine returns 0
98768 ** if pStmt is an SQL statement that does not return data (for 
98769 ** example an UPDATE).
98770 */
98771 int sqlite3_column_count(sqlite3_stmt *pStmt);
98772
98773 /*
98774 ** CAPI3REF: Column Names In A Result Set {F13720}
98775 **
98776 ** {F13721} These routines return the name assigned to a particular column
98777 ** in the result set of a SELECT statement.  {F13722} The sqlite3_column_name()
98778 ** interface returns a pointer to a zero-terminated UTF8 string
98779 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
98780 ** UTF16 string. {F13723}  The first parameter is the
98781 ** [sqlite3_stmt | prepared statement] that implements the SELECT statement.
98782 ** The second parameter is the column number.  The left-most column is
98783 ** number 0.
98784 **
98785 ** {F13724} The returned string pointer is valid until either the 
98786 ** [sqlite3_stmt | prepared statement] is destroyed by [sqlite3_finalize()]
98787 ** or until the next call sqlite3_column_name() or sqlite3_column_name16()
98788 ** on the same column.
98789 **
98790 ** {F13725} If sqlite3_malloc() fails during the processing of either routine
98791 ** (for example during a conversion from UTF-8 to UTF-16) then a
98792 ** NULL pointer is returned.
98793 */
98794 const char *sqlite3_column_name(sqlite3_stmt*, int N);
98795 const void *sqlite3_column_name16(sqlite3_stmt*, int N);
98796
98797 /*
98798 ** CAPI3REF: Source Of Data In A Query Result {F13740}
98799 **
98800 ** {F13741} These routines provide a means to determine what column of what
98801 ** table in which database a result of a SELECT statement comes from.
98802 ** {F13742} The name of the database or table or column can be returned as
98803 ** either a UTF8 or UTF16 string.  {F13743} The _database_ routines return
98804 ** the database name, the _table_ routines return the table name, and
98805 ** the origin_ routines return the column name. {F13744}
98806 ** The returned string is valid until
98807 ** the [sqlite3_stmt | prepared statement] is destroyed using
98808 ** [sqlite3_finalize()] or until the same information is requested
98809 ** again in a different encoding.
98810 **
98811 ** {F13745} The names returned are the original un-aliased names of the
98812 ** database, table, and column.
98813 **
98814 ** {F13746} The first argument to the following calls is a 
98815 ** [sqlite3_stmt | compiled SQL statement].
98816 ** {F13747} These functions return information about the Nth column returned by 
98817 ** the statement, where N is the second function argument.
98818 **
98819 ** {F13748} If the Nth column returned by the statement is an expression
98820 ** or subquery and is not a column value, then all of these functions
98821 ** return NULL.  {F13749} Otherwise, they return the 
98822 ** name of the attached database, table and column that query result
98823 ** column was extracted from.
98824 **
98825 ** {F13750} As with all other SQLite APIs, those postfixed with "16" return
98826 ** UTF-16 encoded strings, the other functions return UTF-8. {END}
98827 **
98828 ** These APIs are only available if the library was compiled with the 
98829 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
98830 **
98831 ** {U13751}
98832 ** If two or more threads call one or more of these routines against the same
98833 ** prepared statement and column at the same time then the results are
98834 ** undefined.
98835 */
98836 const char *sqlite3_column_database_name(sqlite3_stmt*,int);
98837 const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
98838 const char *sqlite3_column_table_name(sqlite3_stmt*,int);
98839 const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
98840 const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
98841 const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
98842
98843 /*
98844 ** CAPI3REF: Declared Datatype Of A Query Result {F13760}
98845 **
98846 ** The first parameter is a [sqlite3_stmt | compiled SQL statement]. 
98847 ** {F13761} If this statement is a SELECT statement and the Nth column of the 
98848 ** returned result set of that SELECT is a table column (not an
98849 ** expression or subquery) then the declared type of the table
98850 ** column is returned.  {F13762} If the Nth column of the result set is an
98851 ** expression or subquery, then a NULL pointer is returned.
98852 ** {F13763} The returned string is always UTF-8 encoded.  {END} 
98853 ** For example, in the database schema:
98854 **
98855 ** CREATE TABLE t1(c1 VARIANT);
98856 **
98857 ** And the following statement compiled:
98858 **
98859 ** SELECT c1 + 1, c1 FROM t1;
98860 **
98861 ** Then this routine would return the string "VARIANT" for the second
98862 ** result column (i==1), and a NULL pointer for the first result column
98863 ** (i==0).
98864 **
98865 ** SQLite uses dynamic run-time typing.  So just because a column
98866 ** is declared to contain a particular type does not mean that the
98867 ** data stored in that column is of the declared type.  SQLite is
98868 ** strongly typed, but the typing is dynamic not static.  Type
98869 ** is associated with individual values, not with the containers
98870 ** used to hold those values.
98871 */
98872 const char *sqlite3_column_decltype(sqlite3_stmt *, int i);
98873 const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
98874
98875 /* 
98876 ** CAPI3REF:  Evaluate An SQL Statement {F13200}
98877 **
98878 ** After an [sqlite3_stmt | SQL statement] has been prepared with a call
98879 ** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of
98880 ** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()],
98881 ** then this function must be called one or more times to evaluate the 
98882 ** statement.
98883 **
98884 ** The details of the behavior of this sqlite3_step() interface depend
98885 ** on whether the statement was prepared using the newer "v2" interface
98886 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
98887 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
98888 ** new "v2" interface is recommended for new applications but the legacy
98889 ** interface will continue to be supported.
98890 **
98891 ** In the lagacy interface, the return value will be either [SQLITE_BUSY], 
98892 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
98893 ** With the "v2" interface, any of the other [SQLITE_OK | result code]
98894 ** or [SQLITE_IOERR_READ | extended result code] might be returned as
98895 ** well.
98896 **
98897 ** [SQLITE_BUSY] means that the database engine was unable to acquire the
98898 ** database locks it needs to do its job.  If the statement is a COMMIT
98899 ** or occurs outside of an explicit transaction, then you can retry the
98900 ** statement.  If the statement is not a COMMIT and occurs within a
98901 ** explicit transaction then you should rollback the transaction before
98902 ** continuing.
98903 **
98904 ** [SQLITE_DONE] means that the statement has finished executing
98905 ** successfully.  sqlite3_step() should not be called again on this virtual
98906 ** machine without first calling [sqlite3_reset()] to reset the virtual
98907 ** machine back to its initial state.
98908 **
98909 ** If the SQL statement being executed returns any data, then 
98910 ** [SQLITE_ROW] is returned each time a new row of data is ready
98911 ** for processing by the caller. The values may be accessed using
98912 ** the [sqlite3_column_int | column access functions].
98913 ** sqlite3_step() is called again to retrieve the next row of data.
98914 ** 
98915 ** [SQLITE_ERROR] means that a run-time error (such as a constraint
98916 ** violation) has occurred.  sqlite3_step() should not be called again on
98917 ** the VM. More information may be found by calling [sqlite3_errmsg()].
98918 ** With the legacy interface, a more specific error code (example:
98919 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
98920 ** can be obtained by calling [sqlite3_reset()] on the
98921 ** [sqlite3_stmt | prepared statement].  In the "v2" interface,
98922 ** the more specific error code is returned directly by sqlite3_step().
98923 **
98924 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
98925 ** Perhaps it was called on a [sqlite3_stmt | prepared statement] that has
98926 ** already been [sqlite3_finalize | finalized] or on one that had 
98927 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
98928 ** be the case that the same database connection is being used by two or
98929 ** more threads at the same moment in time.
98930 **
98931 ** <b>Goofy Interface Alert:</b>
98932 ** In the legacy interface, 
98933 ** the sqlite3_step() API always returns a generic error code,
98934 ** [SQLITE_ERROR], following any error other than [SQLITE_BUSY]
98935 ** and [SQLITE_MISUSE].  You must call [sqlite3_reset()] or
98936 ** [sqlite3_finalize()] in order to find one of the specific
98937 ** [SQLITE_ERROR | result codes] that better describes the error.
98938 ** We admit that this is a goofy design.  The problem has been fixed
98939 ** with the "v2" interface.  If you prepare all of your SQL statements
98940 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
98941 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the 
98942 ** more specific [SQLITE_ERROR | result codes] are returned directly
98943 ** by sqlite3_step().  The use of the "v2" interface is recommended.
98944 */
98945 int sqlite3_step(sqlite3_stmt*);
98946
98947 /*
98948 ** CAPI3REF: Number of columns in a result set {F13770}
98949 **
98950 ** Return the number of values in the current row of the result set.
98951 **
98952 ** {F13771} After a call to [sqlite3_step()] that returns [SQLITE_ROW],
98953 ** this routine
98954 ** will return the same value as the [sqlite3_column_count()] function.
98955 ** {F13772}
98956 ** After [sqlite3_step()] has returned an [SQLITE_DONE], [SQLITE_BUSY], or
98957 ** a [SQLITE_ERROR | error code], or before [sqlite3_step()] has been 
98958 ** called on the [sqlite3_stmt | prepared statement] for the first time,
98959 ** this routine returns zero.
98960 */
98961 int sqlite3_data_count(sqlite3_stmt *pStmt);
98962
98963 /*
98964 ** CAPI3REF: Fundamental Datatypes {F10265}
98965 **
98966 ** {F10266}Every value in SQLite has one of five fundamental datatypes:
98967 **
98968 ** <ul>
98969 ** <li> 64-bit signed integer
98970 ** <li> 64-bit IEEE floating point number
98971 ** <li> string
98972 ** <li> BLOB
98973 ** <li> NULL
98974 ** </ul> {END}
98975 **
98976 ** These constants are codes for each of those types.
98977 **
98978 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
98979 ** for a completely different meaning.  Software that links against both
98980 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not
98981 ** SQLITE_TEXT.
98982 */
98983 #define SQLITE_INTEGER  1
98984 #define SQLITE_FLOAT    2
98985 #define SQLITE_BLOB     4
98986 #define SQLITE_NULL     5
98987 #ifdef SQLITE_TEXT
98988 # undef SQLITE_TEXT
98989 #else
98990 # define SQLITE_TEXT     3
98991 #endif
98992 #define SQLITE3_TEXT     3
98993
98994 /*
98995 ** CAPI3REF: Results Values From A Query {F13800}
98996 **
98997 ** These routines return information about
98998 ** a single column of the current result row of a query.  In every
98999 ** case the first argument is a pointer to the 
99000 ** [sqlite3_stmt | SQL statement] that is being
99001 ** evaluated (the [sqlite3_stmt*] that was returned from 
99002 ** [sqlite3_prepare_v2()] or one of its variants) and
99003 ** the second argument is the index of the column for which information 
99004 ** should be returned.  The left-most column of the result set
99005 ** has an index of 0.
99006 **
99007 ** If the SQL statement is not currently point to a valid row, or if the
99008 ** the column index is out of range, the result is undefined. 
99009 ** These routines may only be called when the most recent call to
99010 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
99011 ** [sqlite3_reset()] nor [sqlite3_finalize()] has been call subsequently.
99012 ** If any of these routines are called after [sqlite3_reset()] or
99013 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
99014 ** something other than [SQLITE_ROW], the results are undefined.
99015 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
99016 ** are called from a different thread while any of these routines
99017 ** are pending, then the results are undefined.  
99018 **
99019 ** The sqlite3_column_type() routine returns 
99020 ** [SQLITE_INTEGER | datatype code] for the initial data type
99021 ** of the result column.  The returned value is one of [SQLITE_INTEGER],
99022 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
99023 ** returned by sqlite3_column_type() is only meaningful if no type
99024 ** conversions have occurred as described below.  After a type conversion,
99025 ** the value returned by sqlite3_column_type() is undefined.  Future
99026 ** versions of SQLite may change the behavior of sqlite3_column_type()
99027 ** following a type conversion.
99028 **
99029 ** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() 
99030 ** routine returns the number of bytes in that BLOB or string.
99031 ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
99032 ** the string to UTF-8 and then returns the number of bytes.
99033 ** If the result is a numeric value then sqlite3_column_bytes() uses
99034 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
99035 ** the number of bytes in that string.
99036 ** The value returned does not include the zero terminator at the end
99037 ** of the string.  For clarity: the value returned is the number of
99038 ** bytes in the string, not the number of characters.
99039 **
99040 ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
99041 ** even zero-length strings, are always zero terminated.  The return
99042 ** value from sqlite3_column_blob() for a zero-length blob is an arbitrary
99043 ** pointer, possibly even a NULL pointer.
99044 **
99045 ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
99046 ** but leaves the result in UTF-16 instead of UTF-8.  
99047 ** The zero terminator is not included in this count.
99048 **
99049 ** These routines attempt to convert the value where appropriate.  For
99050 ** example, if the internal representation is FLOAT and a text result
99051 ** is requested, [sqlite3_snprintf()] is used internally to do the conversion
99052 ** automatically.  The following table details the conversions that
99053 ** are applied:
99054 **
99055 ** <blockquote>
99056 ** <table border="1">
99057 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
99058 **
99059 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
99060 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
99061 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
99062 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
99063 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
99064 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
99065 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as for INTEGER->TEXT
99066 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
99067 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
99068 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
99069 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
99070 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
99071 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
99072 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
99073 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
99074 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
99075 ** </table>
99076 ** </blockquote>
99077 **
99078 ** The table above makes reference to standard C library functions atoi()
99079 ** and atof().  SQLite does not really use these functions.  It has its
99080 ** on equavalent internal routines.  The atoi() and atof() names are
99081 ** used in the table for brevity and because they are familiar to most
99082 ** C programmers.
99083 **
99084 ** Note that when type conversions occur, pointers returned by prior
99085 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
99086 ** sqlite3_column_text16() may be invalidated. 
99087 ** Type conversions and pointer invalidations might occur
99088 ** in the following cases:
99089 **
99090 ** <ul>
99091 ** <li><p>  The initial content is a BLOB and sqlite3_column_text() 
99092 **          or sqlite3_column_text16() is called.  A zero-terminator might
99093 **          need to be added to the string.</p></li>
99094 **
99095 ** <li><p>  The initial content is UTF-8 text and sqlite3_column_bytes16() or
99096 **          sqlite3_column_text16() is called.  The content must be converted
99097 **          to UTF-16.</p></li>
99098 **
99099 ** <li><p>  The initial content is UTF-16 text and sqlite3_column_bytes() or
99100 **          sqlite3_column_text() is called.  The content must be converted
99101 **          to UTF-8.</p></li>
99102 ** </ul>
99103 **
99104 ** Conversions between UTF-16be and UTF-16le are always done in place and do
99105 ** not invalidate a prior pointer, though of course the content of the buffer
99106 ** that the prior pointer points to will have been modified.  Other kinds
99107 ** of conversion are done in place when it is possible, but sometime it is
99108 ** not possible and in those cases prior pointers are invalidated.  
99109 **
99110 ** The safest and easiest to remember policy is to invoke these routines
99111 ** in one of the following ways:
99112 **
99113 **  <ul>
99114 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
99115 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
99116 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
99117 **  </ul>
99118 **
99119 ** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(),
99120 ** or sqlite3_column_text16() first to force the result into the desired
99121 ** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to
99122 ** find the size of the result.  Do not mix call to sqlite3_column_text() or
99123 ** sqlite3_column_blob() with calls to sqlite3_column_bytes16().  And do not
99124 ** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes().
99125 **
99126 ** The pointers returned are valid until a type conversion occurs as
99127 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
99128 ** [sqlite3_finalize()] is called.  The memory space used to hold strings
99129 ** and blobs is freed automatically.  Do <b>not</b> pass the pointers returned
99130 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into 
99131 ** [sqlite3_free()].
99132 **
99133 ** If a memory allocation error occurs during the evaluation of any
99134 ** of these routines, a default value is returned.  The default value
99135 ** is either the integer 0, the floating point number 0.0, or a NULL
99136 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
99137 ** [SQLITE_NOMEM].
99138 */
99139 const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
99140 int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
99141 int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
99142 double sqlite3_column_double(sqlite3_stmt*, int iCol);
99143 int sqlite3_column_int(sqlite3_stmt*, int iCol);
99144 sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
99145 const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
99146 const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
99147 int sqlite3_column_type(sqlite3_stmt*, int iCol);
99148 sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
99149
99150 /*
99151 ** CAPI3REF: Destroy A Prepared Statement Object {F13300}
99152 **
99153 ** The sqlite3_finalize() function is called to delete a 
99154 ** [sqlite3_stmt | compiled SQL statement]. If the statement was
99155 ** executed successfully, or not executed at all, then SQLITE_OK is returned.
99156 ** If execution of the statement failed then an 
99157 ** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code]
99158 ** is returned. 
99159 **
99160 ** This routine can be called at any point during the execution of the
99161 ** [sqlite3_stmt | virtual machine].  If the virtual machine has not 
99162 ** completed execution when this routine is called, that is like
99163 ** encountering an error or an interrupt.  (See [sqlite3_interrupt()].) 
99164 ** Incomplete updates may be rolled back and transactions cancelled,  
99165 ** depending on the circumstances, and the 
99166 ** [SQLITE_ERROR | result code] returned will be [SQLITE_ABORT].
99167 */
99168 int sqlite3_finalize(sqlite3_stmt *pStmt);
99169
99170 /*
99171 ** CAPI3REF: Reset A Prepared Statement Object {F13330}
99172 **
99173 ** The sqlite3_reset() function is called to reset a 
99174 ** [sqlite3_stmt | compiled SQL statement] object.
99175 ** back to its initial state, ready to be re-executed.
99176 ** Any SQL statement variables that had values bound to them using
99177 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
99178 ** Use [sqlite3_clear_bindings()] to reset the bindings.
99179 */
99180 int sqlite3_reset(sqlite3_stmt *pStmt);
99181
99182 /*
99183 ** CAPI3REF: Create Or Redefine SQL Functions {F16100}
99184 **
99185 ** The following two functions are used to add SQL functions or aggregates
99186 ** or to redefine the behavior of existing SQL functions or aggregates.  The
99187 ** difference only between the two is that the second parameter, the
99188 ** name of the (scalar) function or aggregate, is encoded in UTF-8 for
99189 ** sqlite3_create_function() and UTF-16 for sqlite3_create_function16().
99190 **
99191 ** The first argument is the [sqlite3 | database handle] that holds the
99192 ** SQL function or aggregate is to be added or redefined. If a single
99193 ** program uses more than one database handle internally, then SQL
99194 ** functions or aggregates must be added individually to each database
99195 ** handle with which they will be used.
99196 **
99197 ** The second parameter is the name of the SQL function to be created
99198 ** or redefined.
99199 ** The length of the name is limited to 255 bytes, exclusive of the 
99200 ** zero-terminator.  Note that the name length limit is in bytes, not
99201 ** characters.  Any attempt to create a function with a longer name
99202 ** will result in an SQLITE_ERROR error.
99203 **
99204 ** The third parameter is the number of arguments that the SQL function or
99205 ** aggregate takes. If this parameter is negative, then the SQL function or
99206 ** aggregate may take any number of arguments.
99207 **
99208 ** The fourth parameter, eTextRep, specifies what 
99209 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
99210 ** its parameters.  Any SQL function implementation should be able to work
99211 ** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
99212 ** more efficient with one encoding than another.  It is allowed to
99213 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
99214 ** times with the same function but with different values of eTextRep.
99215 ** When multiple implementations of the same function are available, SQLite
99216 ** will pick the one that involves the least amount of data conversion.
99217 ** If there is only a single implementation which does not care what
99218 ** text encoding is used, then the fourth argument should be
99219 ** [SQLITE_ANY].
99220 **
99221 ** The fifth parameter is an arbitrary pointer.  The implementation
99222 ** of the function can gain access to this pointer using
99223 ** [sqlite3_user_data()].
99224 **
99225 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
99226 ** pointers to C-language functions that implement the SQL
99227 ** function or aggregate. A scalar SQL function requires an implementation of
99228 ** the xFunc callback only, NULL pointers should be passed as the xStep
99229 ** and xFinal parameters. An aggregate SQL function requires an implementation
99230 ** of xStep and xFinal and NULL should be passed for xFunc. To delete an
99231 ** existing SQL function or aggregate, pass NULL for all three function
99232 ** callback.
99233 **
99234 ** It is permitted to register multiple implementations of the same
99235 ** functions with the same name but with either differing numbers of
99236 ** arguments or differing perferred text encodings.  SQLite will use
99237 ** the implementation most closely matches the way in which the
99238 ** SQL function is used.
99239 */
99240 int sqlite3_create_function(
99241   sqlite3 *,
99242   const char *zFunctionName,
99243   int nArg,
99244   int eTextRep,
99245   void*,
99246   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
99247   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
99248   void (*xFinal)(sqlite3_context*)
99249 );
99250 int sqlite3_create_function16(
99251   sqlite3*,
99252   const void *zFunctionName,
99253   int nArg,
99254   int eTextRep,
99255   void*,
99256   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
99257   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
99258   void (*xFinal)(sqlite3_context*)
99259 );
99260
99261 /*
99262 ** CAPI3REF: Text Encodings {F10267}
99263 **
99264 ** These constant define integer codes that represent the various
99265 ** text encodings supported by SQLite.
99266 */
99267 #define SQLITE_UTF8           1
99268 #define SQLITE_UTF16LE        2
99269 #define SQLITE_UTF16BE        3
99270 #define SQLITE_UTF16          4    /* Use native byte order */
99271 #define SQLITE_ANY            5    /* sqlite3_create_function only */
99272 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
99273
99274 /*
99275 ** CAPI3REF: Obsolete Functions
99276 **
99277 ** These functions are all now obsolete.  In order to maintain
99278 ** backwards compatibility with older code, we continue to support
99279 ** these functions.  However, new development projects should avoid
99280 ** the use of these functions.  To help encourage people to avoid
99281 ** using these functions, we are not going to tell you want they do.
99282 */
99283 int sqlite3_aggregate_count(sqlite3_context*);
99284 int sqlite3_expired(sqlite3_stmt*);
99285 int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
99286 int sqlite3_global_recover(void);
99287 void sqlite3_thread_cleanup(void);
99288 int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
99289
99290 /*
99291 ** CAPI3REF: Obtaining SQL Function Parameter Values {F15100}
99292 **
99293 ** The C-language implementation of SQL functions and aggregates uses
99294 ** this set of interface routines to access the parameter values on
99295 ** the function or aggregate.
99296 **
99297 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
99298 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
99299 ** define callbacks that implement the SQL functions and aggregates.
99300 ** The 4th parameter to these callbacks is an array of pointers to
99301 ** [sqlite3_value] objects.  There is one [sqlite3_value] object for
99302 ** each parameter to the SQL function.  These routines are used to
99303 ** extract values from the [sqlite3_value] objects.
99304 **
99305 ** These routines work just like the corresponding 
99306 ** [sqlite3_column_blob | sqlite3_column_* routines] except that 
99307 ** these routines take a single [sqlite3_value*] pointer instead
99308 ** of an [sqlite3_stmt*] pointer and an integer column number.
99309 **
99310 ** The sqlite3_value_text16() interface extracts a UTF16 string
99311 ** in the native byte-order of the host machine.  The
99312 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
99313 ** extract UTF16 strings as big-endian and little-endian respectively.
99314 **
99315 ** The sqlite3_value_numeric_type() interface attempts to apply
99316 ** numeric affinity to the value.  This means that an attempt is
99317 ** made to convert the value to an integer or floating point.  If
99318 ** such a conversion is possible without loss of information (in other
99319 ** words if the value is a string that looks like a number)
99320 ** then the conversion is done.  Otherwise no conversion occurs.  The 
99321 ** [SQLITE_INTEGER | datatype] after conversion is returned.
99322 **
99323 ** Please pay particular attention to the fact that the pointer that
99324 ** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or
99325 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
99326 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
99327 ** or [sqlite3_value_text16()].  
99328 **
99329 ** These routines must be called from the same thread as
99330 ** the SQL function that supplied the sqlite3_value* parameters.
99331 ** Or, if the sqlite3_value* argument comes from the [sqlite3_column_value()]
99332 ** interface, then these routines should be called from the same thread
99333 ** that ran [sqlite3_column_value()].
99334 **
99335 */
99336 const void *sqlite3_value_blob(sqlite3_value*);
99337 int sqlite3_value_bytes(sqlite3_value*);
99338 int sqlite3_value_bytes16(sqlite3_value*);
99339 double sqlite3_value_double(sqlite3_value*);
99340 int sqlite3_value_int(sqlite3_value*);
99341 sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
99342 const unsigned char *sqlite3_value_text(sqlite3_value*);
99343 const void *sqlite3_value_text16(sqlite3_value*);
99344 const void *sqlite3_value_text16le(sqlite3_value*);
99345 const void *sqlite3_value_text16be(sqlite3_value*);
99346 int sqlite3_value_type(sqlite3_value*);
99347 int sqlite3_value_numeric_type(sqlite3_value*);
99348
99349 /*
99350 ** CAPI3REF: Obtain Aggregate Function Context {F16210}
99351 **
99352 ** The implementation of aggregate SQL functions use this routine to allocate
99353 ** a structure for storing their state.  
99354 ** {F16211} The first time the sqlite3_aggregate_context() routine is
99355 ** is called for a particular aggregate, SQLite allocates nBytes of memory
99356 ** zeros that memory, and returns a pointer to it.
99357 ** {F16212} On second and subsequent calls to sqlite3_aggregate_context()
99358 ** for the same aggregate function index, the same buffer is returned. {END}
99359 ** The implementation
99360 ** of the aggregate can use the returned buffer to accumulate data.
99361 **
99362 ** {F16213} SQLite automatically frees the allocated buffer when the aggregate
99363 ** query concludes. {END}
99364 **
99365 ** The first parameter should be a copy of the 
99366 ** [sqlite3_context | SQL function context] that is the first
99367 ** parameter to the callback routine that implements the aggregate
99368 ** function.
99369 **
99370 ** This routine must be called from the same thread in which
99371 ** the aggregate SQL function is running.
99372 */
99373 void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
99374
99375 /*
99376 ** CAPI3REF: User Data For Functions {F16240}
99377 **
99378 ** {F16241} The sqlite3_user_data() interface returns a copy of
99379 ** the pointer that was the pUserData parameter (the 5th parameter)
99380 ** of the the [sqlite3_create_function()]
99381 ** and [sqlite3_create_function16()] routines that originally
99382 ** registered the application defined function. {END}
99383 **
99384 ** {U16243} This routine must be called from the same thread in which
99385 ** the application-defined function is running.
99386 */
99387 void *sqlite3_user_data(sqlite3_context*);
99388
99389 /*
99390 ** CAPI3REF: Function Auxiliary Data {F16270}
99391 **
99392 ** The following two functions may be used by scalar SQL functions to
99393 ** associate meta-data with argument values. If the same value is passed to
99394 ** multiple invocations of the same SQL function during query execution, under
99395 ** some circumstances the associated meta-data may be preserved. This may
99396 ** be used, for example, to add a regular-expression matching scalar
99397 ** function. The compiled version of the regular expression is stored as
99398 ** meta-data associated with the SQL value passed as the regular expression
99399 ** pattern.  The compiled regular expression can be reused on multiple
99400 ** invocations of the same function so that the original pattern string
99401 ** does not need to be recompiled on each invocation.
99402 **
99403 ** {F16271}
99404 ** The sqlite3_get_auxdata() interface returns a pointer to the meta-data
99405 ** associated by the sqlite3_set_auxdata() function with the Nth argument
99406 ** value to the application-defined function.
99407 ** {F16272} If no meta-data has been ever been set for the Nth
99408 ** argument of the function, or if the cooresponding function parameter
99409 ** has changed since the meta-data was set, then sqlite3_get_auxdata()
99410 ** returns a NULL pointer.
99411 **
99412 ** {F16275} The sqlite3_set_auxdata() interface saves the meta-data
99413 ** pointed to by its 3rd parameter as the meta-data for the N-th
99414 ** argument of the application-defined function. {END} Subsequent
99415 ** calls to sqlite3_get_auxdata() might return this data, if it has
99416 ** not been destroyed. 
99417 ** {F16277} If it is not NULL, SQLite will invoke the destructor 
99418 ** function given by the 4th parameter to sqlite3_set_auxdata() on
99419 ** the meta-data when the corresponding function parameter changes
99420 ** or when the SQL statement completes, whichever comes first. {END}
99421 **
99422 ** In practice, meta-data is preserved between function calls for
99423 ** expressions that are constant at compile time. This includes literal
99424 ** values and SQL variables.
99425 **
99426 ** These routines must be called from the same thread in which
99427 ** the SQL function is running.
99428 */
99429 void *sqlite3_get_auxdata(sqlite3_context*, int N);
99430 void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
99431
99432
99433 /*
99434 ** CAPI3REF: Constants Defining Special Destructor Behavior {F10280}
99435 **
99436 ** These are special value for the destructor that is passed in as the
99437 ** final argument to routines like [sqlite3_result_blob()].  If the destructor
99438 ** argument is SQLITE_STATIC, it means that the content pointer is constant
99439 ** and will never change.  It does not need to be destroyed.  The 
99440 ** SQLITE_TRANSIENT value means that the content will likely change in
99441 ** the near future and that SQLite should make its own private copy of
99442 ** the content before returning.
99443 **
99444 ** The typedef is necessary to work around problems in certain
99445 ** C++ compilers.  See ticket #2191.
99446 */
99447 typedef void (*sqlite3_destructor_type)(void*);
99448 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
99449 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
99450
99451 /*
99452 ** CAPI3REF: Setting The Result Of An SQL Function {F16400}
99453 **
99454 ** These routines are used by the xFunc or xFinal callbacks that
99455 ** implement SQL functions and aggregates.  See
99456 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
99457 ** for additional information.
99458 **
99459 ** These functions work very much like the 
99460 ** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used
99461 ** to bind values to host parameters in prepared statements.
99462 ** Refer to the
99463 ** [sqlite3_bind_blob | sqlite3_bind_* documentation] for
99464 ** additional information.
99465 **
99466 ** {F16402} The sqlite3_result_blob() interface sets the result from
99467 ** an application defined function to be the BLOB whose content is pointed
99468 ** to by the second parameter and which is N bytes long where N is the
99469 ** third parameter. 
99470 ** {F16403} The sqlite3_result_zeroblob() inerfaces set the result of
99471 ** the application defined function to be a BLOB containing all zero
99472 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
99473 **
99474 ** {F16407} The sqlite3_result_double() interface sets the result from
99475 ** an application defined function to be a floating point value specified
99476 ** by its 2nd argument.
99477 **
99478 ** {F16409} The sqlite3_result_error() and sqlite3_result_error16() functions
99479 ** cause the implemented SQL function to throw an exception.
99480 ** {F16411} SQLite uses the string pointed to by the
99481 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
99482 ** as the text of an error message. {F16412} SQLite interprets the error
99483 ** message string from sqlite3_result_error() as UTF8.  {F16413} SQLite
99484 ** interprets the string from sqlite3_result_error16() as UTF16 in native
99485 ** byte order.  {F16414} If the third parameter to sqlite3_result_error()
99486 ** or sqlite3_result_error16() is negative then SQLite takes as the error
99487 ** message all text up through the first zero character.
99488 ** {F16415} If the third parameter to sqlite3_result_error() or
99489 ** sqlite3_result_error16() is non-negative then SQLite takes that many
99490 ** bytes (not characters) from the 2nd parameter as the error message.
99491 ** {F16417} The sqlite3_result_error() and sqlite3_result_error16()
99492 ** routines make a copy private copy of the error message text before
99493 ** they return.  {END} Hence, the calling function can deallocate or
99494 ** modify the text after they return without harm.
99495 **
99496 ** {F16421} The sqlite3_result_toobig() interface causes SQLite
99497 ** to throw an error indicating that a string or BLOB is to long
99498 ** to represent.  {F16422} The sqlite3_result_nomem() interface
99499 ** causes SQLite to throw an exception indicating that the a
99500 ** memory allocation failed.
99501 **
99502 ** {F16431} The sqlite3_result_int() interface sets the return value
99503 ** of the application-defined function to be the 32-bit signed integer
99504 ** value given in the 2nd argument.
99505 ** {F16432} The sqlite3_result_int64() interface sets the return value
99506 ** of the application-defined function to be the 64-bit signed integer
99507 ** value given in the 2nd argument.
99508 **
99509 ** {F16437} The sqlite3_result_null() interface sets the return value
99510 ** of the application-defined function to be NULL.
99511 **
99512 ** {F16441} The sqlite3_result_text(), sqlite3_result_text16(), 
99513 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
99514 ** set the return value of the application-defined function to be
99515 ** a text string which is represented as UTF-8, UTF-16 native byte order,
99516 ** UTF-16 little endian, or UTF-16 big endian, respectively.
99517 ** {F16442} SQLite takes the text result from the application from
99518 ** the 2nd parameter of the sqlite3_result_text* interfaces.
99519 ** {F16444} If the 3rd parameter to the sqlite3_result_text* interfaces
99520 ** is negative, then SQLite takes result text from the 2nd parameter 
99521 ** through the first zero character.
99522 ** {F16447} If the 3rd parameter to the sqlite3_result_text* interfaces
99523 ** is non-negative, then as many bytes (not characters) of the text
99524 ** pointed to by the 2nd parameter are taken as the application-defined
99525 ** function result.
99526 ** {F16451} If the 4th parameter to the sqlite3_result_text* interfaces
99527 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
99528 ** function as the destructor on the text or blob result when it has
99529 ** finished using that result.
99530 ** {F16453} If the 4th parameter to the sqlite3_result_text* interfaces
99531 ** or sqlite3_result_blob is the special constant SQLITE_STATIC, then
99532 ** SQLite assumes that the text or blob result is constant space and
99533 ** does not copy the space or call a destructor when it has
99534 ** finished using that result.
99535 ** {F16454} If the 4th parameter to the sqlite3_result_text* interfaces
99536 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
99537 ** then SQLite makes a copy of the result into space obtained from
99538 ** from [sqlite3_malloc()] before it returns.
99539 **
99540 ** {F16461} The sqlite3_result_value() interface sets the result of
99541 ** the application-defined function to be a copy the [sqlite3_value]
99542 ** object specified by the 2nd parameter.  {F16463} The
99543 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
99544 ** so that [sqlite3_value] specified in the parameter may change or
99545 ** be deallocated after sqlite3_result_value() returns without harm.
99546 **
99547 ** {U16491} These routines are called from within the different thread 
99548 ** than the one containing the application-defined function that recieved
99549 ** the [sqlite3_context] pointer, the results are undefined.
99550 */
99551 void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
99552 void sqlite3_result_double(sqlite3_context*, double);
99553 void sqlite3_result_error(sqlite3_context*, const char*, int);
99554 void sqlite3_result_error16(sqlite3_context*, const void*, int);
99555 void sqlite3_result_error_toobig(sqlite3_context*);
99556 void sqlite3_result_error_nomem(sqlite3_context*);
99557 void sqlite3_result_int(sqlite3_context*, int);
99558 void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
99559 void sqlite3_result_null(sqlite3_context*);
99560 void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
99561 void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
99562 void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
99563 void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
99564 void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
99565 void sqlite3_result_zeroblob(sqlite3_context*, int n);
99566
99567 /*
99568 ** CAPI3REF: Define New Collating Sequences {F16600}
99569 **
99570 ** {F16601}
99571 ** These functions are used to add new collation sequences to the
99572 ** [sqlite3*] handle specified as the first argument. 
99573 **
99574 ** {F16602}
99575 ** The name of the new collation sequence is specified as a UTF-8 string
99576 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
99577 ** and a UTF-16 string for sqlite3_create_collation16(). {F16603} In all cases
99578 ** the name is passed as the second function argument.
99579 **
99580 ** {F16604}
99581 ** The third argument may be one of the constants [SQLITE_UTF8],
99582 ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
99583 ** routine expects to be passed pointers to strings encoded using UTF-8,
99584 ** UTF-16 little-endian or UTF-16 big-endian respectively. {F16605} The
99585 ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that
99586 ** the routine expects pointers to 16-bit word aligned strings
99587 ** of UTF16 in the native byte order of the host computer.
99588 **
99589 ** {F16607}
99590 ** A pointer to the user supplied routine must be passed as the fifth
99591 ** argument. {F16609} If it is NULL, this is the same as deleting the collation
99592 ** sequence (so that SQLite cannot call it anymore).
99593 ** {F16611} Each time the application
99594 ** supplied function is invoked, it is passed a copy of the void* passed as
99595 ** the fourth argument to sqlite3_create_collation() or
99596 ** sqlite3_create_collation16() as its first parameter.
99597 **
99598 ** {F16612}
99599 ** The remaining arguments to the application-supplied routine are two strings,
99600 ** each represented by a [length, data] pair and encoded in the encoding
99601 ** that was passed as the third argument when the collation sequence was
99602 ** registered. {END} The application defined collation routine should
99603 ** return negative, zero or positive if
99604 ** the first string is less than, equal to, or greater than the second
99605 ** string. i.e. (STRING1 - STRING2).
99606 **
99607 ** {F16615}
99608 ** The sqlite3_create_collation_v2() works like sqlite3_create_collation()
99609 ** excapt that it takes an extra argument which is a destructor for
99610 ** the collation.  {F16617} The destructor is called when the collation is
99611 ** destroyed and is passed a copy of the fourth parameter void* pointer
99612 ** of the sqlite3_create_collation_v2().
99613 ** {F16618}  Collations are destroyed when
99614 ** they are overridden by later calls to the collation creation functions
99615 ** or when the [sqlite3*] database handle is closed using [sqlite3_close()].
99616 */
99617 int sqlite3_create_collation(
99618   sqlite3*, 
99619   const char *zName, 
99620   int eTextRep, 
99621   void*,
99622   int(*xCompare)(void*,int,const void*,int,const void*)
99623 );
99624 int sqlite3_create_collation_v2(
99625   sqlite3*, 
99626   const char *zName, 
99627   int eTextRep, 
99628   void*,
99629   int(*xCompare)(void*,int,const void*,int,const void*),
99630   void(*xDestroy)(void*)
99631 );
99632 int sqlite3_create_collation16(
99633   sqlite3*, 
99634   const char *zName, 
99635   int eTextRep, 
99636   void*,
99637   int(*xCompare)(void*,int,const void*,int,const void*)
99638 );
99639
99640 /*
99641 ** CAPI3REF: Collation Needed Callbacks {F16700}
99642 **
99643 ** {F16701}
99644 ** To avoid having to register all collation sequences before a database
99645 ** can be used, a single callback function may be registered with the
99646 ** database handle to be called whenever an undefined collation sequence is
99647 ** required.
99648 **
99649 ** {F16702}
99650 ** If the function is registered using the sqlite3_collation_needed() API,
99651 ** then it is passed the names of undefined collation sequences as strings
99652 ** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, the names
99653 ** are passed as UTF-16 in machine native byte order. {F16704} A call to either
99654 ** function replaces any existing callback.
99655 **
99656 ** {F16705} When the callback is invoked, the first argument passed is a copy
99657 ** of the second argument to sqlite3_collation_needed() or
99658 ** sqlite3_collation_needed16(). {F16706} The second argument is the database
99659 ** handle.  {F16707} The third argument is one of [SQLITE_UTF8],
99660 ** [SQLITE_UTF16BE], or [SQLITE_UTF16LE], indicating the most
99661 ** desirable form of the collation sequence function required.
99662 ** {F16708} The fourth parameter is the name of the
99663 ** required collation sequence. {END}
99664 **
99665 ** The callback function should register the desired collation using
99666 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
99667 ** [sqlite3_create_collation_v2()].
99668 */
99669 int sqlite3_collation_needed(
99670   sqlite3*, 
99671   void*, 
99672   void(*)(void*,sqlite3*,int eTextRep,const char*)
99673 );
99674 int sqlite3_collation_needed16(
99675   sqlite3*, 
99676   void*,
99677   void(*)(void*,sqlite3*,int eTextRep,const void*)
99678 );
99679
99680 /*
99681 ** Specify the key for an encrypted database.  This routine should be
99682 ** called right after sqlite3_open().
99683 **
99684 ** The code to implement this API is not available in the public release
99685 ** of SQLite.
99686 */
99687 int sqlite3_key(
99688   sqlite3 *db,                   /* Database to be rekeyed */
99689   const void *pKey, int nKey     /* The key */
99690 );
99691
99692 /*
99693 ** Change the key on an open database.  If the current database is not
99694 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
99695 ** database is decrypted.
99696 **
99697 ** The code to implement this API is not available in the public release
99698 ** of SQLite.
99699 */
99700 int sqlite3_rekey(
99701   sqlite3 *db,                   /* Database to be rekeyed */
99702   const void *pKey, int nKey     /* The new key */
99703 );
99704
99705 /*
99706 ** CAPI3REF:  Suspend Execution For A Short Time {F10530}
99707 **
99708 ** {F10531} The sqlite3_sleep() function
99709 ** causes the current thread to suspend execution
99710 ** for at least a number of milliseconds specified in its parameter.
99711 **
99712 ** {F10532} If the operating system does not support sleep requests with 
99713 ** millisecond time resolution, then the time will be rounded up to 
99714 ** the nearest second. {F10533} The number of milliseconds of sleep actually 
99715 ** requested from the operating system is returned.
99716 **
99717 ** {F10534} SQLite implements this interface by calling the xSleep()
99718 ** method of the default [sqlite3_vfs] object. {END}
99719 */
99720 int sqlite3_sleep(int);
99721
99722 /*
99723 ** CAPI3REF:  Name Of The Folder Holding Temporary Files {F10310}
99724 **
99725 ** If this global variable is made to point to a string which is
99726 ** the name of a folder (a.ka. directory), then all temporary files
99727 ** created by SQLite will be placed in that directory.  If this variable
99728 ** is NULL pointer, then SQLite does a search for an appropriate temporary
99729 ** file directory.
99730 **
99731 ** It is not safe to modify this variable once a database connection
99732 ** has been opened.  It is intended that this variable be set once
99733 ** as part of process initialization and before any SQLite interface
99734 ** routines have been call and remain unchanged thereafter.
99735 */
99736 SQLITE_EXTERN char *sqlite3_temp_directory;
99737
99738 /*
99739 ** CAPI3REF:  Test To See If The Database Is In Auto-Commit Mode {F12930}
99740 **
99741 ** {F12931} The sqlite3_get_autocommit() interfaces returns non-zero or
99742 ** zero if the given database connection is or is not in autocommit mode,
99743 ** respectively. {F12932}  Autocommit mode is on
99744 ** by default.  {F12933} Autocommit mode is disabled by a BEGIN statement.
99745 ** {F12934} Autocommit mode is reenabled by a COMMIT or ROLLBACK. {END}
99746 **
99747 ** If certain kinds of errors occur on a statement within a multi-statement
99748 ** transactions (errors including [SQLITE_FULL], [SQLITE_IOERR], 
99749 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
99750 ** transaction might be rolled back automatically.  {F12935} The only way to
99751 ** find out if SQLite automatically rolled back the transaction after
99752 ** an error is to use this function. {END}
99753 **
99754 ** {U12936} If another thread changes the autocommit status of the database
99755 ** connection while this routine is running, then the return value
99756 ** is undefined. {END}
99757 */
99758 int sqlite3_get_autocommit(sqlite3*);
99759
99760 /*
99761 ** CAPI3REF:  Find The Database Handle Of A Prepared Statement {F13120}
99762 **
99763 ** {F13121} The sqlite3_db_handle interface
99764 ** returns the [sqlite3*] database handle to which a
99765 ** [sqlite3_stmt | prepared statement] belongs.
99766 ** {F13122} the database handle returned by sqlite3_db_handle
99767 ** is the same database handle that was
99768 ** the first argument to the [sqlite3_prepare_v2()] or its variants
99769 ** that was used to create the statement in the first place.
99770 */
99771 sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
99772
99773
99774 /*
99775 ** CAPI3REF: Commit And Rollback Notification Callbacks {F12950}
99776 **
99777 ** {F12951} The sqlite3_commit_hook() interface registers a callback
99778 ** function to be invoked whenever a transaction is committed.
99779 ** {F12952} Any callback set by a previous call to sqlite3_commit_hook()
99780 ** for the same database connection is overridden.
99781 ** {F12953} The sqlite3_rollback_hook() interface registers a callback
99782 ** function to be invoked whenever a transaction is committed.
99783 ** {F12954} Any callback set by a previous call to sqlite3_commit_hook()
99784 ** for the same database connection is overridden.
99785 ** {F12956} The pArg argument is passed through
99786 ** to the callback.  {F12957} If the callback on a commit hook function 
99787 ** returns non-zero, then the commit is converted into a rollback.
99788 **
99789 ** {F12958} If another function was previously registered, its
99790 ** pArg value is returned.  Otherwise NULL is returned.
99791 **
99792 ** {F12959} Registering a NULL function disables the callback.
99793 **
99794 ** {F12961} For the purposes of this API, a transaction is said to have been 
99795 ** rolled back if an explicit "ROLLBACK" statement is executed, or
99796 ** an error or constraint causes an implicit rollback to occur.
99797 ** {F12962} The rollback callback is not invoked if a transaction is
99798 ** automatically rolled back because the database connection is closed.
99799 ** {F12964} The rollback callback is not invoked if a transaction is
99800 ** rolled back because a commit callback returned non-zero.
99801 ** <todo> Check on this </todo> {END}
99802 **
99803 ** These are experimental interfaces and are subject to change.
99804 */
99805 void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
99806 void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
99807
99808 /*
99809 ** CAPI3REF: Data Change Notification Callbacks {F12970}
99810 **
99811 ** {F12971} The sqlite3_update_hook() interface
99812 ** registers a callback function with the database connection identified by the 
99813 ** first argument to be invoked whenever a row is updated, inserted or deleted.
99814 ** {F12972} Any callback set by a previous call to this function for the same 
99815 ** database connection is overridden.
99816 **
99817 ** {F12974} The second argument is a pointer to the function to invoke when a 
99818 ** row is updated, inserted or deleted. 
99819 ** {F12976} The first argument to the callback is
99820 ** a copy of the third argument to sqlite3_update_hook().
99821 ** {F12977} The second callback 
99822 ** argument is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
99823 ** depending on the operation that caused the callback to be invoked.
99824 ** {F12978} The third and 
99825 ** fourth arguments to the callback contain pointers to the database and 
99826 ** table name containing the affected row.
99827 ** {F12979} The final callback parameter is 
99828 ** the rowid of the row.
99829 ** {F12981} In the case of an update, this is the rowid after 
99830 ** the update takes place.
99831 **
99832 ** {F12983} The update hook is not invoked when internal system tables are
99833 ** modified (i.e. sqlite_master and sqlite_sequence).
99834 **
99835 ** {F12984} If another function was previously registered, its pArg value
99836 ** is returned.  {F12985} Otherwise NULL is returned.
99837 */
99838 void *sqlite3_update_hook(
99839   sqlite3*, 
99840   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
99841   void*
99842 );
99843
99844 /*
99845 ** CAPI3REF:  Enable Or Disable Shared Pager Cache {F10330}
99846 **
99847 ** {F10331}
99848 ** This routine enables or disables the sharing of the database cache
99849 ** and schema data structures between connections to the same database.
99850 ** {F10332}
99851 ** Sharing is enabled if the argument is true and disabled if the argument
99852 ** is false.
99853 **
99854 ** {F10333} Cache sharing is enabled and disabled
99855 ** for an entire process. {END} This is a change as of SQLite version 3.5.0.
99856 ** In prior versions of SQLite, sharing was
99857 ** enabled or disabled for each thread separately.
99858 **
99859 ** {F10334}
99860 ** The cache sharing mode set by this interface effects all subsequent
99861 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
99862 ** {F10335} Existing database connections continue use the sharing mode
99863 ** that was in effect at the time they were opened. {END}
99864 **
99865 ** Virtual tables cannot be used with a shared cache.  {F10336} When shared
99866 ** cache is enabled, the [sqlite3_create_module()] API used to register
99867 ** virtual tables will always return an error. {END}
99868 **
99869 ** {F10337} This routine returns [SQLITE_OK] if shared cache was
99870 ** enabled or disabled successfully.  {F10338} An [SQLITE_ERROR | error code]
99871 ** is returned otherwise. {END}
99872 **
99873 ** {F10339} Shared cache is disabled by default. {END} But this might change in
99874 ** future releases of SQLite.  Applications that care about shared
99875 ** cache setting should set it explicitly.
99876 */
99877 int sqlite3_enable_shared_cache(int);
99878
99879 /*
99880 ** CAPI3REF:  Attempt To Free Heap Memory {F17340}
99881 **
99882 ** {F17341} The sqlite3_release_memory() interface attempts to
99883 ** free N bytes of heap memory by deallocating non-essential memory
99884 ** allocations held by the database labrary. {END}  Memory used
99885 ** to cache database pages to improve performance is an example of
99886 ** non-essential memory.  {F16342} sqlite3_release_memory() returns
99887 ** the number of bytes actually freed, which might be more or less
99888 ** than the amount requested.
99889 */
99890 int sqlite3_release_memory(int);
99891
99892 /*
99893 ** CAPI3REF:  Impose A Limit On Heap Size {F17350}
99894 **
99895 ** {F16351} The sqlite3_soft_heap_limit() interface
99896 ** places a "soft" limit on the amount of heap memory that may be allocated
99897 ** by SQLite. {F16352} If an internal allocation is requested 
99898 ** that would exceed the soft heap limit, [sqlite3_release_memory()] is
99899 ** invoked one or more times to free up some space before the allocation
99900 ** is made. {END}
99901 **
99902 ** {F16353} The limit is called "soft", because if
99903 ** [sqlite3_release_memory()] cannot
99904 ** free sufficient memory to prevent the limit from being exceeded,
99905 ** the memory is allocated anyway and the current operation proceeds.
99906 **
99907 ** {F16354}
99908 ** A negative or zero value for N means that there is no soft heap limit and
99909 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
99910 ** {F16355} The default value for the soft heap limit is zero.
99911 **
99912 ** SQLite makes a best effort to honor the soft heap limit.  
99913 ** {F16356} But if the soft heap limit cannot honored, execution will
99914 ** continue without error or notification. {END}  This is why the limit is 
99915 ** called a "soft" limit.  It is advisory only.
99916 **
99917 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
99918 ** allocated by a single thread - the same thread in which this routine
99919 ** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
99920 ** applied to all threads. {F16357} The value specified for the soft heap limit
99921 ** is an upper bound on the total memory allocation for all threads. {END}  In
99922 ** version 3.5.0 there is no mechanism for limiting the heap usage for
99923 ** individual threads.
99924 */
99925 void sqlite3_soft_heap_limit(int);
99926
99927 /*
99928 ** CAPI3REF:  Extract Metadata About A Column Of A Table {F12850}
99929 **
99930 ** This routine
99931 ** returns meta-data about a specific column of a specific database
99932 ** table accessible using the connection handle passed as the first function 
99933 ** argument.
99934 **
99935 ** The column is identified by the second, third and fourth parameters to 
99936 ** this function. The second parameter is either the name of the database
99937 ** (i.e. "main", "temp" or an attached database) containing the specified
99938 ** table or NULL. If it is NULL, then all attached databases are searched
99939 ** for the table using the same algorithm as the database engine uses to 
99940 ** resolve unqualified table references.
99941 **
99942 ** The third and fourth parameters to this function are the table and column 
99943 ** name of the desired column, respectively. Neither of these parameters 
99944 ** may be NULL.
99945 **
99946 ** Meta information is returned by writing to the memory locations passed as
99947 ** the 5th and subsequent parameters to this function. Any of these 
99948 ** arguments may be NULL, in which case the corresponding element of meta 
99949 ** information is ommitted.
99950 **
99951 ** <pre>
99952 ** Parameter     Output Type      Description
99953 ** -----------------------------------
99954 **
99955 **   5th         const char*      Data type
99956 **   6th         const char*      Name of the default collation sequence 
99957 **   7th         int              True if the column has a NOT NULL constraint
99958 **   8th         int              True if the column is part of the PRIMARY KEY
99959 **   9th         int              True if the column is AUTOINCREMENT
99960 ** </pre>
99961 **
99962 **
99963 ** The memory pointed to by the character pointers returned for the 
99964 ** declaration type and collation sequence is valid only until the next 
99965 ** call to any sqlite API function.
99966 **
99967 ** If the specified table is actually a view, then an error is returned.
99968 **
99969 ** If the specified column is "rowid", "oid" or "_rowid_" and an 
99970 ** INTEGER PRIMARY KEY column has been explicitly declared, then the output 
99971 ** parameters are set for the explicitly declared column. If there is no
99972 ** explicitly declared IPK column, then the output parameters are set as 
99973 ** follows:
99974 **
99975 ** <pre>
99976 **     data type: "INTEGER"
99977 **     collation sequence: "BINARY"
99978 **     not null: 0
99979 **     primary key: 1
99980 **     auto increment: 0
99981 ** </pre>
99982 **
99983 ** This function may load one or more schemas from database files. If an
99984 ** error occurs during this process, or if the requested table or column
99985 ** cannot be found, an SQLITE error code is returned and an error message
99986 ** left in the database handle (to be retrieved using sqlite3_errmsg()).
99987 **
99988 ** This API is only available if the library was compiled with the
99989 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
99990 */
99991 int sqlite3_table_column_metadata(
99992   sqlite3 *db,                /* Connection handle */
99993   const char *zDbName,        /* Database name or NULL */
99994   const char *zTableName,     /* Table name */
99995   const char *zColumnName,    /* Column name */
99996   char const **pzDataType,    /* OUTPUT: Declared data type */
99997   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
99998   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
99999   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
100000   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
100001 );
100002
100003 /*
100004 ** CAPI3REF: Load An Extension {F12600}
100005 **
100006 ** {F12601} The sqlite3_load_extension() interface
100007 ** attempts to load an SQLite extension library contained in the file
100008 ** zFile. {F12602} The entry point is zProc. {F12603} zProc may be 0
100009 ** in which case the name of the entry point defaults
100010 ** to "sqlite3_extension_init".
100011 **
100012 ** {F12604} The sqlite3_load_extension() interface shall
100013 ** return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
100014 **
100015 ** {F12605}
100016 ** If an error occurs and pzErrMsg is not 0, then the
100017 ** sqlite3_load_extension() interface shall attempt to fill *pzErrMsg with 
100018 ** error message text stored in memory obtained from [sqlite3_malloc()].
100019 ** {END}  The calling function should free this memory
100020 ** by calling [sqlite3_free()].
100021 **
100022 ** {F12606}
100023 ** Extension loading must be enabled using [sqlite3_enable_load_extension()]
100024 ** prior to calling this API or an error will be returned.
100025 */
100026 int sqlite3_load_extension(
100027   sqlite3 *db,          /* Load the extension into this database connection */
100028   const char *zFile,    /* Name of the shared library containing extension */
100029   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
100030   char **pzErrMsg       /* Put error message here if not 0 */
100031 );
100032
100033 /*
100034 ** CAPI3REF:  Enable Or Disable Extension Loading {F12620}
100035 **
100036 ** So as not to open security holes in older applications that are
100037 ** unprepared to deal with extension loading, and as a means of disabling
100038 ** extension loading while evaluating user-entered SQL, the following
100039 ** API is provided to turn the [sqlite3_load_extension()] mechanism on and
100040 ** off.  {F12622} It is off by default. {END} See ticket #1863.
100041 **
100042 ** {F12621} Call the sqlite3_enable_load_extension() routine
100043 ** with onoff==1 to turn extension loading on
100044 ** and call it with onoff==0 to turn it back off again. {END}
100045 */
100046 int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
100047
100048 /*
100049 ** CAPI3REF: Make Arrangements To Automatically Load An Extension {F12640}
100050 **
100051 ** {F12641} This function
100052 ** registers an extension entry point that is automatically invoked
100053 ** whenever a new database connection is opened using
100054 ** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. {END}
100055 **
100056 ** This API can be invoked at program startup in order to register
100057 ** one or more statically linked extensions that will be available
100058 ** to all new database connections.
100059 **
100060 ** {F12642} Duplicate extensions are detected so calling this routine multiple
100061 ** times with the same extension is harmless.
100062 **
100063 ** {F12643} This routine stores a pointer to the extension in an array
100064 ** that is obtained from sqlite_malloc(). {END} If you run a memory leak
100065 ** checker on your program and it reports a leak because of this
100066 ** array, then invoke [sqlite3_reset_auto_extension()] prior
100067 ** to shutdown to free the memory.
100068 **
100069 ** {F12644} Automatic extensions apply across all threads. {END}
100070 **
100071 ** This interface is experimental and is subject to change or
100072 ** removal in future releases of SQLite.
100073 */
100074 int sqlite3_auto_extension(void *xEntryPoint);
100075
100076
100077 /*
100078 ** CAPI3REF: Reset Automatic Extension Loading {F12660}
100079 **
100080 ** {F12661} This function disables all previously registered
100081 ** automatic extensions. {END}  This
100082 ** routine undoes the effect of all prior [sqlite3_automatic_extension()]
100083 ** calls.
100084 **
100085 ** {F12662} This call disabled automatic extensions in all threads. {END}
100086 **
100087 ** This interface is experimental and is subject to change or
100088 ** removal in future releases of SQLite.
100089 */
100090 void sqlite3_reset_auto_extension(void);
100091
100092
100093 /*
100094 ****** EXPERIMENTAL - subject to change without notice **************
100095 **
100096 ** The interface to the virtual-table mechanism is currently considered
100097 ** to be experimental.  The interface might change in incompatible ways.
100098 ** If this is a problem for you, do not use the interface at this time.
100099 **
100100 ** When the virtual-table mechanism stablizes, we will declare the
100101 ** interface fixed, support it indefinitely, and remove this comment.
100102 */
100103
100104 /*
100105 ** Structures used by the virtual table interface
100106 */
100107 typedef struct sqlite3_vtab sqlite3_vtab;
100108 typedef struct sqlite3_index_info sqlite3_index_info;
100109 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
100110 typedef struct sqlite3_module sqlite3_module;
100111
100112 /*
100113 ** A module is a class of virtual tables.  Each module is defined
100114 ** by an instance of the following structure.  This structure consists
100115 ** mostly of methods for the module.
100116 */
100117 struct sqlite3_module {
100118   int iVersion;
100119   int (*xCreate)(sqlite3*, void *pAux,
100120                int argc, const char *const*argv,
100121                sqlite3_vtab **ppVTab, char**);
100122   int (*xConnect)(sqlite3*, void *pAux,
100123                int argc, const char *const*argv,
100124                sqlite3_vtab **ppVTab, char**);
100125   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
100126   int (*xDisconnect)(sqlite3_vtab *pVTab);
100127   int (*xDestroy)(sqlite3_vtab *pVTab);
100128   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
100129   int (*xClose)(sqlite3_vtab_cursor*);
100130   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
100131                 int argc, sqlite3_value **argv);
100132   int (*xNext)(sqlite3_vtab_cursor*);
100133   int (*xEof)(sqlite3_vtab_cursor*);
100134   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
100135   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
100136   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
100137   int (*xBegin)(sqlite3_vtab *pVTab);
100138   int (*xSync)(sqlite3_vtab *pVTab);
100139   int (*xCommit)(sqlite3_vtab *pVTab);
100140   int (*xRollback)(sqlite3_vtab *pVTab);
100141   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
100142                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
100143                        void **ppArg);
100144
100145   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
100146 };
100147
100148 /*
100149 ** The sqlite3_index_info structure and its substructures is used to
100150 ** pass information into and receive the reply from the xBestIndex
100151 ** method of an sqlite3_module.  The fields under **Inputs** are the
100152 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
100153 ** results into the **Outputs** fields.
100154 **
100155 ** The aConstraint[] array records WHERE clause constraints of the
100156 ** form:
100157 **
100158 **         column OP expr
100159 **
100160 ** Where OP is =, &lt;, &lt;=, &gt;, or &gt;=.  
100161 ** The particular operator is stored
100162 ** in aConstraint[].op.  The index of the column is stored in 
100163 ** aConstraint[].iColumn.  aConstraint[].usable is TRUE if the
100164 ** expr on the right-hand side can be evaluated (and thus the constraint
100165 ** is usable) and false if it cannot.
100166 **
100167 ** The optimizer automatically inverts terms of the form "expr OP column"
100168 ** and makes other simplifications to the WHERE clause in an attempt to
100169 ** get as many WHERE clause terms into the form shown above as possible.
100170 ** The aConstraint[] array only reports WHERE clause terms in the correct
100171 ** form that refer to the particular virtual table being queried.
100172 **
100173 ** Information about the ORDER BY clause is stored in aOrderBy[].
100174 ** Each term of aOrderBy records a column of the ORDER BY clause.
100175 **
100176 ** The xBestIndex method must fill aConstraintUsage[] with information
100177 ** about what parameters to pass to xFilter.  If argvIndex>0 then
100178 ** the right-hand side of the corresponding aConstraint[] is evaluated
100179 ** and becomes the argvIndex-th entry in argv.  If aConstraintUsage[].omit
100180 ** is true, then the constraint is assumed to be fully handled by the
100181 ** virtual table and is not checked again by SQLite.
100182 **
100183 ** The idxNum and idxPtr values are recorded and passed into xFilter.
100184 ** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
100185 **
100186 ** The orderByConsumed means that output from xFilter will occur in
100187 ** the correct order to satisfy the ORDER BY clause so that no separate
100188 ** sorting step is required.
100189 **
100190 ** The estimatedCost value is an estimate of the cost of doing the
100191 ** particular lookup.  A full scan of a table with N entries should have
100192 ** a cost of N.  A binary search of a table of N entries should have a
100193 ** cost of approximately log(N).
100194 */
100195 struct sqlite3_index_info {
100196   /* Inputs */
100197   int nConstraint;           /* Number of entries in aConstraint */
100198   struct sqlite3_index_constraint {
100199      int iColumn;              /* Column on left-hand side of constraint */
100200      unsigned char op;         /* Constraint operator */
100201      unsigned char usable;     /* True if this constraint is usable */
100202      int iTermOffset;          /* Used internally - xBestIndex should ignore */
100203   } *aConstraint;            /* Table of WHERE clause constraints */
100204   int nOrderBy;              /* Number of terms in the ORDER BY clause */
100205   struct sqlite3_index_orderby {
100206      int iColumn;              /* Column number */
100207      unsigned char desc;       /* True for DESC.  False for ASC. */
100208   } *aOrderBy;               /* The ORDER BY clause */
100209
100210   /* Outputs */
100211   struct sqlite3_index_constraint_usage {
100212     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
100213     unsigned char omit;      /* Do not code a test for this constraint */
100214   } *aConstraintUsage;
100215   int idxNum;                /* Number used to identify the index */
100216   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
100217   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
100218   int orderByConsumed;       /* True if output is already ordered */
100219   double estimatedCost;      /* Estimated cost of using this index */
100220 };
100221 #define SQLITE_INDEX_CONSTRAINT_EQ    2
100222 #define SQLITE_INDEX_CONSTRAINT_GT    4
100223 #define SQLITE_INDEX_CONSTRAINT_LE    8
100224 #define SQLITE_INDEX_CONSTRAINT_LT    16
100225 #define SQLITE_INDEX_CONSTRAINT_GE    32
100226 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
100227
100228 /*
100229 ** This routine is used to register a new module name with an SQLite
100230 ** connection.  Module names must be registered before creating new
100231 ** virtual tables on the module, or before using preexisting virtual
100232 ** tables of the module.
100233 */
100234 int sqlite3_create_module(
100235   sqlite3 *db,               /* SQLite connection to register module with */
100236   const char *zName,         /* Name of the module */
100237   const sqlite3_module *,    /* Methods for the module */
100238   void *                     /* Client data for xCreate/xConnect */
100239 );
100240
100241 /*
100242 ** This routine is identical to the sqlite3_create_module() method above,
100243 ** except that it allows a destructor function to be specified. It is
100244 ** even more experimental than the rest of the virtual tables API.
100245 */
100246 int sqlite3_create_module_v2(
100247   sqlite3 *db,               /* SQLite connection to register module with */
100248   const char *zName,         /* Name of the module */
100249   const sqlite3_module *,    /* Methods for the module */
100250   void *,                    /* Client data for xCreate/xConnect */
100251   void(*xDestroy)(void*)     /* Module destructor function */
100252 );
100253
100254 /*
100255 ** Every module implementation uses a subclass of the following structure
100256 ** to describe a particular instance of the module.  Each subclass will
100257 ** be tailored to the specific needs of the module implementation.   The
100258 ** purpose of this superclass is to define certain fields that are common
100259 ** to all module implementations.
100260 **
100261 ** Virtual tables methods can set an error message by assigning a
100262 ** string obtained from sqlite3_mprintf() to zErrMsg.  The method should
100263 ** take care that any prior string is freed by a call to sqlite3_free()
100264 ** prior to assigning a new string to zErrMsg.  After the error message
100265 ** is delivered up to the client application, the string will be automatically
100266 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.  Note
100267 ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
100268 ** since virtual tables are commonly implemented in loadable extensions which
100269 ** do not have access to sqlite3MPrintf() or sqlite3Free().
100270 */
100271 struct sqlite3_vtab {
100272   const sqlite3_module *pModule;  /* The module for this virtual table */
100273   int nRef;                       /* Used internally */
100274   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
100275   /* Virtual table implementations will typically add additional fields */
100276 };
100277
100278 /* Every module implementation uses a subclass of the following structure
100279 ** to describe cursors that point into the virtual table and are used
100280 ** to loop through the virtual table.  Cursors are created using the
100281 ** xOpen method of the module.  Each module implementation will define
100282 ** the content of a cursor structure to suit its own needs.
100283 **
100284 ** This superclass exists in order to define fields of the cursor that
100285 ** are common to all implementations.
100286 */
100287 struct sqlite3_vtab_cursor {
100288   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
100289   /* Virtual table implementations will typically add additional fields */
100290 };
100291
100292 /*
100293 ** The xCreate and xConnect methods of a module use the following API
100294 ** to declare the format (the names and datatypes of the columns) of
100295 ** the virtual tables they implement.
100296 */
100297 int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
100298
100299 /*
100300 ** Virtual tables can provide alternative implementations of functions
100301 ** using the xFindFunction method.  But global versions of those functions
100302 ** must exist in order to be overloaded.
100303 **
100304 ** This API makes sure a global version of a function with a particular
100305 ** name and number of parameters exists.  If no such function exists
100306 ** before this API is called, a new function is created.  The implementation
100307 ** of the new function always causes an exception to be thrown.  So
100308 ** the new function is not good for anything by itself.  Its only
100309 ** purpose is to be a place-holder function that can be overloaded
100310 ** by virtual tables.
100311 **
100312 ** This API should be considered part of the virtual table interface,
100313 ** which is experimental and subject to change.
100314 */
100315 int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
100316
100317 /*
100318 ** The interface to the virtual-table mechanism defined above (back up
100319 ** to a comment remarkably similar to this one) is currently considered
100320 ** to be experimental.  The interface might change in incompatible ways.
100321 ** If this is a problem for you, do not use the interface at this time.
100322 **
100323 ** When the virtual-table mechanism stabilizes, we will declare the
100324 ** interface fixed, support it indefinitely, and remove this comment.
100325 **
100326 ****** EXPERIMENTAL - subject to change without notice **************
100327 */
100328
100329 /*
100330 ** CAPI3REF: A Handle To An Open BLOB {F17800}
100331 **
100332 ** An instance of the following opaque structure is used to 
100333 ** represent an blob-handle.  A blob-handle is created by
100334 ** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()].
100335 ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
100336 ** can be used to read or write small subsections of the blob.
100337 ** The [sqlite3_blob_bytes()] interface returns the size of the
100338 ** blob in bytes.
100339 */
100340 typedef struct sqlite3_blob sqlite3_blob;
100341
100342 /*
100343 ** CAPI3REF: Open A BLOB For Incremental I/O {F17810}
100344 **
100345 ** {F17811} This interfaces opens a handle to the blob located
100346 ** in row iRow,, column zColumn, table zTable in database zDb;
100347 ** in other words,  the same blob that would be selected by:
100348 **
100349 ** <pre>
100350 **     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
100351 ** </pre> {END}
100352 **
100353 ** {F17812} If the flags parameter is non-zero, the blob is opened for 
100354 ** read and write access. If it is zero, the blob is opened for read 
100355 ** access. {END}
100356 **
100357 ** {F17813} On success, [SQLITE_OK] is returned and the new 
100358 ** [sqlite3_blob | blob handle] is written to *ppBlob. 
100359 ** {F17814} Otherwise an error code is returned and 
100360 ** any value written to *ppBlob should not be used by the caller.
100361 ** {F17815} This function sets the database-handle error code and message
100362 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()].
100363 ** <todo>We should go through and mark all interfaces that behave this
100364 ** way with a similar statement</todo>
100365 */
100366 int sqlite3_blob_open(
100367   sqlite3*,
100368   const char *zDb,
100369   const char *zTable,
100370   const char *zColumn,
100371   sqlite3_int64 iRow,
100372   int flags,
100373   sqlite3_blob **ppBlob
100374 );
100375
100376 /*
100377 ** CAPI3REF:  Close A BLOB Handle {F17830}
100378 **
100379 ** Close an open [sqlite3_blob | blob handle].
100380 **
100381 ** {F17831} Closing a BLOB shall cause the current transaction to commit
100382 ** if there are no other BLOBs, no pending prepared statements, and the
100383 ** database connection is in autocommit mode.
100384 ** {F17832} If any writes were made to the BLOB, they might be held in cache
100385 ** until the close operation if they will fit. {END}
100386 ** Closing the BLOB often forces the changes
100387 ** out to disk and so if any I/O errors occur, they will likely occur
100388 ** at the time when the BLOB is closed.  {F17833} Any errors that occur during
100389 ** closing are reported as a non-zero return value.
100390 **
100391 ** {F17839} The BLOB is closed unconditionally.  Even if this routine returns
100392 ** an error code, the BLOB is still closed.
100393 */
100394 int sqlite3_blob_close(sqlite3_blob *);
100395
100396 /*
100397 ** CAPI3REF:  Return The Size Of An Open BLOB {F17805}
100398 **
100399 ** {F16806} Return the size in bytes of the blob accessible via the open 
100400 ** [sqlite3_blob | blob-handle] passed as an argument.
100401 */
100402 int sqlite3_blob_bytes(sqlite3_blob *);
100403
100404 /*
100405 ** CAPI3REF:  Read Data From A BLOB Incrementally {F17850}
100406 **
100407 ** This function is used to read data from an open 
100408 ** [sqlite3_blob | blob-handle] into a caller supplied buffer.
100409 ** {F17851} n bytes of data are copied into buffer
100410 ** z from the open blob, starting at offset iOffset.
100411 **
100412 ** {F17852} If offset iOffset is less than n bytes from the end of the blob, 
100413 ** [SQLITE_ERROR] is returned and no data is read.  {F17853} If n is
100414 ** less than zero [SQLITE_ERROR] is returned and no data is read.
100415 **
100416 ** {F17854} On success, SQLITE_OK is returned. Otherwise, an 
100417 ** [SQLITE_ERROR | SQLite error code] or an
100418 ** [SQLITE_IOERR_READ | extended error code] is returned.
100419 */
100420 int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset);
100421
100422 /*
100423 ** CAPI3REF:  Write Data Into A BLOB Incrementally {F17870}
100424 **
100425 ** This function is used to write data into an open 
100426 ** [sqlite3_blob | blob-handle] from a user supplied buffer.
100427 ** {F17871} n bytes of data are copied from the buffer
100428 ** pointed to by z into the open blob, starting at offset iOffset.
100429 **
100430 ** {F17872} If the [sqlite3_blob | blob-handle] passed as the first argument
100431 ** was not opened for writing (the flags parameter to [sqlite3_blob_open()]
100432 *** was zero), this function returns [SQLITE_READONLY].
100433 **
100434 ** {F17873} This function may only modify the contents of the blob; it is
100435 ** not possible to increase the size of a blob using this API.
100436 ** {F17874} If offset iOffset is less than n bytes from the end of the blob, 
100437 ** [SQLITE_ERROR] is returned and no data is written.  {F17875} If n is
100438 ** less than zero [SQLITE_ERROR] is returned and no data is written.
100439 **
100440 ** {F17876} On success, SQLITE_OK is returned. Otherwise, an 
100441 ** [SQLITE_ERROR | SQLite error code] or an
100442 ** [SQLITE_IOERR_READ | extended error code] is returned.
100443 */
100444 int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
100445
100446 /*
100447 ** CAPI3REF:  Virtual File System Objects {F11200}
100448 **
100449 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
100450 ** that SQLite uses to interact
100451 ** with the underlying operating system.  Most builds come with a
100452 ** single default VFS that is appropriate for the host computer.
100453 ** New VFSes can be registered and existing VFSes can be unregistered.
100454 ** The following interfaces are provided.
100455 **
100456 ** {F11201} The sqlite3_vfs_find() interface returns a pointer to 
100457 ** a VFS given its name.  {F11202} Names are case sensitive.
100458 ** {F11203} Names are zero-terminated UTF-8 strings.
100459 ** {F11204} If there is no match, a NULL
100460 ** pointer is returned. {F11205} If zVfsName is NULL then the default 
100461 ** VFS is returned. {END}
100462 **
100463 ** {F11210} New VFSes are registered with sqlite3_vfs_register().
100464 ** {F11211} Each new VFS becomes the default VFS if the makeDflt flag is set.
100465 ** {F11212} The same VFS can be registered multiple times without injury.
100466 ** {F11213} To make an existing VFS into the default VFS, register it again
100467 ** with the makeDflt flag set. {U11214} If two different VFSes with the
100468 ** same name are registered, the behavior is undefined.  {U11215} If a
100469 ** VFS is registered with a name that is NULL or an empty string,
100470 ** then the behavior is undefined.
100471 ** 
100472 ** {F11220} Unregister a VFS with the sqlite3_vfs_unregister() interface.
100473 ** {F11221} If the default VFS is unregistered, another VFS is chosen as
100474 ** the default.  The choice for the new VFS is arbitrary.
100475 */
100476 sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
100477 int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
100478 int sqlite3_vfs_unregister(sqlite3_vfs*);
100479
100480 /*
100481 ** CAPI3REF: Mutexes {F17000}
100482 **
100483 ** The SQLite core uses these routines for thread
100484 ** synchronization.  Though they are intended for internal
100485 ** use by SQLite, code that links against SQLite is
100486 ** permitted to use any of these routines.
100487 **
100488 ** The SQLite source code contains multiple implementations 
100489 ** of these mutex routines.  An appropriate implementation
100490 ** is selected automatically at compile-time.  The following
100491 ** implementations are available in the SQLite core:
100492 **
100493 ** <ul>
100494 ** <li>   SQLITE_MUTEX_OS2
100495 ** <li>   SQLITE_MUTEX_PTHREAD
100496 ** <li>   SQLITE_MUTEX_W32
100497 ** <li>   SQLITE_MUTEX_NOOP
100498 ** </ul>
100499 **
100500 ** The SQLITE_MUTEX_NOOP implementation is a set of routines 
100501 ** that does no real locking and is appropriate for use in 
100502 ** a single-threaded application.  The SQLITE_MUTEX_OS2,
100503 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
100504 ** are appropriate for use on os/2, unix, and windows.
100505 ** 
100506 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
100507 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
100508 ** implementation is included with the library.  The
100509 ** mutex interface routines defined here become external
100510 ** references in the SQLite library for which implementations
100511 ** must be provided by the application.  This facility allows an
100512 ** application that links against SQLite to provide its own mutex
100513 ** implementation without having to modify the SQLite core.
100514 **
100515 ** {F17011} The sqlite3_mutex_alloc() routine allocates a new
100516 ** mutex and returns a pointer to it. {F17012} If it returns NULL
100517 ** that means that a mutex could not be allocated. {F17013} SQLite
100518 ** will unwind its stack and return an error. {F17014} The argument
100519 ** to sqlite3_mutex_alloc() is one of these integer constants:
100520 **
100521 ** <ul>
100522 ** <li>  SQLITE_MUTEX_FAST
100523 ** <li>  SQLITE_MUTEX_RECURSIVE
100524 ** <li>  SQLITE_MUTEX_STATIC_MASTER
100525 ** <li>  SQLITE_MUTEX_STATIC_MEM
100526 ** <li>  SQLITE_MUTEX_STATIC_MEM2
100527 ** <li>  SQLITE_MUTEX_STATIC_PRNG
100528 ** <li>  SQLITE_MUTEX_STATIC_LRU
100529 ** </ul> {END}
100530 **
100531 ** {F17015} The first two constants cause sqlite3_mutex_alloc() to create
100532 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
100533 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END}
100534 ** The mutex implementation does not need to make a distinction
100535 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
100536 ** not want to.  {F17016} But SQLite will only request a recursive mutex in
100537 ** cases where it really needs one.  {END} If a faster non-recursive mutex
100538 ** implementation is available on the host platform, the mutex subsystem
100539 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
100540 **
100541 ** {F17017} The other allowed parameters to sqlite3_mutex_alloc() each return
100542 ** a pointer to a static preexisting mutex. {END}  Four static mutexes are
100543 ** used by the current version of SQLite.  Future versions of SQLite
100544 ** may add additional static mutexes.  Static mutexes are for internal
100545 ** use by SQLite only.  Applications that use SQLite mutexes should
100546 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
100547 ** SQLITE_MUTEX_RECURSIVE.
100548 **
100549 ** {F17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
100550 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
100551 ** returns a different mutex on every call.  {F17034} But for the static 
100552 ** mutex types, the same mutex is returned on every call that has
100553 ** the same type number. {END}
100554 **
100555 ** {F17019} The sqlite3_mutex_free() routine deallocates a previously
100556 ** allocated dynamic mutex. {F17020} SQLite is careful to deallocate every
100557 ** dynamic mutex that it allocates. {U17021} The dynamic mutexes must not be in 
100558 ** use when they are deallocated. {U17022} Attempting to deallocate a static
100559 ** mutex results in undefined behavior. {F17023} SQLite never deallocates
100560 ** a static mutex. {END}
100561 **
100562 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
100563 ** to enter a mutex. {F17024} If another thread is already within the mutex,
100564 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
100565 ** SQLITE_BUSY. {F17025}  The sqlite3_mutex_try() interface returns SQLITE_OK
100566 ** upon successful entry.  {F17026} Mutexes created using
100567 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
100568 ** {F17027} In such cases the,
100569 ** mutex must be exited an equal number of times before another thread
100570 ** can enter.  {U17028} If the same thread tries to enter any other
100571 ** kind of mutex more than once, the behavior is undefined.
100572 ** {F17029} SQLite will never exhibit
100573 ** such behavior in its own use of mutexes. {END}
100574 **
100575 ** Some systems (ex: windows95) do not the operation implemented by
100576 ** sqlite3_mutex_try().  On those systems, sqlite3_mutex_try() will
100577 ** always return SQLITE_BUSY.  {F17030} The SQLite core only ever uses
100578 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior. {END}
100579 **
100580 ** {F17031} The sqlite3_mutex_leave() routine exits a mutex that was
100581 ** previously entered by the same thread.  {U17032} The behavior
100582 ** is undefined if the mutex is not currently entered by the
100583 ** calling thread or is not currently allocated.  {F17033} SQLite will
100584 ** never do either. {END}
100585 **
100586 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
100587 */
100588 sqlite3_mutex *sqlite3_mutex_alloc(int);
100589 void sqlite3_mutex_free(sqlite3_mutex*);
100590 void sqlite3_mutex_enter(sqlite3_mutex*);
100591 int sqlite3_mutex_try(sqlite3_mutex*);
100592 void sqlite3_mutex_leave(sqlite3_mutex*);
100593
100594 /*
100595 ** CAPI3REF: Mutex Verifcation Routines {F17080}
100596 **
100597 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
100598 ** are intended for use inside assert() statements. {F17081} The SQLite core
100599 ** never uses these routines except inside an assert() and applications
100600 ** are advised to follow the lead of the core.  {F17082} The core only
100601 ** provides implementations for these routines when it is compiled
100602 ** with the SQLITE_DEBUG flag.  {U17087} External mutex implementations
100603 ** are only required to provide these routines if SQLITE_DEBUG is
100604 ** defined and if NDEBUG is not defined.
100605 **
100606 ** {F17083} These routines should return true if the mutex in their argument
100607 ** is held or not held, respectively, by the calling thread. {END}
100608 **
100609 ** {X17084} The implementation is not required to provided versions of these
100610 ** routines that actually work.
100611 ** If the implementation does not provide working
100612 ** versions of these routines, it should at least provide stubs
100613 ** that always return true so that one does not get spurious
100614 ** assertion failures. {END}
100615 **
100616 ** {F17085} If the argument to sqlite3_mutex_held() is a NULL pointer then
100617 ** the routine should return 1.  {END} This seems counter-intuitive since
100618 ** clearly the mutex cannot be held if it does not exist.  But the
100619 ** the reason the mutex does not exist is because the build is not
100620 ** using mutexes.  And we do not want the assert() containing the
100621 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
100622 ** the appropriate thing to do.  {F17086} The sqlite3_mutex_notheld() 
100623 ** interface should also return 1 when given a NULL pointer.
100624 */
100625 int sqlite3_mutex_held(sqlite3_mutex*);
100626 int sqlite3_mutex_notheld(sqlite3_mutex*);
100627
100628 /*
100629 ** CAPI3REF: Mutex Types {F17001}
100630 **
100631 ** {F17002} The [sqlite3_mutex_alloc()] interface takes a single argument
100632 ** which is one of these integer constants. {END}
100633 */
100634 #define SQLITE_MUTEX_FAST             0
100635 #define SQLITE_MUTEX_RECURSIVE        1
100636 #define SQLITE_MUTEX_STATIC_MASTER    2
100637 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
100638 #define SQLITE_MUTEX_STATIC_MEM2      4  /* sqlite3_release_memory() */
100639 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
100640 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
100641
100642 /*
100643 ** CAPI3REF: Low-Level Control Of Database Files {F11300}
100644 **
100645 ** {F11301} The [sqlite3_file_control()] interface makes a direct call to the
100646 ** xFileControl method for the [sqlite3_io_methods] object associated
100647 ** with a particular database identified by the second argument. {F11302} The
100648 ** name of the database is the name assigned to the database by the
100649 ** <a href="lang_attach.html">ATTACH</a> SQL command that opened the
100650 ** database. {F11303} To control the main database file, use the name "main"
100651 ** or a NULL pointer. {F11304} The third and fourth parameters to this routine
100652 ** are passed directly through to the second and third parameters of
100653 ** the xFileControl method.  {F11305} The return value of the xFileControl
100654 ** method becomes the return value of this routine.
100655 **
100656 ** {F11306} If the second parameter (zDbName) does not match the name of any
100657 ** open database file, then SQLITE_ERROR is returned. {F11307} This error
100658 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
100659 ** or [sqlite3_errmsg()]. {U11308} The underlying xFileControl method might
100660 ** also return SQLITE_ERROR.  {U11309} There is no way to distinguish between
100661 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
100662 ** xFileControl method. {END}
100663 **
100664 ** See also: [SQLITE_FCNTL_LOCKSTATE]
100665 */
100666 int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
100667
100668 /*
100669 ** Undo the hack that converts floating point types to integer for
100670 ** builds on processors without floating point support.
100671 */
100672 #ifdef SQLITE_OMIT_FLOATING_POINT
100673 # undef double
100674 #endif
100675
100676 #if 0
100677 }  /* End of the 'extern "C"' block */
100678 #endif
100679 #endif
100680
100681 /************** End of sqlite3.h *********************************************/
100682 /************** Continuing where we left off in sqlite3ext.h *****************/
100683
100684 typedef struct sqlite3_api_routines sqlite3_api_routines;
100685
100686 /*
100687 ** The following structure hold pointers to all of the SQLite API
100688 ** routines.
100689 **
100690 ** WARNING:  In order to maintain backwards compatibility, add new
100691 ** interfaces to the end of this structure only.  If you insert new
100692 ** interfaces in the middle of this structure, then older different
100693 ** versions of SQLite will not be able to load each others shared
100694 ** libraries!
100695 */
100696 struct sqlite3_api_routines {
100697   void * (*aggregate_context)(sqlite3_context*,int nBytes);
100698   int  (*aggregate_count)(sqlite3_context*);
100699   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
100700   int  (*bind_double)(sqlite3_stmt*,int,double);
100701   int  (*bind_int)(sqlite3_stmt*,int,int);
100702   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
100703   int  (*bind_null)(sqlite3_stmt*,int);
100704   int  (*bind_parameter_count)(sqlite3_stmt*);
100705   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
100706   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
100707   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
100708   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
100709   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
100710   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
100711   int  (*busy_timeout)(sqlite3*,int ms);
100712   int  (*changes)(sqlite3*);
100713   int  (*close)(sqlite3*);
100714   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
100715   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
100716   const void * (*column_blob)(sqlite3_stmt*,int iCol);
100717   int  (*column_bytes)(sqlite3_stmt*,int iCol);
100718   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
100719   int  (*column_count)(sqlite3_stmt*pStmt);
100720   const char * (*column_database_name)(sqlite3_stmt*,int);
100721   const void * (*column_database_name16)(sqlite3_stmt*,int);
100722   const char * (*column_decltype)(sqlite3_stmt*,int i);
100723   const void * (*column_decltype16)(sqlite3_stmt*,int);
100724   double  (*column_double)(sqlite3_stmt*,int iCol);
100725   int  (*column_int)(sqlite3_stmt*,int iCol);
100726   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
100727   const char * (*column_name)(sqlite3_stmt*,int);
100728   const void * (*column_name16)(sqlite3_stmt*,int);
100729   const char * (*column_origin_name)(sqlite3_stmt*,int);
100730   const void * (*column_origin_name16)(sqlite3_stmt*,int);
100731   const char * (*column_table_name)(sqlite3_stmt*,int);
100732   const void * (*column_table_name16)(sqlite3_stmt*,int);
100733   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
100734   const void * (*column_text16)(sqlite3_stmt*,int iCol);
100735   int  (*column_type)(sqlite3_stmt*,int iCol);
100736   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
100737   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
100738   int  (*complete)(const char*sql);
100739   int  (*complete16)(const void*sql);
100740   int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
100741   int  (*create_collation16)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
100742   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*));
100743   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*));
100744   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
100745   int  (*data_count)(sqlite3_stmt*pStmt);
100746   sqlite3 * (*db_handle)(sqlite3_stmt*);
100747   int (*declare_vtab)(sqlite3*,const char*);
100748   int  (*enable_shared_cache)(int);
100749   int  (*errcode)(sqlite3*db);
100750   const char * (*errmsg)(sqlite3*);
100751   const void * (*errmsg16)(sqlite3*);
100752   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
100753   int  (*expired)(sqlite3_stmt*);
100754   int  (*finalize)(sqlite3_stmt*pStmt);
100755   void  (*free)(void*);
100756   void  (*free_table)(char**result);
100757   int  (*get_autocommit)(sqlite3*);
100758   void * (*get_auxdata)(sqlite3_context*,int);
100759   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
100760   int  (*global_recover)(void);
100761   void  (*interruptx)(sqlite3*);
100762   sqlite_int64  (*last_insert_rowid)(sqlite3*);
100763   const char * (*libversion)(void);
100764   int  (*libversion_number)(void);
100765   void *(*malloc)(int);
100766   char * (*mprintf)(const char*,...);
100767   int  (*open)(const char*,sqlite3**);
100768   int  (*open16)(const void*,sqlite3**);
100769   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
100770   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
100771   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
100772   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
100773   void *(*realloc)(void*,int);
100774   int  (*reset)(sqlite3_stmt*pStmt);
100775   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
100776   void  (*result_double)(sqlite3_context*,double);
100777   void  (*result_error)(sqlite3_context*,const char*,int);
100778   void  (*result_error16)(sqlite3_context*,const void*,int);
100779   void  (*result_int)(sqlite3_context*,int);
100780   void  (*result_int64)(sqlite3_context*,sqlite_int64);
100781   void  (*result_null)(sqlite3_context*);
100782   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
100783   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
100784   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
100785   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
100786   void  (*result_value)(sqlite3_context*,sqlite3_value*);
100787   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
100788   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
100789   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
100790   char * (*snprintf)(int,char*,const char*,...);
100791   int  (*step)(sqlite3_stmt*);
100792   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
100793   void  (*thread_cleanup)(void);
100794   int  (*total_changes)(sqlite3*);
100795   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
100796   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
100797   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
100798   void * (*user_data)(sqlite3_context*);
100799   const void * (*value_blob)(sqlite3_value*);
100800   int  (*value_bytes)(sqlite3_value*);
100801   int  (*value_bytes16)(sqlite3_value*);
100802   double  (*value_double)(sqlite3_value*);
100803   int  (*value_int)(sqlite3_value*);
100804   sqlite_int64  (*value_int64)(sqlite3_value*);
100805   int  (*value_numeric_type)(sqlite3_value*);
100806   const unsigned char * (*value_text)(sqlite3_value*);
100807   const void * (*value_text16)(sqlite3_value*);
100808   const void * (*value_text16be)(sqlite3_value*);
100809   const void * (*value_text16le)(sqlite3_value*);
100810   int  (*value_type)(sqlite3_value*);
100811   char *(*vmprintf)(const char*,va_list);
100812   /* Added ??? */
100813   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
100814   /* Added by 3.3.13 */
100815   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
100816   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
100817   int (*clear_bindings)(sqlite3_stmt*);
100818   /* Added by 3.4.1 */
100819   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
100820   /* Added by 3.5.0 */
100821   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
100822   int (*blob_bytes)(sqlite3_blob*);
100823   int (*blob_close)(sqlite3_blob*);
100824   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
100825   int (*blob_read)(sqlite3_blob*,void*,int,int);
100826   int (*blob_write)(sqlite3_blob*,const void*,int,int);
100827   int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
100828   int (*file_control)(sqlite3*,const char*,int,void*);
100829   sqlite3_int64 (*memory_highwater)(int);
100830   sqlite3_int64 (*memory_used)(void);
100831   sqlite3_mutex *(*mutex_alloc)(int);
100832   void (*mutex_enter)(sqlite3_mutex*);
100833   void (*mutex_free)(sqlite3_mutex*);
100834   void (*mutex_leave)(sqlite3_mutex*);
100835   int (*mutex_try)(sqlite3_mutex*);
100836   int (*open_v2)(const char*,sqlite3**,int,const char*);
100837   int (*release_memory)(int);
100838   void (*result_error_nomem)(sqlite3_context*);
100839   void (*result_error_toobig)(sqlite3_context*);
100840   int (*sleep)(int);
100841   void (*soft_heap_limit)(int);
100842   sqlite3_vfs *(*vfs_find)(const char*);
100843   int (*vfs_register)(sqlite3_vfs*,int);
100844   int (*vfs_unregister)(sqlite3_vfs*);
100845 };
100846
100847 /*
100848 ** The following macros redefine the API routines so that they are
100849 ** redirected throught the global sqlite3_api structure.
100850 **
100851 ** This header file is also used by the loadext.c source file
100852 ** (part of the main SQLite library - not an extension) so that
100853 ** it can get access to the sqlite3_api_routines structure
100854 ** definition.  But the main library does not want to redefine
100855 ** the API.  So the redefinition macros are only valid if the
100856 ** SQLITE_CORE macros is undefined.
100857 */
100858 #ifndef SQLITE_CORE
100859 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
100860 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
100861 #define sqlite3_bind_blob              sqlite3_api->bind_blob
100862 #define sqlite3_bind_double            sqlite3_api->bind_double
100863 #define sqlite3_bind_int               sqlite3_api->bind_int
100864 #define sqlite3_bind_int64             sqlite3_api->bind_int64
100865 #define sqlite3_bind_null              sqlite3_api->bind_null
100866 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
100867 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
100868 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
100869 #define sqlite3_bind_text              sqlite3_api->bind_text
100870 #define sqlite3_bind_text16            sqlite3_api->bind_text16
100871 #define sqlite3_bind_value             sqlite3_api->bind_value
100872 #define sqlite3_busy_handler           sqlite3_api->busy_handler
100873 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
100874 #define sqlite3_changes                sqlite3_api->changes
100875 #define sqlite3_close                  sqlite3_api->close
100876 #define sqlite3_collation_needed       sqlite3_api->collation_needed
100877 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
100878 #define sqlite3_column_blob            sqlite3_api->column_blob
100879 #define sqlite3_column_bytes           sqlite3_api->column_bytes
100880 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
100881 #define sqlite3_column_count           sqlite3_api->column_count
100882 #define sqlite3_column_database_name   sqlite3_api->column_database_name
100883 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
100884 #define sqlite3_column_decltype        sqlite3_api->column_decltype
100885 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
100886 #define sqlite3_column_double          sqlite3_api->column_double
100887 #define sqlite3_column_int             sqlite3_api->column_int
100888 #define sqlite3_column_int64           sqlite3_api->column_int64
100889 #define sqlite3_column_name            sqlite3_api->column_name
100890 #define sqlite3_column_name16          sqlite3_api->column_name16
100891 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
100892 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
100893 #define sqlite3_column_table_name      sqlite3_api->column_table_name
100894 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
100895 #define sqlite3_column_text            sqlite3_api->column_text
100896 #define sqlite3_column_text16          sqlite3_api->column_text16
100897 #define sqlite3_column_type            sqlite3_api->column_type
100898 #define sqlite3_column_value           sqlite3_api->column_value
100899 #define sqlite3_commit_hook            sqlite3_api->commit_hook
100900 #define sqlite3_complete               sqlite3_api->complete
100901 #define sqlite3_complete16             sqlite3_api->complete16
100902 #define sqlite3_create_collation       sqlite3_api->create_collation
100903 #define sqlite3_create_collation16     sqlite3_api->create_collation16
100904 #define sqlite3_create_function        sqlite3_api->create_function
100905 #define sqlite3_create_function16      sqlite3_api->create_function16
100906 #define sqlite3_create_module          sqlite3_api->create_module
100907 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
100908 #define sqlite3_data_count             sqlite3_api->data_count
100909 #define sqlite3_db_handle              sqlite3_api->db_handle
100910 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
100911 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
100912 #define sqlite3_errcode                sqlite3_api->errcode
100913 #define sqlite3_errmsg                 sqlite3_api->errmsg
100914 #define sqlite3_errmsg16               sqlite3_api->errmsg16
100915 #define sqlite3_exec                   sqlite3_api->exec
100916 #define sqlite3_expired                sqlite3_api->expired
100917 #define sqlite3_finalize               sqlite3_api->finalize
100918 #define sqlite3_free                   sqlite3_api->free
100919 #define sqlite3_free_table             sqlite3_api->free_table
100920 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
100921 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
100922 #define sqlite3_get_table              sqlite3_api->get_table
100923 #define sqlite3_global_recover         sqlite3_api->global_recover
100924 #define sqlite3_interrupt              sqlite3_api->interruptx
100925 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
100926 #define sqlite3_libversion             sqlite3_api->libversion
100927 #define sqlite3_libversion_number      sqlite3_api->libversion_number
100928 #define sqlite3_malloc                 sqlite3_api->malloc
100929 #define sqlite3_mprintf                sqlite3_api->mprintf
100930 #define sqlite3_open                   sqlite3_api->open
100931 #define sqlite3_open16                 sqlite3_api->open16
100932 #define sqlite3_prepare                sqlite3_api->prepare
100933 #define sqlite3_prepare16              sqlite3_api->prepare16
100934 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
100935 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
100936 #define sqlite3_profile                sqlite3_api->profile
100937 #define sqlite3_progress_handler       sqlite3_api->progress_handler
100938 #define sqlite3_realloc                sqlite3_api->realloc
100939 #define sqlite3_reset                  sqlite3_api->reset
100940 #define sqlite3_result_blob            sqlite3_api->result_blob
100941 #define sqlite3_result_double          sqlite3_api->result_double
100942 #define sqlite3_result_error           sqlite3_api->result_error
100943 #define sqlite3_result_error16         sqlite3_api->result_error16
100944 #define sqlite3_result_int             sqlite3_api->result_int
100945 #define sqlite3_result_int64           sqlite3_api->result_int64
100946 #define sqlite3_result_null            sqlite3_api->result_null
100947 #define sqlite3_result_text            sqlite3_api->result_text
100948 #define sqlite3_result_text16          sqlite3_api->result_text16
100949 #define sqlite3_result_text16be        sqlite3_api->result_text16be
100950 #define sqlite3_result_text16le        sqlite3_api->result_text16le
100951 #define sqlite3_result_value           sqlite3_api->result_value
100952 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
100953 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
100954 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
100955 #define sqlite3_snprintf               sqlite3_api->snprintf
100956 #define sqlite3_step                   sqlite3_api->step
100957 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
100958 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
100959 #define sqlite3_total_changes          sqlite3_api->total_changes
100960 #define sqlite3_trace                  sqlite3_api->trace
100961 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
100962 #define sqlite3_update_hook            sqlite3_api->update_hook
100963 #define sqlite3_user_data              sqlite3_api->user_data
100964 #define sqlite3_value_blob             sqlite3_api->value_blob
100965 #define sqlite3_value_bytes            sqlite3_api->value_bytes
100966 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
100967 #define sqlite3_value_double           sqlite3_api->value_double
100968 #define sqlite3_value_int              sqlite3_api->value_int
100969 #define sqlite3_value_int64            sqlite3_api->value_int64
100970 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
100971 #define sqlite3_value_text             sqlite3_api->value_text
100972 #define sqlite3_value_text16           sqlite3_api->value_text16
100973 #define sqlite3_value_text16be         sqlite3_api->value_text16be
100974 #define sqlite3_value_text16le         sqlite3_api->value_text16le
100975 #define sqlite3_value_type             sqlite3_api->value_type
100976 #define sqlite3_vmprintf               sqlite3_api->vmprintf
100977 #define sqlite3_overload_function      sqlite3_api->overload_function
100978 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
100979 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
100980 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
100981 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
100982 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
100983 #define sqlite3_blob_close             sqlite3_api->blob_close
100984 #define sqlite3_blob_open              sqlite3_api->blob_open
100985 #define sqlite3_blob_read              sqlite3_api->blob_read
100986 #define sqlite3_blob_write             sqlite3_api->blob_write
100987 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
100988 #define sqlite3_file_control           sqlite3_api->file_control
100989 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
100990 #define sqlite3_memory_used            sqlite3_api->memory_used
100991 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
100992 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
100993 #define sqlite3_mutex_free             sqlite3_api->mutex_free
100994 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
100995 #define sqlite3_mutex_try              sqlite3_api->mutex_try
100996 #define sqlite3_open_v2                sqlite3_api->open_v2
100997 #define sqlite3_release_memory         sqlite3_api->release_memory
100998 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
100999 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
101000 #define sqlite3_sleep                  sqlite3_api->sleep
101001 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
101002 #define sqlite3_vfs_find               sqlite3_api->vfs_find
101003 #define sqlite3_vfs_register           sqlite3_api->vfs_register
101004 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
101005 #endif /* SQLITE_CORE */
101006
101007 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api;
101008 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
101009
101010 #endif /* _SQLITE3EXT_H_ */
101011
101012 /************** End of sqlite3ext.h ******************************************/
101013 /************** Continuing where we left off in fts3_tokenizer.c *************/
101014 SQLITE_EXTENSION_INIT1
101015
101016 /************** Include fts3_hash.h in the middle of fts3_tokenizer.c ********/
101017 /************** Begin file fts3_hash.h ***************************************/
101018 /*
101019 ** 2001 September 22
101020 **
101021 ** The author disclaims copyright to this source code.  In place of
101022 ** a legal notice, here is a blessing:
101023 **
101024 **    May you do good and not evil.
101025 **    May you find forgiveness for yourself and forgive others.
101026 **    May you share freely, never taking more than you give.
101027 **
101028 *************************************************************************
101029 ** This is the header file for the generic hash-table implemenation
101030 ** used in SQLite.  We've modified it slightly to serve as a standalone
101031 ** hash table implementation for the full-text indexing module.
101032 **
101033 */
101034 #ifndef _FTS3_HASH_H_
101035 #define _FTS3_HASH_H_
101036
101037 /* Forward declarations of structures. */
101038 typedef struct fts3Hash fts3Hash;
101039 typedef struct fts3HashElem fts3HashElem;
101040
101041 /* A complete hash table is an instance of the following structure.
101042 ** The internals of this structure are intended to be opaque -- client
101043 ** code should not attempt to access or modify the fields of this structure
101044 ** directly.  Change this structure only by using the routines below.
101045 ** However, many of the "procedures" and "functions" for modifying and
101046 ** accessing this structure are really macros, so we can't really make
101047 ** this structure opaque.
101048 */
101049 struct fts3Hash {
101050   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
101051   char copyKey;           /* True if copy of key made on insert */
101052   int count;              /* Number of entries in this table */
101053   fts3HashElem *first;    /* The first element of the array */
101054   int htsize;             /* Number of buckets in the hash table */
101055   struct _fts3ht {        /* the hash table */
101056     int count;               /* Number of entries with this hash */
101057     fts3HashElem *chain;     /* Pointer to first entry with this hash */
101058   } *ht;
101059 };
101060
101061 /* Each element in the hash table is an instance of the following 
101062 ** structure.  All elements are stored on a single doubly-linked list.
101063 **
101064 ** Again, this structure is intended to be opaque, but it can't really
101065 ** be opaque because it is used by macros.
101066 */
101067 struct fts3HashElem {
101068   fts3HashElem *next, *prev; /* Next and previous elements in the table */
101069   void *data;                /* Data associated with this element */
101070   void *pKey; int nKey;      /* Key associated with this element */
101071 };
101072
101073 /*
101074 ** There are 2 different modes of operation for a hash table:
101075 **
101076 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
101077 **                           (including the null-terminator, if any).  Case
101078 **                           is respected in comparisons.
101079 **
101080 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
101081 **                           memcmp() is used to compare keys.
101082 **
101083 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
101084 */
101085 #define FTS3_HASH_STRING    1
101086 #define FTS3_HASH_BINARY    2
101087
101088 /*
101089 ** Access routines.  To delete, insert a NULL pointer.
101090 */
101091 void sqlite3Fts3HashInit(fts3Hash*, int keytype, int copyKey);
101092 void *sqlite3Fts3HashInsert(fts3Hash*, const void *pKey, int nKey, void *pData);
101093 void *sqlite3Fts3HashFind(const fts3Hash*, const void *pKey, int nKey);
101094 void sqlite3Fts3HashClear(fts3Hash*);
101095
101096 /*
101097 ** Shorthand for the functions above
101098 */
101099 #define fts3HashInit   sqlite3Fts3HashInit
101100 #define fts3HashInsert sqlite3Fts3HashInsert
101101 #define fts3HashFind   sqlite3Fts3HashFind
101102 #define fts3HashClear  sqlite3Fts3HashClear
101103
101104 /*
101105 ** Macros for looping over all elements of a hash table.  The idiom is
101106 ** like this:
101107 **
101108 **   fts3Hash h;
101109 **   fts3HashElem *p;
101110 **   ...
101111 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
101112 **     SomeStructure *pData = fts3HashData(p);
101113 **     // do something with pData
101114 **   }
101115 */
101116 #define fts3HashFirst(H)  ((H)->first)
101117 #define fts3HashNext(E)   ((E)->next)
101118 #define fts3HashData(E)   ((E)->data)
101119 #define fts3HashKey(E)    ((E)->pKey)
101120 #define fts3HashKeysize(E) ((E)->nKey)
101121
101122 /*
101123 ** Number of entries in a hash table
101124 */
101125 #define fts3HashCount(H)  ((H)->count)
101126
101127 #endif /* _FTS3_HASH_H_ */
101128
101129 /************** End of fts3_hash.h *******************************************/
101130 /************** Continuing where we left off in fts3_tokenizer.c *************/
101131 /************** Include fts3_tokenizer.h in the middle of fts3_tokenizer.c ***/
101132 /************** Begin file fts3_tokenizer.h **********************************/
101133 /*
101134 ** 2006 July 10
101135 **
101136 ** The author disclaims copyright to this source code.
101137 **
101138 *************************************************************************
101139 ** Defines the interface to tokenizers used by fulltext-search.  There
101140 ** are three basic components:
101141 **
101142 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
101143 ** interface functions.  This is essentially the class structure for
101144 ** tokenizers.
101145 **
101146 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
101147 ** including customization information defined at creation time.
101148 **
101149 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
101150 ** tokens from a particular input.
101151 */
101152 #ifndef _FTS3_TOKENIZER_H_
101153 #define _FTS3_TOKENIZER_H_
101154
101155 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
101156 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
101157 ** we will need a way to register the API consistently.
101158 */
101159 /************** Include sqlite3.h in the middle of fts3_tokenizer.h **********/
101160 /************** Begin file sqlite3.h *****************************************/
101161 /*
101162 ** 2001 September 15
101163 **
101164 ** The author disclaims copyright to this source code.  In place of
101165 ** a legal notice, here is a blessing:
101166 **
101167 **    May you do good and not evil.
101168 **    May you find forgiveness for yourself and forgive others.
101169 **    May you share freely, never taking more than you give.
101170 **
101171 *************************************************************************
101172 ** This header file defines the interface that the SQLite library
101173 ** presents to client programs.  If a C-function, structure, datatype,
101174 ** or constant definition does not appear in this file, then it is
101175 ** not a published API of SQLite, is subject to change without
101176 ** notice, and should not be referenced by programs that use SQLite.
101177 **
101178 ** Some of the definitions that are in this file are marked as
101179 ** "experimental".  Experimental interfaces are normally new
101180 ** features recently added to SQLite.  We do not anticipate changes 
101181 ** to experimental interfaces but reserve to make minor changes if
101182 ** experience from use "in the wild" suggest such changes are prudent.
101183 **
101184 ** The official C-language API documentation for SQLite is derived
101185 ** from comments in this file.  This file is the authoritative source
101186 ** on how SQLite interfaces are suppose to operate.
101187 **
101188 ** The name of this file under configuration management is "sqlite.h.in".
101189 ** The makefile makes some minor changes to this file (such as inserting
101190 ** the version number) and changes its name to "sqlite3.h" as
101191 ** part of the build process.
101192 **
101193 ** @(#) $Id: sqlite.h.in,v 1.278 2007/12/13 21:54:11 drh Exp $
101194 */
101195 #ifndef _SQLITE3_H_
101196 #define _SQLITE3_H_
101197
101198 /*
101199 ** Make sure we can call this stuff from C++.
101200 */
101201 #if 0
101202 extern "C" {
101203 #endif
101204
101205
101206 /*
101207 ** Add the ability to override 'extern'
101208 */
101209 #ifndef SQLITE_EXTERN
101210 # define SQLITE_EXTERN extern
101211 #endif
101212
101213 /*
101214 ** Make sure these symbols where not defined by some previous header
101215 ** file.
101216 */
101217 #ifdef SQLITE_VERSION
101218 # undef SQLITE_VERSION
101219 #endif
101220 #ifdef SQLITE_VERSION_NUMBER
101221 # undef SQLITE_VERSION_NUMBER
101222 #endif
101223
101224 /*
101225 ** CAPI3REF: Compile-Time Library Version Numbers {F10010}
101226 **
101227 ** {F10011} The #define in the sqlite3.h header file named
101228 ** SQLITE_VERSION resolves to a string literal that identifies
101229 ** the version of the SQLite library in the format "X.Y.Z", where
101230 ** X is the major version number, Y is the minor version number and Z
101231 ** is the release number.  The X.Y.Z might be followed by "alpha" or "beta".
101232 ** {END} For example "3.1.1beta".
101233 **
101234 ** The X value is always 3 in SQLite.  The X value only changes when
101235 ** backwards compatibility is broken and we intend to never break
101236 ** backwards compatibility.  The Y value only changes when
101237 ** there are major feature enhancements that are forwards compatible
101238 ** but not backwards compatible.  The Z value is incremented with
101239 ** each release but resets back to 0 when Y is incremented.
101240 **
101241 ** {F10014} The SQLITE_VERSION_NUMBER #define resolves to an integer
101242 ** with the value  (X*1000000 + Y*1000 + Z) where X, Y, and Z are as
101243 ** with SQLITE_VERSION. {END} For example, for version "3.1.1beta", 
101244 ** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using 
101245 ** version 3.1.1 or greater at compile time, programs may use the test 
101246 ** (SQLITE_VERSION_NUMBER>=3001001).
101247 **
101248 ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
101249 */
101250 #define SQLITE_VERSION         "3.5.4"
101251 #define SQLITE_VERSION_NUMBER 3005004
101252
101253 /*
101254 ** CAPI3REF: Run-Time Library Version Numbers {F10020}
101255 **
101256 ** {F10021} The sqlite3_libversion_number() interface returns an integer
101257 ** equal to [SQLITE_VERSION_NUMBER].  {END} The value returned
101258 ** by this routine should only be different from the header values
101259 ** if the application is compiled using an sqlite3.h header from a
101260 ** different version of SQLite than library.  Cautious programmers might
101261 ** include a check in their application to verify that 
101262 ** sqlite3_libversion_number() always returns the value 
101263 ** [SQLITE_VERSION_NUMBER].
101264 **
101265 ** {F10022} The sqlite3_version[] string constant contains the text of the
101266 ** [SQLITE_VERSION] string. {F10023} The sqlite3_libversion() function returns
101267 ** a pointer to the sqlite3_version[] string constant. {END} The 
101268 ** sqlite3_libversion() function
101269 ** is provided for DLL users who can only access functions and not
101270 ** constants within the DLL.
101271 */
101272 SQLITE_EXTERN const char sqlite3_version[];
101273 const char *sqlite3_libversion(void);
101274 int sqlite3_libversion_number(void);
101275
101276 /*
101277 ** CAPI3REF: Test To See If The Library Is Threadsafe {F10100}
101278 **
101279 ** {F10101} The sqlite3_threadsafe() routine returns nonzero
101280 ** if SQLite was compiled with its mutexes enabled or zero if
101281 ** SQLite was compiled with mutexes disabled. {END}  If this
101282 ** routine returns false, then it is not safe for simultaneously
101283 ** running threads to both invoke SQLite interfaces.
101284 **
101285 ** Really all this routine does is return true if SQLite was
101286 ** compiled with the -DSQLITE_THREADSAFE=1 option and false if
101287 ** compiled with -DSQLITE_THREADSAFE=0.  If SQLite uses an
101288 ** application-defined mutex subsystem, malloc subsystem, collating
101289 ** sequence, VFS, SQL function, progress callback, commit hook,
101290 ** extension, or other accessories and these add-ons are not
101291 ** threadsafe, then clearly the combination will not be threadsafe
101292 ** either.  Hence, this routine never reports that the library
101293 ** is guaranteed to be threadsafe, only when it is guaranteed not
101294 ** to be.
101295 */
101296 int sqlite3_threadsafe(void);
101297
101298 /*
101299 ** CAPI3REF: Database Connection Handle {F12000}
101300 **
101301 ** Each open SQLite database is represented by pointer to an instance of the
101302 ** opaque structure named "sqlite3".  It is useful to think of an sqlite3
101303 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
101304 ** [sqlite3_open_v2()] interfaces are its constructors
101305 ** and [sqlite3_close()] is its destructor.  There are many other interfaces
101306 ** (such as [sqlite3_prepare_v2()], [sqlite3_create_function()], and
101307 ** [sqlite3_busy_timeout()] to name but three) that are methods on this
101308 ** object.
101309 */
101310 typedef struct sqlite3 sqlite3;
101311
101312
101313 /*
101314 ** CAPI3REF: 64-Bit Integer Types {F10200}
101315 **
101316 ** Because there is no cross-platform way to specify such types
101317 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
101318 ** {F10201} The sqlite_int64 and sqlite3_int64 types specify a
101319 ** 64-bit signed integer. {F10202} The sqlite_uint64 and
101320 ** sqlite3_uint64 types specify a 64-bit unsigned integer. {END}
101321 **
101322 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type
101323 ** definitions.  The sqlite_int64 and sqlite_uint64 types are
101324 ** supported for backwards compatibility only.
101325 */
101326 #ifdef SQLITE_INT64_TYPE
101327   typedef SQLITE_INT64_TYPE sqlite_int64;
101328   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
101329 #elif defined(_MSC_VER) || defined(__BORLANDC__)
101330   typedef __int64 sqlite_int64;
101331   typedef unsigned __int64 sqlite_uint64;
101332 #else
101333   typedef long long int sqlite_int64;
101334   typedef unsigned long long int sqlite_uint64;
101335 #endif
101336 typedef sqlite_int64 sqlite3_int64;
101337 typedef sqlite_uint64 sqlite3_uint64;
101338
101339 /*
101340 ** If compiling for a processor that lacks floating point support,
101341 ** substitute integer for floating-point
101342 */
101343 #ifdef SQLITE_OMIT_FLOATING_POINT
101344 # define double sqlite3_int64
101345 #endif
101346
101347 /*
101348 ** CAPI3REF: Closing A Database Connection {F12010}
101349 **
101350 ** {F12011} The sqlite3_close() interfaces destroys an [sqlite3] object
101351 ** allocated by a prior call to [sqlite3_open()], [sqlite3_open16()], or
101352 ** [sqlite3_open_v2()]. {F12012} Sqlite3_close() releases all
101353 ** memory used by the connection and closes all open files. {END}.
101354 **
101355 ** {F12013} If the database connection contains
101356 ** [sqlite3_stmt | prepared statements] that have not been finalized
101357 ** by [sqlite3_finalize()], then sqlite3_close() returns SQLITE_BUSY
101358 ** and leaves the connection open.  {F12014} Giving sqlite3_close()
101359 ** a NULL pointer is a harmless no-op. {END}
101360 **
101361 ** {U12015} Passing this routine a database connection that has already been
101362 ** closed results in undefined behavior. {U12016} If other interfaces that
101363 ** reference the same database connection are pending (either in the
101364 ** same thread or in different threads) when this routine is called,
101365 ** then the behavior is undefined and is almost certainly undesirable.
101366 */
101367 int sqlite3_close(sqlite3 *);
101368
101369 /*
101370 ** The type for a callback function.
101371 ** This is legacy and deprecated.  It is included for historical
101372 ** compatibility and is not documented.
101373 */
101374 typedef int (*sqlite3_callback)(void*,int,char**, char**);
101375
101376 /*
101377 ** CAPI3REF: One-Step Query Execution Interface {F12100}
101378 **
101379 ** {F12101} The sqlite3_exec() interface evaluates zero or more 
101380 ** UTF-8 encoded, semicolon-separated SQL statements in the zero-terminated
101381 ** string of its second argument.  {F12102} The SQL
101382 ** statements are evaluated in the context of the database connection
101383 ** specified by in the first argument.
101384 ** {F12103} SQL statements are prepared one by one using
101385 ** [sqlite3_prepare()] or the equivalent, evaluated
101386 ** using one or more calls to [sqlite3_step()], then destroyed
101387 ** using [sqlite3_finalize()]. {F12104} The return value of
101388 ** sqlite3_exec() is SQLITE_OK if all SQL statement run
101389 ** successfully.
101390 **
101391 ** {F12105} If one or more of the SQL statements handed to
101392 ** sqlite3_exec() are queries, then
101393 ** the callback function specified by the 3rd parameter is
101394 ** invoked once for each row of the query result. {F12106}
101395 ** If the callback returns a non-zero value then the query
101396 ** is aborted, all subsequent SQL statements
101397 ** are skipped and the sqlite3_exec() function returns the [SQLITE_ABORT].
101398 **
101399 ** {F12107} The 4th parameter to sqlite3_exec() is an arbitrary pointer
101400 ** that is passed through to the callback function as its first parameter.
101401 **
101402 ** {F12108} The 2nd parameter to the callback function is the number of
101403 ** columns in the query result.  {F12109} The 3rd parameter to the callback
101404 ** is an array of pointers to strings holding the values for each column
101405 ** as extracted using [sqlite3_column_text()].  NULL values in the result
101406 ** set result in a NULL pointer.  All other value are in their UTF-8
101407 ** string representation. {F12117}
101408 ** The 4th parameter to the callback is an array of strings
101409 ** obtained using [sqlite3_column_name()] and holding
101410 ** the names of each column, also in UTF-8.
101411 **
101412 ** {F12110} The callback function may be NULL, even for queries.  A NULL
101413 ** callback is not an error.  It just means that no callback
101414 ** will be invoked. 
101415 **
101416 ** {F12112} If an error occurs while parsing or evaluating the SQL
101417 ** then an appropriate error message is written into memory obtained
101418 ** from [sqlite3_malloc()] and *errmsg is made to point to that message
101419 ** assuming errmsg is not NULL.  
101420 ** {U12113} The calling function is responsible for freeing the memory
101421 ** using [sqlite3_free()].
101422 ** {F12116} If [sqlite3_malloc()] fails while attempting to generate
101423 ** the error message, *errmsg is set to NULL.
101424 ** {F12114} If errmsg is NULL then no attempt is made to generate an
101425 ** error message. <todo>Is the return code SQLITE_NOMEM or the original
101426 ** error code?</todo> <todo>What happens if there are multiple errors?
101427 ** Do we get code for the first error, or is the choice of reported
101428 ** error arbitrary?</todo>
101429 **
101430 ** {F12115} The return value is is SQLITE_OK if there are no errors and
101431 ** some other [SQLITE_OK | return code] if there is an error.  
101432 ** The particular return value depends on the type of error.  {END}
101433 */
101434 int sqlite3_exec(
101435   sqlite3*,                                  /* An open database */
101436   const char *sql,                           /* SQL to be evaluted */
101437   int (*callback)(void*,int,char**,char**),  /* Callback function */
101438   void *,                                    /* 1st argument to callback */
101439   char **errmsg                              /* Error msg written here */
101440 );
101441
101442 /*
101443 ** CAPI3REF: Result Codes {F10210}
101444 ** KEYWORDS: SQLITE_OK
101445 **
101446 ** Many SQLite functions return an integer result code from the set shown
101447 ** above in order to indicates success or failure.
101448 **
101449 ** {F10211} The result codes shown here are the only ones returned 
101450 ** by SQLite in its default configuration. {F10212} However, the
101451 ** [sqlite3_extended_result_codes()] API can be used to set a database
101452 ** connectoin to return more detailed result codes. {END}
101453 **
101454 ** See also: [SQLITE_IOERR_READ | extended result codes]
101455 **
101456 */
101457 #define SQLITE_OK           0   /* Successful result */
101458 /* beginning-of-error-codes */
101459 #define SQLITE_ERROR        1   /* SQL error or missing database */
101460 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
101461 #define SQLITE_PERM         3   /* Access permission denied */
101462 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
101463 #define SQLITE_BUSY         5   /* The database file is locked */
101464 #define SQLITE_LOCKED       6   /* A table in the database is locked */
101465 #define SQLITE_NOMEM        7   /* A malloc() failed */
101466 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
101467 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
101468 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
101469 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
101470 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
101471 #define SQLITE_FULL        13   /* Insertion failed because database is full */
101472 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
101473 #define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
101474 #define SQLITE_EMPTY       16   /* Database is empty */
101475 #define SQLITE_SCHEMA      17   /* The database schema changed */
101476 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
101477 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
101478 #define SQLITE_MISMATCH    20   /* Data type mismatch */
101479 #define SQLITE_MISUSE      21   /* Library used incorrectly */
101480 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
101481 #define SQLITE_AUTH        23   /* Authorization denied */
101482 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
101483 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
101484 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
101485 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
101486 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
101487 /* end-of-error-codes */
101488
101489 /*
101490 ** CAPI3REF: Extended Result Codes {F10220}
101491 **
101492 ** In its default configuration, SQLite API routines return one of 26 integer
101493 ** [SQLITE_OK | result codes].  However, experience has shown that
101494 ** many of these result codes are too course-grained.  They do not provide as
101495 ** much information about problems as programmers might like.  In an effort to
101496 ** address this, newer versions of SQLite (version 3.3.8 and later) include
101497 ** support for additional result codes that provide more detailed information
101498 ** about errors. {F10221} The extended result codes are enabled or disabled
101499 ** for each database connection using the [sqlite3_extended_result_codes()]
101500 ** API. {END}
101501 ** 
101502 ** Some of the available extended result codes are listed above.
101503 ** We expect the number of extended result codes will be expand
101504 ** over time.  {U10422} Software that uses extended result codes should expect
101505 ** to see new result codes in future releases of SQLite. {END}
101506 ** 
101507 ** {F10223} The symbolic name for an extended result code always contains
101508 ** a related primary result code as a prefix. {F10224} Primary result
101509 ** codes contain a single "_" character.  {F10225} Extended result codes
101510 ** contain two or more "_" characters. {F10226} The numeric value of an
101511 ** extended result code can be converted to its
101512 ** corresponding primary result code by masking off the lower 8 bytes. {END}
101513 **
101514 ** The SQLITE_OK result code will never be extended.  It will always
101515 ** be exactly zero.
101516 */
101517 #define SQLITE_IOERR_READ          (SQLITE_IOERR | (1<<8))
101518 #define SQLITE_IOERR_SHORT_READ    (SQLITE_IOERR | (2<<8))
101519 #define SQLITE_IOERR_WRITE         (SQLITE_IOERR | (3<<8))
101520 #define SQLITE_IOERR_FSYNC         (SQLITE_IOERR | (4<<8))
101521 #define SQLITE_IOERR_DIR_FSYNC     (SQLITE_IOERR | (5<<8))
101522 #define SQLITE_IOERR_TRUNCATE      (SQLITE_IOERR | (6<<8))
101523 #define SQLITE_IOERR_FSTAT         (SQLITE_IOERR | (7<<8))
101524 #define SQLITE_IOERR_UNLOCK        (SQLITE_IOERR | (8<<8))
101525 #define SQLITE_IOERR_RDLOCK        (SQLITE_IOERR | (9<<8))
101526 #define SQLITE_IOERR_DELETE        (SQLITE_IOERR | (10<<8))
101527 #define SQLITE_IOERR_BLOCKED       (SQLITE_IOERR | (11<<8))
101528 #define SQLITE_IOERR_NOMEM         (SQLITE_IOERR | (12<<8))
101529
101530 /*
101531 ** CAPI3REF: Flags For File Open Operations {F10230}
101532 **
101533 ** {F10231} Some combination of the these bit values are used as the
101534 ** third argument to the [sqlite3_open_v2()] interface and
101535 ** as fourth argument to the xOpen method of the
101536 ** [sqlite3_vfs] object.
101537 */
101538 #define SQLITE_OPEN_READONLY         0x00000001
101539 #define SQLITE_OPEN_READWRITE        0x00000002
101540 #define SQLITE_OPEN_CREATE           0x00000004
101541 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008
101542 #define SQLITE_OPEN_EXCLUSIVE        0x00000010
101543 #define SQLITE_OPEN_MAIN_DB          0x00000100
101544 #define SQLITE_OPEN_TEMP_DB          0x00000200
101545 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400
101546 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800
101547 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000
101548 #define SQLITE_OPEN_SUBJOURNAL       0x00002000
101549 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000
101550
101551 /*
101552 ** CAPI3REF: Device Characteristics {F10240}
101553 **
101554 ** {F10241} The xDeviceCapabilities method of the [sqlite3_io_methods]
101555 ** object returns an integer which is a vector of the these
101556 ** bit values expressing I/O characteristics of the mass storage
101557 ** device that holds the file that the [sqlite3_io_methods]
101558 ** refers to. {END}
101559 **
101560 ** {F10242} The SQLITE_IOCAP_ATOMIC property means that all writes of
101561 ** any size are atomic.  {F10243} The SQLITE_IOCAP_ATOMICnnn values
101562 ** mean that writes of blocks that are nnn bytes in size and
101563 ** are aligned to an address which is an integer multiple of
101564 ** nnn are atomic.  {F10244} The SQLITE_IOCAP_SAFE_APPEND value means
101565 ** that when data is appended to a file, the data is appended
101566 ** first then the size of the file is extended, never the other
101567 ** way around.  {F10245} The SQLITE_IOCAP_SEQUENTIAL property means that
101568 ** information is written to disk in the same order as calls
101569 ** to xWrite().
101570 */
101571 #define SQLITE_IOCAP_ATOMIC          0x00000001
101572 #define SQLITE_IOCAP_ATOMIC512       0x00000002
101573 #define SQLITE_IOCAP_ATOMIC1K        0x00000004
101574 #define SQLITE_IOCAP_ATOMIC2K        0x00000008
101575 #define SQLITE_IOCAP_ATOMIC4K        0x00000010
101576 #define SQLITE_IOCAP_ATOMIC8K        0x00000020
101577 #define SQLITE_IOCAP_ATOMIC16K       0x00000040
101578 #define SQLITE_IOCAP_ATOMIC32K       0x00000080
101579 #define SQLITE_IOCAP_ATOMIC64K       0x00000100
101580 #define SQLITE_IOCAP_SAFE_APPEND     0x00000200
101581 #define SQLITE_IOCAP_SEQUENTIAL      0x00000400
101582
101583 /*
101584 ** CAPI3REF: File Locking Levels {F10250}
101585 **
101586 ** {F10251} SQLite uses one of the following integer values as the second
101587 ** argument to calls it makes to the xLock() and xUnlock() methods
101588 ** of an [sqlite3_io_methods] object. {END}
101589 */
101590 #define SQLITE_LOCK_NONE          0
101591 #define SQLITE_LOCK_SHARED        1
101592 #define SQLITE_LOCK_RESERVED      2
101593 #define SQLITE_LOCK_PENDING       3
101594 #define SQLITE_LOCK_EXCLUSIVE     4
101595
101596 /*
101597 ** CAPI3REF: Synchronization Type Flags {F10260}
101598 **
101599 ** {F10261} When SQLite invokes the xSync() method of an
101600 ** [sqlite3_io_methods] object it uses a combination of the
101601 ** these integer values as the second argument.
101602 **
101603 ** {F10262} When the SQLITE_SYNC_DATAONLY flag is used, it means that the
101604 ** sync operation only needs to flush data to mass storage.  Inode
101605 ** information need not be flushed. {F10263} The SQLITE_SYNC_NORMAL means 
101606 ** to use normal fsync() semantics. {F10264} The SQLITE_SYNC_FULL flag means 
101607 ** to use Mac OS-X style fullsync instead of fsync().
101608 */
101609 #define SQLITE_SYNC_NORMAL        0x00002
101610 #define SQLITE_SYNC_FULL          0x00003
101611 #define SQLITE_SYNC_DATAONLY      0x00010
101612
101613
101614 /*
101615 ** CAPI3REF: OS Interface Open File Handle {F11110}
101616 **
101617 ** An [sqlite3_file] object represents an open file in the OS
101618 ** interface layer.  Individual OS interface implementations will
101619 ** want to subclass this object by appending additional fields
101620 ** for their own use.  The pMethods entry is a pointer to an
101621 ** [sqlite3_io_methods] object that defines methods for performing
101622 ** I/O operations on the open file.
101623 */
101624 typedef struct sqlite3_file sqlite3_file;
101625 struct sqlite3_file {
101626   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
101627 };
101628
101629 /*
101630 ** CAPI3REF: OS Interface File Virtual Methods Object {F11120}
101631 **
101632 ** Every file opened by the [sqlite3_vfs] xOpen method contains a pointer to
101633 ** an instance of the this object.  This object defines the
101634 ** methods used to perform various operations against the open file.
101635 **
101636 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
101637 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
101638 *  The second choice is an
101639 ** OS-X style fullsync.  The SQLITE_SYNC_DATA flag may be ORed in to
101640 ** indicate that only the data of the file and not its inode needs to be
101641 ** synced.
101642 ** 
101643 ** The integer values to xLock() and xUnlock() are one of
101644 ** <ul>
101645 ** <li> [SQLITE_LOCK_NONE],
101646 ** <li> [SQLITE_LOCK_SHARED],
101647 ** <li> [SQLITE_LOCK_RESERVED],
101648 ** <li> [SQLITE_LOCK_PENDING], or
101649 ** <li> [SQLITE_LOCK_EXCLUSIVE].
101650 ** </ul>
101651 ** xLock() increases the lock. xUnlock() decreases the lock.  
101652 ** The xCheckReservedLock() method looks
101653 ** to see if any database connection, either in this
101654 ** process or in some other process, is holding an RESERVED,
101655 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
101656 ** if such a lock exists and false if not.
101657 ** 
101658 ** The xFileControl() method is a generic interface that allows custom
101659 ** VFS implementations to directly control an open file using the
101660 ** [sqlite3_file_control()] interface.  The second "op" argument
101661 ** is an integer opcode.   The third
101662 ** argument is a generic pointer which is intended to be a pointer
101663 ** to a structure that may contain arguments or space in which to
101664 ** write return values.  Potential uses for xFileControl() might be
101665 ** functions to enable blocking locks with timeouts, to change the
101666 ** locking strategy (for example to use dot-file locks), to inquire
101667 ** about the status of a lock, or to break stale locks.  The SQLite
101668 ** core reserves opcodes less than 100 for its own use. 
101669 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
101670 ** Applications that define a custom xFileControl method should use opcodes 
101671 ** greater than 100 to avoid conflicts.
101672 **
101673 ** The xSectorSize() method returns the sector size of the
101674 ** device that underlies the file.  The sector size is the
101675 ** minimum write that can be performed without disturbing
101676 ** other bytes in the file.  The xDeviceCharacteristics()
101677 ** method returns a bit vector describing behaviors of the
101678 ** underlying device:
101679 **
101680 ** <ul>
101681 ** <li> [SQLITE_IOCAP_ATOMIC]
101682 ** <li> [SQLITE_IOCAP_ATOMIC512]
101683 ** <li> [SQLITE_IOCAP_ATOMIC1K]
101684 ** <li> [SQLITE_IOCAP_ATOMIC2K]
101685 ** <li> [SQLITE_IOCAP_ATOMIC4K]
101686 ** <li> [SQLITE_IOCAP_ATOMIC8K]
101687 ** <li> [SQLITE_IOCAP_ATOMIC16K]
101688 ** <li> [SQLITE_IOCAP_ATOMIC32K]
101689 ** <li> [SQLITE_IOCAP_ATOMIC64K]
101690 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
101691 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
101692 ** </ul>
101693 **
101694 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
101695 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
101696 ** mean that writes of blocks that are nnn bytes in size and
101697 ** are aligned to an address which is an integer multiple of
101698 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
101699 ** that when data is appended to a file, the data is appended
101700 ** first then the size of the file is extended, never the other
101701 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
101702 ** information is written to disk in the same order as calls
101703 ** to xWrite().
101704 */
101705 typedef struct sqlite3_io_methods sqlite3_io_methods;
101706 struct sqlite3_io_methods {
101707   int iVersion;
101708   int (*xClose)(sqlite3_file*);
101709   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
101710   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
101711   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
101712   int (*xSync)(sqlite3_file*, int flags);
101713   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
101714   int (*xLock)(sqlite3_file*, int);
101715   int (*xUnlock)(sqlite3_file*, int);
101716   int (*xCheckReservedLock)(sqlite3_file*);
101717   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
101718   int (*xSectorSize)(sqlite3_file*);
101719   int (*xDeviceCharacteristics)(sqlite3_file*);
101720   /* Additional methods may be added in future releases */
101721 };
101722
101723 /*
101724 ** CAPI3REF: Standard File Control Opcodes {F11310}
101725 **
101726 ** These integer constants are opcodes for the xFileControl method
101727 ** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()]
101728 ** interface.
101729 **
101730 ** {F11311} The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
101731 ** opcode cases the xFileControl method to write the current state of
101732 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
101733 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
101734 ** into an integer that the pArg argument points to. {F11312} This capability
101735 ** is used during testing and only needs to be supported when SQLITE_TEST
101736 ** is defined.
101737 */
101738 #define SQLITE_FCNTL_LOCKSTATE        1
101739
101740 /*
101741 ** CAPI3REF: Mutex Handle {F17110}
101742 **
101743 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
101744 ** abstract type for a mutex object.  {F17111} The SQLite core never looks
101745 ** at the internal representation of an [sqlite3_mutex]. {END} It only
101746 ** deals with pointers to the [sqlite3_mutex] object.
101747 **
101748 ** Mutexes are created using [sqlite3_mutex_alloc()].
101749 */
101750 typedef struct sqlite3_mutex sqlite3_mutex;
101751
101752 /*
101753 ** CAPI3REF: OS Interface Object {F11140}
101754 **
101755 ** An instance of this object defines the interface between the
101756 ** SQLite core and the underlying operating system.  The "vfs"
101757 ** in the name of the object stands for "virtual file system".
101758 **
101759 ** The iVersion field is initially 1 but may be larger for future
101760 ** versions of SQLite.  Additional fields may be appended to this
101761 ** object when the iVersion value is increased.
101762 **
101763 ** The szOsFile field is the size of the subclassed [sqlite3_file]
101764 ** structure used by this VFS.  mxPathname is the maximum length of
101765 ** a pathname in this VFS.
101766 **
101767 ** Registered vfs modules are kept on a linked list formed by
101768 ** the pNext pointer.  The [sqlite3_vfs_register()]
101769 ** and [sqlite3_vfs_unregister()] interfaces manage this list
101770 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
101771 ** searches the list.
101772 **
101773 ** The pNext field is the only fields in the sqlite3_vfs 
101774 ** structure that SQLite will ever modify.  SQLite will only access
101775 ** or modify this field while holding a particular static mutex.
101776 ** The application should never modify anything within the sqlite3_vfs
101777 ** object once the object has been registered.
101778 **
101779 ** The zName field holds the name of the VFS module.  The name must
101780 ** be unique across all VFS modules.
101781 **
101782 ** {F11141} SQLite will guarantee that the zFilename string passed to
101783 ** xOpen() is a full pathname as generated by xFullPathname() and
101784 ** that the string will be valid and unchanged until xClose() is
101785 ** called.  {END} So the [sqlite3_file] can store a pointer to the
101786 ** filename if it needs to remember the filename for some reason.
101787 **
101788 ** {F11142} The flags argument to xOpen() includes all bits set in
101789 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
101790 ** or [sqlite3_open16()] is used, then flags includes at least
101791 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END}
101792 ** If xOpen() opens a file read-only then it sets *pOutFlags to
101793 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be
101794 ** set.
101795 ** 
101796 ** {F11143} SQLite will also add one of the following flags to the xOpen()
101797 ** call, depending on the object being opened:
101798 ** 
101799 ** <ul>
101800 ** <li>  [SQLITE_OPEN_MAIN_DB]
101801 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
101802 ** <li>  [SQLITE_OPEN_TEMP_DB]
101803 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
101804 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
101805 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
101806 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
101807 ** </ul> {END}
101808 **
101809 ** The file I/O implementation can use the object type flags to
101810 ** changes the way it deals with files.  For example, an application
101811 ** that does not care about crash recovery or rollback, might make
101812 ** the open of a journal file a no-op.  Writes to this journal are
101813 ** also a no-op.  Any attempt to read the journal return SQLITE_IOERR.
101814 ** Or the implementation might recognize the a database file will
101815 ** be doing page-aligned sector reads and writes in a random order
101816 ** and set up its I/O subsystem accordingly.
101817 ** 
101818 ** {F11144} SQLite might also add one of the following flags to the xOpen
101819 ** method:
101820 ** 
101821 ** <ul>
101822 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
101823 ** <li> [SQLITE_OPEN_EXCLUSIVE]
101824 ** </ul>
101825 ** 
101826 ** {F11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
101827 ** deleted when it is closed.  {F11146} The [SQLITE_OPEN_DELETEONCLOSE]
101828 ** will be set for TEMP  databases, journals and for subjournals. 
101829 ** {F11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened
101830 ** for exclusive access.  This flag is set for all files except
101831 ** for the main database file. {END}
101832 ** 
101833 ** {F11148} At least szOsFile bytes of memory is allocated by SQLite 
101834 ** to hold the  [sqlite3_file] structure passed as the third 
101835 ** argument to xOpen.  {END}  The xOpen method does not have to
101836 ** allocate the structure; it should just fill it in.
101837 ** 
101838 ** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] 
101839 ** to test for the existance of a file,
101840 ** or [SQLITE_ACCESS_READWRITE] to test to see
101841 ** if a file is readable and writable, or [SQLITE_ACCESS_READ]
101842 ** to test to see if a file is at least readable.  {END} The file can be a 
101843 ** directory.
101844 ** 
101845 ** {F11150} SQLite will always allocate at least mxPathname+1 byte for
101846 ** the output buffers for xGetTempname and xFullPathname. {F11151} The exact
101847 ** size of the output buffer is also passed as a parameter to both 
101848 ** methods. {END} If the output buffer is not large enough, SQLITE_CANTOPEN
101849 ** should be returned. As this is handled as a fatal error by SQLite,
101850 ** vfs implementations should endeavor to prevent this by setting 
101851 ** mxPathname to a sufficiently large value.
101852 ** 
101853 ** The xRandomness(), xSleep(), and xCurrentTime() interfaces
101854 ** are not strictly a part of the filesystem, but they are
101855 ** included in the VFS structure for completeness.
101856 ** The xRandomness() function attempts to return nBytes bytes
101857 ** of good-quality randomness into zOut.  The return value is
101858 ** the actual number of bytes of randomness obtained.  The
101859 ** xSleep() method cause the calling thread to sleep for at
101860 ** least the number of microseconds given.  The xCurrentTime()
101861 ** method returns a Julian Day Number for the current date and
101862 ** time.
101863 */
101864 typedef struct sqlite3_vfs sqlite3_vfs;
101865 struct sqlite3_vfs {
101866   int iVersion;            /* Structure version number */
101867   int szOsFile;            /* Size of subclassed sqlite3_file */
101868   int mxPathname;          /* Maximum file pathname length */
101869   sqlite3_vfs *pNext;      /* Next registered VFS */
101870   const char *zName;       /* Name of this virtual file system */
101871   void *pAppData;          /* Pointer to application-specific data */
101872   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
101873                int flags, int *pOutFlags);
101874   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
101875   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags);
101876   int (*xGetTempname)(sqlite3_vfs*, int nOut, char *zOut);
101877   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
101878   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
101879   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
101880   void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol);
101881   void (*xDlClose)(sqlite3_vfs*, void*);
101882   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
101883   int (*xSleep)(sqlite3_vfs*, int microseconds);
101884   int (*xCurrentTime)(sqlite3_vfs*, double*);
101885   /* New fields may be appended in figure versions.  The iVersion
101886   ** value will increment whenever this happens. */
101887 };
101888
101889 /*
101890 ** CAPI3REF: Flags for the xAccess VFS method {F11190}
101891 **
101892 ** {F11191} These integer constants can be used as the third parameter to
101893 ** the xAccess method of an [sqlite3_vfs] object. {END}  They determine
101894 ** the kind of what kind of permissions the xAccess method is
101895 ** looking for.  {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method
101896 ** simply checks to see if the file exists. {F11193} With
101897 ** SQLITE_ACCESS_READWRITE, the xAccess method checks to see
101898 ** if the file is both readable and writable.  {F11194} With
101899 ** SQLITE_ACCESS_READ the xAccess method
101900 ** checks to see if the file is readable.
101901 */
101902 #define SQLITE_ACCESS_EXISTS    0
101903 #define SQLITE_ACCESS_READWRITE 1
101904 #define SQLITE_ACCESS_READ      2
101905
101906 /*
101907 ** CAPI3REF: Enable Or Disable Extended Result Codes {F12200}
101908 **
101909 ** {F12201} The sqlite3_extended_result_codes() routine enables or disables the
101910 ** [SQLITE_IOERR_READ | extended result codes] feature on a database
101911 ** connection if its 2nd parameter is
101912 ** non-zero or zero, respectively. {F12202}
101913 ** By default, SQLite API routines return one of only 26 integer
101914 ** [SQLITE_OK | result codes].  {F12203} When extended result codes
101915 ** are enabled by this routine, the repetoire of result codes can be
101916 ** much larger and can (hopefully) provide more detailed information
101917 ** about the cause of an error.
101918 **
101919 ** {F12204} The second argument is a boolean value that turns extended result
101920 ** codes on and off. {F12205} Extended result codes are off by default for
101921 ** backwards compatibility with older versions of SQLite.
101922 */
101923 int sqlite3_extended_result_codes(sqlite3*, int onoff);
101924
101925 /*
101926 ** CAPI3REF: Last Insert Rowid {F12220}
101927 **
101928 ** {F12221} Each entry in an SQLite table has a unique 64-bit signed
101929 ** integer key called the "rowid".  {F12222} The rowid is always available
101930 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
101931 ** names are not also used by explicitly declared columns. {F12223} If
101932 ** the table has a column of type INTEGER PRIMARY KEY then that column
101933 ** is another an alias for the rowid.
101934 **
101935 ** {F12224} This routine returns the rowid of the most recent
101936 ** successful INSERT into the database from the database connection
101937 ** shown in the first argument.  {F12225} If no successful inserts
101938 ** have ever occurred on this database connection, zero is returned.
101939 **
101940 ** {F12226} If an INSERT occurs within a trigger, then the rowid of the
101941 ** inserted row is returned by this routine as long as the trigger
101942 ** is running.  {F12227} But once the trigger terminates, the value returned
101943 ** by this routine reverts to the last value inserted before the
101944 ** trigger fired.
101945 **
101946 ** {F12228} An INSERT that fails due to a constraint violation is not a
101947 ** successful insert and does not change the value returned by this
101948 ** routine.  {F12229} Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
101949 ** and INSERT OR ABORT make no changes to the return value of this
101950 ** routine when their insertion fails.  {F12231} When INSERT OR REPLACE 
101951 ** encounters a constraint violation, it does not fail.  The
101952 ** INSERT continues to completion after deleting rows that caused
101953 ** the constraint problem so INSERT OR REPLACE will always change
101954 ** the return value of this interface. 
101955 **
101956 ** {UF12232} If another thread does a new insert on the same database connection
101957 ** while this routine is running and thus changes the last insert rowid,
101958 ** then the return value of this routine is undefined.
101959 */
101960 sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
101961
101962 /*
101963 ** CAPI3REF: Count The Number Of Rows Modified {F12240}
101964 **
101965 ** {F12241} This function returns the number of database rows that were changed
101966 ** or inserted or deleted by the most recently completed SQL statement
101967 ** on the connection specified by the first parameter. {F12242} Only
101968 ** changes that are directly specified by the INSERT, UPDATE, or
101969 ** DELETE statement are counted.  Auxiliary changes caused by
101970 ** triggers are not counted. {F12243} Use the [sqlite3_total_changes()] function
101971 ** to find the total number of changes including changes caused by triggers.
101972 **
101973 ** {F12244} Within the body of a trigger, the sqlite3_changes() interface
101974 ** can be called to find the number of
101975 ** changes in the most recently completed INSERT, UPDATE, or DELETE
101976 ** statement within the body of the same trigger.
101977 **
101978 ** {F12245} All changes are counted, even if they are later undone by a
101979 ** ROLLBACK or ABORT.  {F12246} Except, changes associated with creating and
101980 ** dropping tables are not counted.
101981 **
101982 ** {F12247} If a callback invokes [sqlite3_exec()] or [sqlite3_step()]
101983 ** recursively, then the changes in the inner, recursive call are
101984 ** counted together with the changes in the outer call.
101985 **
101986 ** {F12248} SQLite implements the command "DELETE FROM table" without
101987 ** a WHERE clause by dropping and recreating the table.  (This is much
101988 ** faster than going through and deleting individual elements from the
101989 ** table.)  Because of this optimization, the change count for 
101990 ** "DELETE FROM table" will be zero regardless of the number of elements
101991 ** that were originally in the table. {F12251} To get an accurate count
101992 ** of the number of rows deleted, use
101993 ** "DELETE FROM table WHERE 1" instead.
101994 **
101995 ** {UF12252} If another thread makes changes on the same database connection
101996 ** while this routine is running then the return value of this routine
101997 ** is undefined.
101998 */
101999 int sqlite3_changes(sqlite3*);
102000
102001 /*
102002 ** CAPI3REF: Total Number Of Rows Modified {F12260}
102003 ***
102004 ** {F12261} This function returns the number of database rows that have been
102005 ** modified by INSERT, UPDATE or DELETE statements since the database handle
102006 ** was opened. {F12262} The count includes UPDATE, INSERT and DELETE 
102007 ** statements executed as part of trigger programs.  {F12263} All changes
102008 ** are counted as soon as the statement that makes them is completed 
102009 ** (when the statement handle is passed to [sqlite3_reset()] or 
102010 ** [sqlite3_finalize()]). {END}
102011 **
102012 ** See also the [sqlite3_change()] interface.
102013 **
102014 ** {F12265} SQLite implements the command "DELETE FROM table" without
102015 ** a WHERE clause by dropping and recreating the table.  (This is much
102016 ** faster than going
102017 ** through and deleting individual elements form the table.)  Because of
102018 ** this optimization, the change count for "DELETE FROM table" will be
102019 ** zero regardless of the number of elements that were originally in the
102020 ** table. To get an accurate count of the number of rows deleted, use
102021 ** "DELETE FROM table WHERE 1" instead.
102022 **
102023 ** {U12264} If another thread makes changes on the same database connection
102024 ** while this routine is running then the return value of this routine
102025 ** is undefined. {END}
102026 */
102027 int sqlite3_total_changes(sqlite3*);
102028
102029 /*
102030 ** CAPI3REF: Interrupt A Long-Running Query {F12270}
102031 **
102032 ** {F12271} This function causes any pending database operation to abort and
102033 ** return at its earliest opportunity. {END} This routine is typically
102034 ** called in response to a user action such as pressing "Cancel"
102035 ** or Ctrl-C where the user wants a long query operation to halt
102036 ** immediately.
102037 **
102038 ** {F12272} It is safe to call this routine from a thread different from the
102039 ** thread that is currently running the database operation. {U12273} But it
102040 ** is not safe to call this routine with a database connection that
102041 ** is closed or might close before sqlite3_interrupt() returns.
102042 **
102043 ** If an SQL is very nearly finished at the time when sqlite3_interrupt()
102044 ** is called, then it might not have an opportunity to be interrupted.
102045 ** It might continue to completion.
102046 ** {F12274} The SQL operation that is interrupted will return
102047 ** [SQLITE_INTERRUPT].  {F12275} If the interrupted SQL operation is an
102048 ** INSERT, UPDATE, or DELETE that is inside an explicit transaction, 
102049 ** then the entire transaction will be rolled back automatically.
102050 ** {F12276} A call to sqlite3_interrupt() has no effect on SQL statements
102051 ** that are started after sqlite3_interrupt() returns.
102052 */
102053 void sqlite3_interrupt(sqlite3*);
102054
102055 /*
102056 ** CAPI3REF: Determine If An SQL Statement Is Complete {F10510}
102057 **
102058 ** These routines are useful for command-line input to determine if the
102059 ** currently entered text seems to form complete a SQL statement or
102060 ** if additional input is needed before sending the text into
102061 ** SQLite for parsing.  These routines return true if the input string
102062 ** appears to be a complete SQL statement.  A statement is judged to be
102063 ** complete if it ends with a semicolon and is not a fragment of a
102064 ** CREATE TRIGGER statement.  These routines do not parse the SQL and
102065 ** so will not detect syntactically incorrect SQL.
102066 **
102067 ** {F10511} These functions return true if the given input string 
102068 ** ends with a semicolon optionally followed by whitespace or
102069 ** comments. {F10512} For sqlite3_complete(),
102070 ** the parameter must be a zero-terminated UTF-8 string. {F10513} For
102071 ** sqlite3_complete16(), a zero-terminated machine byte order UTF-16 string
102072 ** is required.  {F10514} These routines return false if the terminal
102073 ** semicolon is within a comment, a string literal or a quoted identifier
102074 ** (in other words if the final semicolon is not really a separate token
102075 ** but part of a larger token) or if the final semicolon is
102076 ** in between the BEGIN and END keywords of a CREATE TRIGGER statement.
102077 ** {END}
102078 */
102079 int sqlite3_complete(const char *sql);
102080 int sqlite3_complete16(const void *sql);
102081
102082 /*
102083 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310}
102084 **
102085 ** {F12311} This routine identifies a callback function that might be
102086 ** invoked whenever an attempt is made to open a database table 
102087 ** that another thread or process has locked.
102088 ** {F12312} If the busy callback is NULL, then [SQLITE_BUSY]
102089 ** or [SQLITE_IOERR_BLOCKED]
102090 ** is returned immediately upon encountering the lock.
102091 ** {F12313} If the busy callback is not NULL, then the
102092 ** callback will be invoked with two arguments.  {F12314} The
102093 ** first argument to the handler is a copy of the void* pointer which
102094 ** is the third argument to this routine.  {F12315} The second argument to
102095 ** the handler is the number of times that the busy handler has
102096 ** been invoked for this locking event.  {F12316} If the
102097 ** busy callback returns 0, then no additional attempts are made to
102098 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
102099 ** {F12317} If the callback returns non-zero, then another attempt
102100 ** is made to open the database for reading and the cycle repeats.
102101 **
102102 ** The presence of a busy handler does not guarantee that
102103 ** it will be invoked when there is lock contention. {F12319}
102104 ** If SQLite determines that invoking the busy handler could result in
102105 ** a deadlock, it will go ahead and return [SQLITE_BUSY] or
102106 ** [SQLITE_IOERR_BLOCKED] instead of invoking the
102107 ** busy handler. {END}
102108 ** Consider a scenario where one process is holding a read lock that
102109 ** it is trying to promote to a reserved lock and
102110 ** a second process is holding a reserved lock that it is trying
102111 ** to promote to an exclusive lock.  The first process cannot proceed
102112 ** because it is blocked by the second and the second process cannot
102113 ** proceed because it is blocked by the first.  If both processes
102114 ** invoke the busy handlers, neither will make any progress.  Therefore,
102115 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
102116 ** will induce the first process to release its read lock and allow
102117 ** the second process to proceed.
102118 **
102119 ** {F12321} The default busy callback is NULL. {END}
102120 **
102121 ** {F12322} The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
102122 ** when SQLite is in the middle of a large transaction where all the
102123 ** changes will not fit into the in-memory cache.  {F12323} SQLite will
102124 ** already hold a RESERVED lock on the database file, but it needs
102125 ** to promote this lock to EXCLUSIVE so that it can spill cache
102126 ** pages into the database file without harm to concurrent
102127 ** readers.  {F12324} If it is unable to promote the lock, then the in-memory
102128 ** cache will be left in an inconsistent state and so the error
102129 ** code is promoted from the relatively benign [SQLITE_BUSY] to
102130 ** the more severe [SQLITE_IOERR_BLOCKED].  {F12325} This error code promotion
102131 ** forces an automatic rollback of the changes. {END} See the
102132 ** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError">
102133 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
102134 ** this is important.
102135 **      
102136 ** {F12326} Sqlite is re-entrant, so the busy handler may start a new
102137 ** query. {END} (It is not clear why anyone would every want to do this,
102138 ** but it is allowed, in theory.) {U12327} But the busy handler may not
102139 ** close the database.  Closing the database from a busy handler will delete 
102140 ** data structures out from under the executing query and will 
102141 ** probably result in a segmentation fault or other runtime error. {END}
102142 **
102143 ** {F12328} There can only be a single busy handler defined for each database
102144 ** connection.  Setting a new busy handler clears any previous one. 
102145 ** {F12329} Note that calling [sqlite3_busy_timeout()] will also set or clear
102146 ** the busy handler.
102147 **
102148 ** {F12331} When operating in [sqlite3_enable_shared_cache | shared cache mode],
102149 ** only a single busy handler can be defined for each database file.
102150 ** So if two database connections share a single cache, then changing
102151 ** the busy handler on one connection will also change the busy
102152 ** handler in the other connection.  {F12332} The busy handler is invoked
102153 ** in the thread that was running when the lock contention occurs.
102154 */
102155 int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
102156
102157 /*
102158 ** CAPI3REF: Set A Busy Timeout {F12340}
102159 **
102160 ** {F12341} This routine sets a [sqlite3_busy_handler | busy handler]
102161 ** that sleeps for a while when a
102162 ** table is locked.  {F12342} The handler will sleep multiple times until 
102163 ** at least "ms" milliseconds of sleeping have been done. {F12343} After
102164 ** "ms" milliseconds of sleeping, the handler returns 0 which
102165 ** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
102166 **
102167 ** {F12344} Calling this routine with an argument less than or equal to zero
102168 ** turns off all busy handlers.
102169 **
102170 ** {F12345} There can only be a single busy handler for a particular database
102171 ** connection.  If another busy handler was defined  
102172 ** (using [sqlite3_busy_handler()]) prior to calling
102173 ** this routine, that other busy handler is cleared.
102174 */
102175 int sqlite3_busy_timeout(sqlite3*, int ms);
102176
102177 /*
102178 ** CAPI3REF: Convenience Routines For Running Queries {F12370}
102179 **
102180 ** This next routine is a convenience wrapper around [sqlite3_exec()].
102181 ** {F12371} Instead of invoking a user-supplied callback for each row of the
102182 ** result, this routine remembers each row of the result in memory
102183 ** obtained from [sqlite3_malloc()], then returns all of the result after the
102184 ** query has finished. {F12372}
102185 **
102186 ** As an example, suppose the query result where this table:
102187 **
102188 ** <blockquote><pre>
102189 **        Name        | Age
102190 **        -----------------------
102191 **        Alice       | 43
102192 **        Bob         | 28
102193 **        Cindy       | 21
102194 ** </pre></blockquote>
102195 **
102196 ** If the 3rd argument were &azResult then after the function returns
102197 ** azResult will contain the following data:
102198 **
102199 ** <blockquote><pre>
102200 **        azResult&#91;0] = "Name";
102201 **        azResult&#91;1] = "Age";
102202 **        azResult&#91;2] = "Alice";
102203 **        azResult&#91;3] = "43";
102204 **        azResult&#91;4] = "Bob";
102205 **        azResult&#91;5] = "28";
102206 **        azResult&#91;6] = "Cindy";
102207 **        azResult&#91;7] = "21";
102208 ** </pre></blockquote>
102209 **
102210 ** Notice that there is an extra row of data containing the column
102211 ** headers.  But the *nrow return value is still 3.  *ncolumn is
102212 ** set to 2.  In general, the number of values inserted into azResult
102213 ** will be ((*nrow) + 1)*(*ncolumn).
102214 **
102215 ** {U12374} After the calling function has finished using the result, it should 
102216 ** pass the result data pointer to sqlite3_free_table() in order to 
102217 ** release the memory that was malloc-ed.  Because of the way the 
102218 ** [sqlite3_malloc()] happens, the calling function must not try to call 
102219 ** [sqlite3_free()] directly.  Only [sqlite3_free_table()] is able to release 
102220 ** the memory properly and safely. {END}
102221 **
102222 ** {F12373} The return value of this routine is the same as
102223 ** from [sqlite3_exec()].
102224 */
102225 int sqlite3_get_table(
102226   sqlite3*,              /* An open database */
102227   const char *sql,       /* SQL to be executed */
102228   char ***resultp,       /* Result written to a char *[]  that this points to */
102229   int *nrow,             /* Number of result rows written here */
102230   int *ncolumn,          /* Number of result columns written here */
102231   char **errmsg          /* Error msg written here */
102232 );
102233 void sqlite3_free_table(char **result);
102234
102235 /*
102236 ** CAPI3REF: Formatted String Printing Functions {F17400}
102237 **
102238 ** These routines are workalikes of the "printf()" family of functions
102239 ** from the standard C library.
102240 **
102241 ** {F17401} The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
102242 ** results into memory obtained from [sqlite3_malloc()].
102243 ** {U17402} The strings returned by these two routines should be
102244 ** released by [sqlite3_free()]. {F17403}  Both routines return a
102245 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
102246 ** memory to hold the resulting string.
102247 **
102248 ** {F17404} In sqlite3_snprintf() routine is similar to "snprintf()" from
102249 ** the standard C library.  The result is written into the
102250 ** buffer supplied as the second parameter whose size is given by
102251 ** the first parameter. {END} Note that the order of the
102252 ** first two parameters is reversed from snprintf().  This is an
102253 ** historical accident that cannot be fixed without breaking
102254 ** backwards compatibility.  {F17405} Note also that sqlite3_snprintf()
102255 ** returns a pointer to its buffer instead of the number of
102256 ** characters actually written into the buffer. {END} We admit that
102257 ** the number of characters written would be a more useful return
102258 ** value but we cannot change the implementation of sqlite3_snprintf()
102259 ** now without breaking compatibility.
102260 **
102261 ** {F17406} As long as the buffer size is greater than zero, sqlite3_snprintf()
102262 ** guarantees that the buffer is always zero-terminated. {F17407} The first
102263 ** parameter "n" is the total size of the buffer, including space for
102264 ** the zero terminator.  {END} So the longest string that can be completely
102265 ** written will be n-1 characters.
102266 **
102267 ** These routines all implement some additional formatting
102268 ** options that are useful for constructing SQL statements.
102269 ** All of the usual printf formatting options apply.  In addition, there
102270 ** is are "%q", "%Q", and "%z" options.
102271 **
102272 ** {F17410} The %q option works like %s in that it substitutes a null-terminated
102273 ** string from the argument list.  But %q also doubles every '\'' character.
102274 ** %q is designed for use inside a string literal. {END} By doubling each '\''
102275 ** character it escapes that character and allows it to be inserted into
102276 ** the string.
102277 **
102278 ** For example, so some string variable contains text as follows:
102279 **
102280 ** <blockquote><pre>
102281 **  char *zText = "It's a happy day!";
102282 ** </pre></blockquote>
102283 **
102284 ** One can use this text in an SQL statement as follows:
102285 **
102286 ** <blockquote><pre>
102287 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
102288 **  sqlite3_exec(db, zSQL, 0, 0, 0);
102289 **  sqlite3_free(zSQL);
102290 ** </pre></blockquote>
102291 **
102292 ** Because the %q format string is used, the '\'' character in zText
102293 ** is escaped and the SQL generated is as follows:
102294 **
102295 ** <blockquote><pre>
102296 **  INSERT INTO table1 VALUES('It''s a happy day!')
102297 ** </pre></blockquote>
102298 **
102299 ** This is correct.  Had we used %s instead of %q, the generated SQL
102300 ** would have looked like this:
102301 **
102302 ** <blockquote><pre>
102303 **  INSERT INTO table1 VALUES('It's a happy day!');
102304 ** </pre></blockquote>
102305 **
102306 ** This second example is an SQL syntax error.  As a general rule you
102307 ** should always use %q instead of %s when inserting text into a string 
102308 ** literal.
102309 **
102310 ** {F17411} The %Q option works like %q except it also adds single quotes around
102311 ** the outside of the total string.  Or if the parameter in the argument
102312 ** list is a NULL pointer, %Q substitutes the text "NULL" (without single
102313 ** quotes) in place of the %Q option. {END}  So, for example, one could say:
102314 **
102315 ** <blockquote><pre>
102316 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
102317 **  sqlite3_exec(db, zSQL, 0, 0, 0);
102318 **  sqlite3_free(zSQL);
102319 ** </pre></blockquote>
102320 **
102321 ** The code above will render a correct SQL statement in the zSQL
102322 ** variable even if the zText variable is a NULL pointer.
102323 **
102324 ** {F17412} The "%z" formatting option works exactly like "%s" with the
102325 ** addition that after the string has been read and copied into
102326 ** the result, [sqlite3_free()] is called on the input string. {END}
102327 */
102328 char *sqlite3_mprintf(const char*,...);
102329 char *sqlite3_vmprintf(const char*, va_list);
102330 char *sqlite3_snprintf(int,char*,const char*, ...);
102331
102332 /*
102333 ** CAPI3REF: Memory Allocation Subsystem {F17300}
102334 **
102335 ** {F17301} The SQLite core  uses these three routines for all of its own
102336 ** internal memory allocation needs. {END}  "Core" in the previous sentence
102337 ** does not include operating-system specific VFS implementation.  The
102338 ** windows VFS uses native malloc and free for some operations.
102339 **
102340 ** {F17302} The sqlite3_malloc() routine returns a pointer to a block
102341 ** of memory at least N bytes in length, where N is the parameter.
102342 ** {F17303} If sqlite3_malloc() is unable to obtain sufficient free
102343 ** memory, it returns a NULL pointer.  {F17304} If the parameter N to
102344 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
102345 ** a NULL pointer.
102346 **
102347 ** {F17305} Calling sqlite3_free() with a pointer previously returned
102348 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
102349 ** that it might be reused.  {F17306} The sqlite3_free() routine is
102350 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
102351 ** to sqlite3_free() is harmless.  {U17307} After being freed, memory
102352 ** should neither be read nor written.  Even reading previously freed
102353 ** memory might result in a segmentation fault or other severe error.
102354 ** {U17309} Memory corruption, a segmentation fault, or other severe error
102355 ** might result if sqlite3_free() is called with a non-NULL pointer that
102356 ** was not obtained from sqlite3_malloc() or sqlite3_free().
102357 **
102358 ** {F17310} The sqlite3_realloc() interface attempts to resize a
102359 ** prior memory allocation to be at least N bytes, where N is the
102360 ** second parameter.  The memory allocation to be resized is the first
102361 ** parameter.  {F17311} If the first parameter to sqlite3_realloc()
102362 ** is a NULL pointer then its behavior is identical to calling
102363 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
102364 ** {F17312} If the second parameter to sqlite3_realloc() is zero or
102365 ** negative then the behavior is exactly the same as calling
102366 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
102367 ** {F17313} Sqlite3_realloc() returns a pointer to a memory allocation
102368 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
102369 ** {F17314} If M is the size of the prior allocation, then min(N,M) bytes
102370 ** of the prior allocation are copied into the beginning of buffer returned
102371 ** by sqlite3_realloc() and the prior allocation is freed.
102372 ** {F17315} If sqlite3_realloc() returns NULL, then the prior allocation
102373 ** is not freed.
102374 **
102375 ** {F17316} The memory returned by sqlite3_malloc() and sqlite3_realloc()
102376 ** is always aligned to at least an 8 byte boundary. {END}
102377 **
102378 ** {F17381} The default implementation
102379 ** of the memory allocation subsystem uses the malloc(), realloc()
102380 ** and free() provided by the standard C library. {F17382} However, if 
102381 ** SQLite is compiled with the following C preprocessor macro
102382 **
102383 ** <blockquote> SQLITE_MEMORY_SIZE=<i>NNN</i> </blockquote>
102384 **
102385 ** where <i>NNN</i> is an integer, then SQLite create a static
102386 ** array of at least <i>NNN</i> bytes in size and use that array
102387 ** for all of its dynamic memory allocation needs. {END}  Additional
102388 ** memory allocator options may be added in future releases.
102389 **
102390 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
102391 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
102392 ** implementation of these routines to be omitted.  That capability
102393 ** is no longer provided.  Only built-in memory allocators can be
102394 ** used.
102395 **
102396 ** The windows OS interface layer calls
102397 ** the system malloc() and free() directly when converting
102398 ** filenames between the UTF-8 encoding used by SQLite
102399 ** and whatever filename encoding is used by the particular windows
102400 ** installation.  Memory allocation errors are detected, but
102401 ** they are reported back as [SQLITE_CANTOPEN] or
102402 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
102403 */
102404 void *sqlite3_malloc(int);
102405 void *sqlite3_realloc(void*, int);
102406 void sqlite3_free(void*);
102407
102408 /*
102409 ** CAPI3REF: Memory Allocator Statistics {F17370}
102410 **
102411 ** In addition to the basic three allocation routines 
102412 ** [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()],
102413 ** the memory allocation subsystem included with the SQLite
102414 ** sources provides the interfaces shown here.
102415 **
102416 ** {F17371} The sqlite3_memory_used() routine returns the
102417 ** number of bytes of memory currently outstanding (malloced but not freed).
102418 ** {F17372} The value returned by sqlite3_memory_used() includes
102419 ** any overhead added by SQLite, but not overhead added by the
102420 ** library malloc() that backs the sqlite3_malloc() implementation.
102421 ** {F17373} The sqlite3_memory_highwater() routines returns the
102422 ** maximum number of bytes that have been outstanding at any time
102423 ** since the highwater mark was last reset.
102424 ** {F17374} The byte count returned by sqlite3_memory_highwater()
102425 ** uses the same byte counting rules as sqlite3_memory_used(). {END}
102426 ** In other words, overhead added internally by SQLite is counted,
102427 ** but overhead from the underlying system malloc is not.
102428 ** {F17375} If the parameter to sqlite3_memory_highwater() is true,
102429 ** then the highwater mark is reset to the current value of
102430 ** sqlite3_memory_used() and the prior highwater mark (before the
102431 ** reset) is returned.  {F17376}  If the parameter to 
102432 ** sqlite3_memory_highwater() is zero, then the highwater mark is
102433 ** unchanged.
102434 */
102435 sqlite3_int64 sqlite3_memory_used(void);
102436 sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
102437
102438 /*
102439 ** CAPI3REF: Compile-Time Authorization Callbacks {F12500}
102440 **
102441 ** {F12501} This routine registers a authorizer callback with a particular
102442 ** database connection, supplied in the first argument. {F12502}
102443 ** The authorizer callback is invoked as SQL statements are being compiled
102444 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
102445 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  {F12503} At various
102446 ** points during the compilation process, as logic is being created
102447 ** to perform various actions, the authorizer callback is invoked to
102448 ** see if those actions are allowed.  The authorizer callback should
102449 ** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the
102450 ** specific action but allow the SQL statement to continue to be
102451 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
102452 ** rejected with an error.  {F12504} If the authorizer callback returns
102453 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
102454 ** then [sqlite3_prepare_v2()] or equivalent call that triggered
102455 ** the authorizer shall
102456 ** fail with an SQLITE_ERROR error code and an appropriate error message. {END}
102457 **
102458 ** When the callback returns [SQLITE_OK], that means the operation
102459 ** requested is ok.  {F12505} When the callback returns [SQLITE_DENY], the
102460 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
102461 ** authorizer shall fail
102462 ** with an SQLITE_ERROR error code and an error message explaining that
102463 ** access is denied. {F12506} If the authorizer code (the 2nd parameter
102464 ** to the authorizer callback is anything other than [SQLITE_READ], then
102465 ** a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. 
102466 ** If the authorizer code is [SQLITE_READ] and the callback returns
102467 ** [SQLITE_IGNORE] then the prepared statement is constructed to
102468 ** insert a NULL value in place of the table column that would have
102469 ** been read if [SQLITE_OK] had been returned. {END}
102470 **
102471 ** {F12510} The first parameter to the authorizer callback is a copy of
102472 ** the third parameter to the sqlite3_set_authorizer() interface.
102473 ** {F12511} The second parameter to the callback is an integer 
102474 ** [SQLITE_COPY | action code] that specifies the particular action
102475 ** to be authorized. {END} The available action codes are
102476 ** [SQLITE_COPY | documented separately].  {F12512} The third through sixth
102477 ** parameters to the callback are zero-terminated strings that contain 
102478 ** additional details about the action to be authorized. {END}
102479 **
102480 ** An authorizer is used when preparing SQL statements from an untrusted
102481 ** source, to ensure that the SQL statements do not try to access data
102482 ** that they are not allowed to see, or that they do not try to
102483 ** execute malicious statements that damage the database.  For
102484 ** example, an application may allow a user to enter arbitrary
102485 ** SQL queries for evaluation by a database.  But the application does
102486 ** not want the user to be able to make arbitrary changes to the
102487 ** database.  An authorizer could then be put in place while the
102488 ** user-entered SQL is being prepared that disallows everything
102489 ** except SELECT statements.  
102490 **
102491 ** {F12520} Only a single authorizer can be in place on a database connection
102492 ** at a time.  Each call to sqlite3_set_authorizer overrides the
102493 ** previous call. {F12521}  A NULL authorizer means that no authorization
102494 ** callback is invoked.  {F12522} The default authorizer is NULL. {END}
102495 **
102496 ** Note that the authorizer callback is invoked only during 
102497 ** [sqlite3_prepare()] or its variants.  {F12523} Authorization is not
102498 ** performed during statement evaluation in [sqlite3_step()]. {END}
102499 */
102500 int sqlite3_set_authorizer(
102501   sqlite3*,
102502   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
102503   void *pUserData
102504 );
102505
102506 /*
102507 ** CAPI3REF: Authorizer Return Codes {F12590}
102508 **
102509 ** The [sqlite3_set_authorizer | authorizer callback function] must
102510 ** return either [SQLITE_OK] or one of these two constants in order
102511 ** to signal SQLite whether or not the action is permitted.  See the
102512 ** [sqlite3_set_authorizer | authorizer documentation] for additional
102513 ** information.
102514 */
102515 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
102516 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
102517
102518 /*
102519 ** CAPI3REF: Authorizer Action Codes {F12550}
102520 **
102521 ** The [sqlite3_set_authorizer()] interface registers a callback function
102522 ** that is invoked to authorizer certain SQL statement actions.  {F12551} The
102523 ** second parameter to the callback is an integer code that specifies
102524 ** what action is being authorized.  These are the integer action codes that
102525 ** the authorizer callback may be passed. {END}
102526 **
102527 ** These action code values signify what kind of operation is to be 
102528 ** authorized.  {F12552} The 3rd and 4th parameters to the authorization
102529 ** callback function will be parameters or NULL depending on which of these
102530 ** codes is used as the second parameter. {F12553} The 5th parameter to the
102531 ** authorizer callback is the name of the database ("main", "temp", 
102532 ** etc.) if applicable. {F12554} The 6th parameter to the authorizer callback
102533 ** is the name of the inner-most trigger or view that is responsible for
102534 ** the access attempt or NULL if this access attempt is directly from 
102535 ** top-level SQL code.
102536 */
102537 /******************************************* 3rd ************ 4th ***********/
102538 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
102539 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
102540 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
102541 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
102542 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
102543 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
102544 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
102545 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
102546 #define SQLITE_DELETE                9   /* Table Name      NULL            */
102547 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
102548 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
102549 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
102550 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
102551 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
102552 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
102553 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
102554 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
102555 #define SQLITE_INSERT               18   /* Table Name      NULL            */
102556 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
102557 #define SQLITE_READ                 20   /* Table Name      Column Name     */
102558 #define SQLITE_SELECT               21   /* NULL            NULL            */
102559 #define SQLITE_TRANSACTION          22   /* NULL            NULL            */
102560 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
102561 #define SQLITE_ATTACH               24   /* Filename        NULL            */
102562 #define SQLITE_DETACH               25   /* Database Name   NULL            */
102563 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
102564 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
102565 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
102566 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
102567 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
102568 #define SQLITE_FUNCTION             31   /* Function Name   NULL            */
102569 #define SQLITE_COPY                  0   /* No longer used */
102570
102571 /*
102572 ** CAPI3REF: Tracing And Profiling Functions {F12280}
102573 **
102574 ** These routines register callback functions that can be used for
102575 ** tracing and profiling the execution of SQL statements.
102576 **
102577 ** {F12281} The callback function registered by sqlite3_trace() is invoked
102578 ** at the first [sqlite3_step()] for the evaluation of an SQL statement.
102579 ** {F12282} Only a single trace callback can be registered at a time.
102580 ** Each call to sqlite3_trace() overrides the previous.  {F12283} A
102581 ** NULL callback for sqlite3_trace() disables tracing.  {F12284} The
102582 ** first argument to the trace callback is a copy of the pointer which
102583 ** was the 3rd argument to sqlite3_trace.  {F12285} The second argument
102584 ** to the trace callback is a zero-terminated UTF8 string containing
102585 ** the original text of the SQL statement as it was passed into
102586 ** [sqlite3_prepare_v2()] or the equivalent. {END}  Note that the
102587 ** host parameter are not expanded in the SQL statement text.
102588 **
102589 ** {F12287} The callback function registered by sqlite3_profile() is invoked
102590 ** as each SQL statement finishes.  {F12288} The first parameter to the
102591 ** profile callback is a copy of the 3rd parameter to sqlite3_profile().
102592 ** {F12289} The second parameter to the profile callback is a
102593 ** zero-terminated UTF-8 string that contains the complete text of
102594 ** the SQL statement as it was processed by [sqlite3_prepare_v2()] or
102595 ** the equivalent.  {F12290} The third parameter to the profile 
102596 ** callback is an estimate of the number of nanoseconds of
102597 ** wall-clock time required to run the SQL statement from start
102598 ** to finish. {END}  
102599 **
102600 ** The sqlite3_profile() API is currently considered experimental and
102601 ** is subject to change.
102602 */
102603 void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
102604 void *sqlite3_profile(sqlite3*,
102605    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
102606
102607 /*
102608 ** CAPI3REF: Query Progress Callbacks {F12910}
102609 **
102610 ** {F12911} This routine configures a callback function - the
102611 ** progress callback - that is invoked periodically during long
102612 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
102613 ** [sqlite3_get_table()]. {END}  An example use for this 
102614 ** interface is to keep a GUI updated during a large query.
102615 **
102616 ** {F12912} The progress callback is invoked once for every N virtual
102617 ** machine opcodes, where N is the second argument to this function.
102618 ** {F12913} The progress callback itself is identified by the third
102619 ** argument to this function. {F12914} The fourth argument to this
102620 ** function is a void pointer passed to the progress callback
102621 ** function each time it is invoked. {END}
102622 **
102623 ** {F12915} If a call to [sqlite3_exec()], [sqlite3_step()], or
102624 ** [sqlite3_get_table()] results in fewer than N opcodes being executed,
102625 ** then the progress callback is never invoked. {END}
102626 ** 
102627 ** {F12916} Only a single progress callback function may be registered for each
102628 ** open database connection.  Every call to sqlite3_progress_handler()
102629 ** overwrites the results of the previous call. {F12917}
102630 ** To remove the progress callback altogether, pass NULL as the third
102631 ** argument to this function. {END}
102632 **
102633 ** {F12918} If the progress callback returns a result other than 0, then
102634 ** the current query is immediately terminated and any database changes
102635 ** rolled back. {F12919}
102636 ** The containing [sqlite3_exec()], [sqlite3_step()], or
102637 ** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. {END}  This feature
102638 ** can be used, for example, to implement the "Cancel" button on a
102639 ** progress dialog box in a GUI.
102640 */
102641 void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
102642
102643 /*
102644 ** CAPI3REF: Opening A New Database Connection {F12700}
102645 **
102646 ** {F12701} These routines open an SQLite database file whose name
102647 ** is given by the filename argument.
102648 ** {F12702} The filename argument is interpreted as UTF-8
102649 ** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16
102650 ** in the native byte order for [sqlite3_open16()].
102651 ** {F12703} An [sqlite3*] handle is returned in *ppDb, even
102652 ** if an error occurs.  {F12723} (Exception: if SQLite is unable
102653 ** to allocate memory to hold the [sqlite3] object, a NULL will
102654 ** be written into *ppDb instead of a pointer to the [sqlite3] object.)
102655 ** {F12704} If the database is opened (and/or created)
102656 ** successfully, then [SQLITE_OK] is returned.  {F12705} Otherwise an
102657 ** error code is returned.  {F12706} The
102658 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()]  routines can be used to obtain
102659 ** an English language description of the error.
102660 **
102661 ** {F12707} The default encoding for the database will be UTF-8 if
102662 ** [sqlite3_open()] or [sqlite3_open_v2()] is called and
102663 ** UTF-16 in the native byte order if [sqlite3_open16()] is used.
102664 **
102665 ** {F12708} Whether or not an error occurs when it is opened, resources
102666 ** associated with the [sqlite3*] handle should be released by passing it
102667 ** to [sqlite3_close()] when it is no longer required.
102668 **
102669 ** {F12709} The [sqlite3_open_v2()] interface works like [sqlite3_open()] 
102670 ** except that it acccepts two additional parameters for additional control
102671 ** over the new database connection.  {F12710} The flags parameter can be
102672 ** one of:
102673 **
102674 ** <ol>
102675 ** <li>  [SQLITE_OPEN_READONLY]
102676 ** <li>  [SQLITE_OPEN_READWRITE]
102677 ** <li>  [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
102678 ** </ol>
102679 **
102680 ** {F12711} The first value opens the database read-only. 
102681 ** {F12712} If the database does not previously exist, an error is returned.
102682 ** {F12713} The second option opens
102683 ** the database for reading and writing if possible, or reading only if
102684 ** if the file is write protected.  {F12714} In either case the database
102685 ** must already exist or an error is returned.  {F12715} The third option
102686 ** opens the database for reading and writing and creates it if it does
102687 ** not already exist. {F12716}
102688 ** The third options is behavior that is always used for [sqlite3_open()]
102689 ** and [sqlite3_open16()].
102690 **
102691 ** {F12717} If the filename is ":memory:", then an private
102692 ** in-memory database is created for the connection. {F12718} This in-memory
102693 ** database will vanish when the database connection is closed. {END}  Future
102694 ** version of SQLite might make use of additional special filenames
102695 ** that begin with the ":" character.  It is recommended that 
102696 ** when a database filename really does begin with
102697 ** ":" that you prefix the filename with a pathname like "./" to
102698 ** avoid ambiguity.
102699 **
102700 ** {F12719} If the filename is an empty string, then a private temporary
102701 ** on-disk database will be created.  {F12720} This private database will be
102702 ** automatically deleted as soon as the database connection is closed.
102703 **
102704 ** {F12721} The fourth parameter to sqlite3_open_v2() is the name of the
102705 ** [sqlite3_vfs] object that defines the operating system 
102706 ** interface that the new database connection should use.  {F12722} If the
102707 ** fourth parameter is a NULL pointer then the default [sqlite3_vfs]
102708 ** object is used. {END}
102709 **
102710 ** <b>Note to windows users:</b>  The encoding used for the filename argument
102711 ** of [sqlite3_open()] and [sqlite3_open_v2()] must be UTF-8, not whatever
102712 ** codepage is currently defined.  Filenames containing international
102713 ** characters must be converted to UTF-8 prior to passing them into
102714 ** [sqlite3_open()] or [sqlite3_open_v2()].
102715 */
102716 int sqlite3_open(
102717   const char *filename,   /* Database filename (UTF-8) */
102718   sqlite3 **ppDb          /* OUT: SQLite db handle */
102719 );
102720 int sqlite3_open16(
102721   const void *filename,   /* Database filename (UTF-16) */
102722   sqlite3 **ppDb          /* OUT: SQLite db handle */
102723 );
102724 int sqlite3_open_v2(
102725   const char *filename,   /* Database filename (UTF-8) */
102726   sqlite3 **ppDb,         /* OUT: SQLite db handle */
102727   int flags,              /* Flags */
102728   const char *zVfs        /* Name of VFS module to use */
102729 );
102730
102731 /*
102732 ** CAPI3REF: Error Codes And Messages {F12800}
102733 **
102734 ** {F12801} The sqlite3_errcode() interface returns the numeric
102735 ** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code]
102736 ** for the most recent failed sqlite3_* API call associated
102737 ** with [sqlite3] handle 'db'. {U12802} If a prior API call failed but the
102738 ** most recent API call succeeded, the return value from sqlite3_errcode()
102739 ** is undefined. {END}
102740 **
102741 ** {F12803} The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
102742 ** text that describes the error, as either UTF8 or UTF16 respectively.
102743 ** {F12804} Memory to hold the error message string is managed internally.
102744 ** {U12805} The 
102745 ** string may be overwritten or deallocated by subsequent calls to SQLite
102746 ** interface functions. {END}
102747 **
102748 ** {F12806} Calls to many sqlite3_* functions set the error code and
102749 ** string returned by [sqlite3_errcode()], [sqlite3_errmsg()], and
102750 ** [sqlite3_errmsg16()] overwriting the previous values.  {F12807}
102751 ** Except, calls to [sqlite3_errcode()],
102752 ** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the
102753 ** results of future invocations.  {F12808} Calls to API routines that
102754 ** do not return an error code (example: [sqlite3_data_count()]) do not
102755 ** change the error code returned by this routine.  {F12809} Interfaces that
102756 ** are not associated with a specific database connection (examples:
102757 ** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change
102758 ** the return code. {END}
102759 **
102760 ** {F12810} Assuming no other intervening sqlite3_* API calls are made,
102761 ** the error code returned by this function is associated with the same
102762 ** error as the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()].
102763 */
102764 int sqlite3_errcode(sqlite3 *db);
102765 const char *sqlite3_errmsg(sqlite3*);
102766 const void *sqlite3_errmsg16(sqlite3*);
102767
102768 /*
102769 ** CAPI3REF: SQL Statement Object {F13000}
102770 **
102771 ** An instance of this object represent single SQL statements.  This
102772 ** object is variously known as a "prepared statement" or a 
102773 ** "compiled SQL statement" or simply as a "statement".
102774 ** 
102775 ** The life of a statement object goes something like this:
102776 **
102777 ** <ol>
102778 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
102779 **      function.
102780 ** <li> Bind values to host parameters using
102781 **      [sqlite3_bind_blob | sqlite3_bind_* interfaces].
102782 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
102783 ** <li> Reset the statement using [sqlite3_reset()] then go back
102784 **      to step 2.  Do this zero or more times.
102785 ** <li> Destroy the object using [sqlite3_finalize()].
102786 ** </ol>
102787 **
102788 ** Refer to documentation on individual methods above for additional
102789 ** information.
102790 */
102791 typedef struct sqlite3_stmt sqlite3_stmt;
102792
102793 /*
102794 ** CAPI3REF: Compiling An SQL Statement {F13010}
102795 **
102796 ** To execute an SQL query, it must first be compiled into a byte-code
102797 ** program using one of these routines. 
102798 **
102799 ** {F13011} The first argument "db" is an [sqlite3 | SQLite database handle] 
102800 ** obtained from a prior call to [sqlite3_open()], [sqlite3_open_v2()]
102801 ** or [sqlite3_open16()]. {F13012}
102802 ** The second argument "zSql" is the statement to be compiled, encoded
102803 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
102804 ** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2()
102805 ** use UTF-16. {END}
102806 **
102807 ** {F13013} If the nByte argument is less
102808 ** than zero, then zSql is read up to the first zero terminator.
102809 ** {F13014} If nByte is non-negative, then it is the maximum number of 
102810 ** bytes read from zSql.  When nByte is non-negative, the
102811 ** zSql string ends at either the first '\000' or '\u0000' character or 
102812 ** until the nByte-th byte, whichever comes first. {END}
102813 **
102814 ** {F13015} *pzTail is made to point to the first byte past the end of the
102815 ** first SQL statement in zSql.  These routines only compiles the first
102816 ** statement in zSql, so *pzTail is left pointing to what remains
102817 ** uncompiled. {END}
102818 **
102819 ** {F13016} *ppStmt is left pointing to a compiled 
102820 ** [sqlite3_stmt | SQL statement structure] that can be
102821 ** executed using [sqlite3_step()].  Or if there is an error, *ppStmt may be
102822 ** set to NULL.  {F13017} If the input text contains no SQL (if the input
102823 ** is and empty string or a comment) then *ppStmt is set to NULL.
102824 ** {U13018} The calling procedure is responsible for deleting the
102825 ** compiled SQL statement
102826 ** using [sqlite3_finalize()] after it has finished with it.
102827 **
102828 ** {F13019} On success, [SQLITE_OK] is returned.  Otherwise an 
102829 ** [SQLITE_ERROR | error code] is returned. {END}
102830 **
102831 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
102832 ** recommended for all new programs. The two older interfaces are retained
102833 ** for backwards compatibility, but their use is discouraged.
102834 ** {F13020} In the "v2" interfaces, the prepared statement
102835 ** that is returned (the [sqlite3_stmt] object) contains a copy of the 
102836 ** original SQL text. {END} This causes the [sqlite3_step()] interface to
102837 ** behave a differently in two ways:
102838 **
102839 ** <ol>
102840 ** <li>{F13022}
102841 ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
102842 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
102843 ** statement and try to run it again. {F12023} If the schema has changed in
102844 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
102845 ** return [SQLITE_SCHEMA].  {END} But unlike the legacy behavior, 
102846 ** [SQLITE_SCHEMA] is now a fatal error.  {F12024} Calling
102847 ** [sqlite3_prepare_v2()] again will not make the
102848 ** error go away.  {F12025} Note: use [sqlite3_errmsg()] to find the text
102849 ** of the parsing error that results in an [SQLITE_SCHEMA] return. {END}
102850 ** </li>
102851 **
102852 ** <li>
102853 ** {F13030} When an error occurs, 
102854 ** [sqlite3_step()] will return one of the detailed 
102855 ** [SQLITE_ERROR | result codes] or
102856 ** [SQLITE_IOERR_READ | extended result codes].  {F13031}
102857 ** The legacy behavior was that [sqlite3_step()] would only return a generic
102858 ** [SQLITE_ERROR] result code and you would have to make a second call to
102859 ** [sqlite3_reset()] in order to find the underlying cause of the problem.
102860 ** {F13032}
102861 ** With the "v2" prepare interfaces, the underlying reason for the error is
102862 ** returned immediately. {END}
102863 ** </li>
102864 ** </ol>
102865 */
102866 int sqlite3_prepare(
102867   sqlite3 *db,            /* Database handle */
102868   const char *zSql,       /* SQL statement, UTF-8 encoded */
102869   int nByte,              /* Maximum length of zSql in bytes. */
102870   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
102871   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
102872 );
102873 int sqlite3_prepare_v2(
102874   sqlite3 *db,            /* Database handle */
102875   const char *zSql,       /* SQL statement, UTF-8 encoded */
102876   int nByte,              /* Maximum length of zSql in bytes. */
102877   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
102878   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
102879 );
102880 int sqlite3_prepare16(
102881   sqlite3 *db,            /* Database handle */
102882   const void *zSql,       /* SQL statement, UTF-16 encoded */
102883   int nByte,              /* Maximum length of zSql in bytes. */
102884   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
102885   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
102886 );
102887 int sqlite3_prepare16_v2(
102888   sqlite3 *db,            /* Database handle */
102889   const void *zSql,       /* SQL statement, UTF-16 encoded */
102890   int nByte,              /* Maximum length of zSql in bytes. */
102891   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
102892   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
102893 );
102894
102895 /*
102896 ** CAPIREF: Retrieving Statement SQL {F13100}
102897 **
102898 ** {F13101} If the compiled SQL statement passed as an argument was
102899 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()],
102900 ** then this function returns a pointer to a zero-terminated string
102901 ** containing a copy of the original SQL statement. {F13102} The
102902 ** pointer is valid until the statement
102903 ** is deleted using sqlite3_finalize().
102904 ** {F13103} The string returned by sqlite3_sql() is always UTF8 even
102905 ** if a UTF16 string was originally entered using [sqlite3_prepare16_v2()]
102906 ** or the equivalent.
102907 **
102908 ** {F13104} If the statement was compiled using either of the legacy
102909 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this
102910 ** function returns NULL.
102911 */
102912 const char *sqlite3_sql(sqlite3_stmt *pStmt);
102913
102914 /*
102915 ** CAPI3REF:  Dynamically Typed Value Object  {F15000}
102916 **
102917 ** {F15001} SQLite uses the sqlite3_value object to represent all values
102918 ** that are or can be stored in a database table. {END}
102919 ** SQLite uses dynamic typing for the values it stores.  
102920 ** {F15002} Values stored in sqlite3_value objects can be
102921 ** be integers, floating point values, strings, BLOBs, or NULL.
102922 */
102923 typedef struct Mem sqlite3_value;
102924
102925 /*
102926 ** CAPI3REF:  SQL Function Context Object {F16001}
102927 **
102928 ** The context in which an SQL function executes is stored in an
102929 ** sqlite3_context object.  {F16002} A pointer to an sqlite3_context
102930 ** object is always first parameter to application-defined SQL functions.
102931 */
102932 typedef struct sqlite3_context sqlite3_context;
102933
102934 /*
102935 ** CAPI3REF:  Binding Values To Prepared Statements {F13500}
102936 **
102937 ** {F13501} In the SQL strings input to [sqlite3_prepare_v2()] and its
102938 ** variants, literals may be replace by a parameter in one
102939 ** of these forms:
102940 **
102941 ** <ul>
102942 ** <li>  ?
102943 ** <li>  ?NNN
102944 ** <li>  :AAA
102945 ** <li>  @AAA
102946 ** <li>  $VVV
102947 ** </ul>
102948 **
102949 ** In the parameter forms shown above NNN is an integer literal,
102950 ** AAA is an alphanumeric identifier and VVV is a variable name according
102951 ** to the syntax rules of the TCL programming language. {END}
102952 ** The values of these parameters (also called "host parameter names")
102953 ** can be set using the sqlite3_bind_*() routines defined here.
102954 **
102955 ** {F13502} The first argument to the sqlite3_bind_*() routines always
102956 ** is a pointer to the [sqlite3_stmt] object returned from
102957 ** [sqlite3_prepare_v2()] or its variants.  {F13503} The second
102958 ** argument is the index of the parameter to be set.  {F13504} The
102959 ** first parameter has an index of 1.  {F13505} When the same named
102960 ** parameter is used more than once, second and subsequent
102961 ** occurrences have the same index as the first occurrence. 
102962 ** {F13506} The index for named parameters can be looked up using the
102963 ** [sqlite3_bind_parameter_name()] API if desired.  {F13507} The index
102964 ** for "?NNN" parameters is the value of NNN.
102965 ** {F13508} The NNN value must be between 1 and the compile-time
102966 ** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). {END}
102967 ** See <a href="limits.html">limits.html</a> for additional information.
102968 **
102969 ** {F13509} The third argument is the value to bind to the parameter. {END}
102970 **
102971 ** {F13510} In those
102972 ** routines that have a fourth argument, its value is the number of bytes
102973 ** in the parameter.  To be clear: the value is the number of bytes in the
102974 ** string, not the number of characters. {F13511}  The number
102975 ** of bytes does not include the zero-terminator at the end of strings.
102976 ** {F13512}
102977 ** If the fourth parameter is negative, the length of the string is
102978 ** number of bytes up to the first zero terminator. {END}
102979 **
102980 ** {F13513}
102981 ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
102982 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
102983 ** text after SQLite has finished with it. {F13514} If the fifth argument is
102984 ** the special value [SQLITE_STATIC], then the library assumes that the
102985 ** information is in static, unmanaged space and does not need to be freed.
102986 ** {F13515} If the fifth argument has the value [SQLITE_TRANSIENT], then
102987 ** SQLite makes its own private copy of the data immediately, before
102988 ** the sqlite3_bind_*() routine returns. {END}
102989 **
102990 ** {F13520} The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
102991 ** is filled with zeros.  {F13521} A zeroblob uses a fixed amount of memory
102992 ** (just an integer to hold it size) while it is being processed. {END}
102993 ** Zeroblobs are intended to serve as place-holders for BLOBs whose
102994 ** content is later written using 
102995 ** [sqlite3_blob_open | increment BLOB I/O] routines. {F13522} A negative
102996 ** value for the zeroblob results in a zero-length BLOB. {END}
102997 **
102998 ** {F13530} The sqlite3_bind_*() routines must be called after
102999 ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and
103000 ** before [sqlite3_step()]. {F13531}
103001 ** Bindings are not cleared by the [sqlite3_reset()] routine.
103002 ** {F13532} Unbound parameters are interpreted as NULL. {END}
103003 **
103004 ** {F13540} These routines return [SQLITE_OK] on success or an error code if
103005 ** anything goes wrong.  {F13541} [SQLITE_RANGE] is returned if the parameter
103006 ** index is out of range.  {F13542} [SQLITE_NOMEM] is returned if malloc fails.
103007 ** {F13543} [SQLITE_MISUSE] is returned if these routines are called on a
103008 ** virtual machine that is the wrong state or which has already been finalized.
103009 */
103010 int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
103011 int sqlite3_bind_double(sqlite3_stmt*, int, double);
103012 int sqlite3_bind_int(sqlite3_stmt*, int, int);
103013 int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
103014 int sqlite3_bind_null(sqlite3_stmt*, int);
103015 int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
103016 int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
103017 int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
103018 int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
103019
103020 /*
103021 ** CAPI3REF: Number Of Host Parameters {F13600}
103022 **
103023 ** {F13601} Return the largest host parameter index in the precompiled
103024 ** statement given as the argument. {F13602} When the host parameters
103025 ** are of the forms like ":AAA", "$VVV", "@AAA", or "?",
103026 ** then they are assigned sequential increasing numbers beginning
103027 ** with one, so the value returned is the number of parameters.
103028 ** {F13603} However
103029 ** if the same host parameter name is used multiple times, each occurrance
103030 ** is given the same number, so the value returned in that case is the number
103031 ** of unique host parameter names. {F13604} If host parameters of the
103032 ** form "?NNN" are used (where NNN is an integer) then there might be
103033 ** gaps in the numbering and the value returned by this interface is
103034 ** the index of the host parameter with the largest index value. {END}
103035 **
103036 ** {U13605} The prepared statement must not be [sqlite3_finalize | finalized]
103037 ** prior to this routine returning.  Otherwise the results are undefined
103038 ** and probably undesirable.
103039 */
103040 int sqlite3_bind_parameter_count(sqlite3_stmt*);
103041
103042 /*
103043 ** CAPI3REF: Name Of A Host Parameter {F13620}
103044 **
103045 ** {F13621} This routine returns a pointer to the name of the n-th
103046 ** parameter in a [sqlite3_stmt | prepared statement]. {F13622}
103047 ** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name
103048 ** which is the string ":AAA" or "@AAA" or "$VVV". 
103049 ** In other words, the initial ":" or "$" or "@"
103050 ** is included as part of the name.  {F13626}
103051 ** Parameters of the form "?" or "?NNN" have no name.
103052 **
103053 ** {F13623} The first host parameter has an index of 1, not 0.
103054 **
103055 ** {F13624} If the value n is out of range or if the n-th parameter is
103056 ** nameless, then NULL is returned.  {F13625} The returned string is
103057 ** always in the UTF-8 encoding even if the named parameter was
103058 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
103059 ** [sqlite3_prepare16_v2()].
103060 */
103061 const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
103062
103063 /*
103064 ** CAPI3REF: Index Of A Parameter With A Given Name {F13640}
103065 **
103066 ** {F13641} This routine returns the index of a host parameter with the
103067 ** given name.  {F13642} The name must match exactly.  {F13643}
103068 ** If no parameter with the given name is found, return 0.
103069 ** {F13644} Parameter names must be UTF8.
103070 */
103071 int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
103072
103073 /*
103074 ** CAPI3REF: Reset All Bindings On A Prepared Statement {F13660}
103075 **
103076 ** {F13661} Contrary to the intuition of many, [sqlite3_reset()] does not
103077 ** reset the [sqlite3_bind_blob | bindings] on a 
103078 ** [sqlite3_stmt | prepared statement]. {F13662} Use this routine to
103079 ** reset all host parameters to NULL.
103080 */
103081 int sqlite3_clear_bindings(sqlite3_stmt*);
103082
103083 /*
103084 ** CAPI3REF: Number Of Columns In A Result Set {F13710}
103085 **
103086 ** {F13711} Return the number of columns in the result set returned by the 
103087 ** [sqlite3_stmt | compiled SQL statement]. {F13712} This routine returns 0
103088 ** if pStmt is an SQL statement that does not return data (for 
103089 ** example an UPDATE).
103090 */
103091 int sqlite3_column_count(sqlite3_stmt *pStmt);
103092
103093 /*
103094 ** CAPI3REF: Column Names In A Result Set {F13720}
103095 **
103096 ** {F13721} These routines return the name assigned to a particular column
103097 ** in the result set of a SELECT statement.  {F13722} The sqlite3_column_name()
103098 ** interface returns a pointer to a zero-terminated UTF8 string
103099 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
103100 ** UTF16 string. {F13723}  The first parameter is the
103101 ** [sqlite3_stmt | prepared statement] that implements the SELECT statement.
103102 ** The second parameter is the column number.  The left-most column is
103103 ** number 0.
103104 **
103105 ** {F13724} The returned string pointer is valid until either the 
103106 ** [sqlite3_stmt | prepared statement] is destroyed by [sqlite3_finalize()]
103107 ** or until the next call sqlite3_column_name() or sqlite3_column_name16()
103108 ** on the same column.
103109 **
103110 ** {F13725} If sqlite3_malloc() fails during the processing of either routine
103111 ** (for example during a conversion from UTF-8 to UTF-16) then a
103112 ** NULL pointer is returned.
103113 */
103114 const char *sqlite3_column_name(sqlite3_stmt*, int N);
103115 const void *sqlite3_column_name16(sqlite3_stmt*, int N);
103116
103117 /*
103118 ** CAPI3REF: Source Of Data In A Query Result {F13740}
103119 **
103120 ** {F13741} These routines provide a means to determine what column of what
103121 ** table in which database a result of a SELECT statement comes from.
103122 ** {F13742} The name of the database or table or column can be returned as
103123 ** either a UTF8 or UTF16 string.  {F13743} The _database_ routines return
103124 ** the database name, the _table_ routines return the table name, and
103125 ** the origin_ routines return the column name. {F13744}
103126 ** The returned string is valid until
103127 ** the [sqlite3_stmt | prepared statement] is destroyed using
103128 ** [sqlite3_finalize()] or until the same information is requested
103129 ** again in a different encoding.
103130 **
103131 ** {F13745} The names returned are the original un-aliased names of the
103132 ** database, table, and column.
103133 **
103134 ** {F13746} The first argument to the following calls is a 
103135 ** [sqlite3_stmt | compiled SQL statement].
103136 ** {F13747} These functions return information about the Nth column returned by 
103137 ** the statement, where N is the second function argument.
103138 **
103139 ** {F13748} If the Nth column returned by the statement is an expression
103140 ** or subquery and is not a column value, then all of these functions
103141 ** return NULL.  {F13749} Otherwise, they return the 
103142 ** name of the attached database, table and column that query result
103143 ** column was extracted from.
103144 **
103145 ** {F13750} As with all other SQLite APIs, those postfixed with "16" return
103146 ** UTF-16 encoded strings, the other functions return UTF-8. {END}
103147 **
103148 ** These APIs are only available if the library was compiled with the 
103149 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
103150 **
103151 ** {U13751}
103152 ** If two or more threads call one or more of these routines against the same
103153 ** prepared statement and column at the same time then the results are
103154 ** undefined.
103155 */
103156 const char *sqlite3_column_database_name(sqlite3_stmt*,int);
103157 const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
103158 const char *sqlite3_column_table_name(sqlite3_stmt*,int);
103159 const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
103160 const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
103161 const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
103162
103163 /*
103164 ** CAPI3REF: Declared Datatype Of A Query Result {F13760}
103165 **
103166 ** The first parameter is a [sqlite3_stmt | compiled SQL statement]. 
103167 ** {F13761} If this statement is a SELECT statement and the Nth column of the 
103168 ** returned result set of that SELECT is a table column (not an
103169 ** expression or subquery) then the declared type of the table
103170 ** column is returned.  {F13762} If the Nth column of the result set is an
103171 ** expression or subquery, then a NULL pointer is returned.
103172 ** {F13763} The returned string is always UTF-8 encoded.  {END} 
103173 ** For example, in the database schema:
103174 **
103175 ** CREATE TABLE t1(c1 VARIANT);
103176 **
103177 ** And the following statement compiled:
103178 **
103179 ** SELECT c1 + 1, c1 FROM t1;
103180 **
103181 ** Then this routine would return the string "VARIANT" for the second
103182 ** result column (i==1), and a NULL pointer for the first result column
103183 ** (i==0).
103184 **
103185 ** SQLite uses dynamic run-time typing.  So just because a column
103186 ** is declared to contain a particular type does not mean that the
103187 ** data stored in that column is of the declared type.  SQLite is
103188 ** strongly typed, but the typing is dynamic not static.  Type
103189 ** is associated with individual values, not with the containers
103190 ** used to hold those values.
103191 */
103192 const char *sqlite3_column_decltype(sqlite3_stmt *, int i);
103193 const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
103194
103195 /* 
103196 ** CAPI3REF:  Evaluate An SQL Statement {F13200}
103197 **
103198 ** After an [sqlite3_stmt | SQL statement] has been prepared with a call
103199 ** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of
103200 ** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()],
103201 ** then this function must be called one or more times to evaluate the 
103202 ** statement.
103203 **
103204 ** The details of the behavior of this sqlite3_step() interface depend
103205 ** on whether the statement was prepared using the newer "v2" interface
103206 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
103207 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
103208 ** new "v2" interface is recommended for new applications but the legacy
103209 ** interface will continue to be supported.
103210 **
103211 ** In the lagacy interface, the return value will be either [SQLITE_BUSY], 
103212 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
103213 ** With the "v2" interface, any of the other [SQLITE_OK | result code]
103214 ** or [SQLITE_IOERR_READ | extended result code] might be returned as
103215 ** well.
103216 **
103217 ** [SQLITE_BUSY] means that the database engine was unable to acquire the
103218 ** database locks it needs to do its job.  If the statement is a COMMIT
103219 ** or occurs outside of an explicit transaction, then you can retry the
103220 ** statement.  If the statement is not a COMMIT and occurs within a
103221 ** explicit transaction then you should rollback the transaction before
103222 ** continuing.
103223 **
103224 ** [SQLITE_DONE] means that the statement has finished executing
103225 ** successfully.  sqlite3_step() should not be called again on this virtual
103226 ** machine without first calling [sqlite3_reset()] to reset the virtual
103227 ** machine back to its initial state.
103228 **
103229 ** If the SQL statement being executed returns any data, then 
103230 ** [SQLITE_ROW] is returned each time a new row of data is ready
103231 ** for processing by the caller. The values may be accessed using
103232 ** the [sqlite3_column_int | column access functions].
103233 ** sqlite3_step() is called again to retrieve the next row of data.
103234 ** 
103235 ** [SQLITE_ERROR] means that a run-time error (such as a constraint
103236 ** violation) has occurred.  sqlite3_step() should not be called again on
103237 ** the VM. More information may be found by calling [sqlite3_errmsg()].
103238 ** With the legacy interface, a more specific error code (example:
103239 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
103240 ** can be obtained by calling [sqlite3_reset()] on the
103241 ** [sqlite3_stmt | prepared statement].  In the "v2" interface,
103242 ** the more specific error code is returned directly by sqlite3_step().
103243 **
103244 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
103245 ** Perhaps it was called on a [sqlite3_stmt | prepared statement] that has
103246 ** already been [sqlite3_finalize | finalized] or on one that had 
103247 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
103248 ** be the case that the same database connection is being used by two or
103249 ** more threads at the same moment in time.
103250 **
103251 ** <b>Goofy Interface Alert:</b>
103252 ** In the legacy interface, 
103253 ** the sqlite3_step() API always returns a generic error code,
103254 ** [SQLITE_ERROR], following any error other than [SQLITE_BUSY]
103255 ** and [SQLITE_MISUSE].  You must call [sqlite3_reset()] or
103256 ** [sqlite3_finalize()] in order to find one of the specific
103257 ** [SQLITE_ERROR | result codes] that better describes the error.
103258 ** We admit that this is a goofy design.  The problem has been fixed
103259 ** with the "v2" interface.  If you prepare all of your SQL statements
103260 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
103261 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the 
103262 ** more specific [SQLITE_ERROR | result codes] are returned directly
103263 ** by sqlite3_step().  The use of the "v2" interface is recommended.
103264 */
103265 int sqlite3_step(sqlite3_stmt*);
103266
103267 /*
103268 ** CAPI3REF: Number of columns in a result set {F13770}
103269 **
103270 ** Return the number of values in the current row of the result set.
103271 **
103272 ** {F13771} After a call to [sqlite3_step()] that returns [SQLITE_ROW],
103273 ** this routine
103274 ** will return the same value as the [sqlite3_column_count()] function.
103275 ** {F13772}
103276 ** After [sqlite3_step()] has returned an [SQLITE_DONE], [SQLITE_BUSY], or
103277 ** a [SQLITE_ERROR | error code], or before [sqlite3_step()] has been 
103278 ** called on the [sqlite3_stmt | prepared statement] for the first time,
103279 ** this routine returns zero.
103280 */
103281 int sqlite3_data_count(sqlite3_stmt *pStmt);
103282
103283 /*
103284 ** CAPI3REF: Fundamental Datatypes {F10265}
103285 **
103286 ** {F10266}Every value in SQLite has one of five fundamental datatypes:
103287 **
103288 ** <ul>
103289 ** <li> 64-bit signed integer
103290 ** <li> 64-bit IEEE floating point number
103291 ** <li> string
103292 ** <li> BLOB
103293 ** <li> NULL
103294 ** </ul> {END}
103295 **
103296 ** These constants are codes for each of those types.
103297 **
103298 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
103299 ** for a completely different meaning.  Software that links against both
103300 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not
103301 ** SQLITE_TEXT.
103302 */
103303 #define SQLITE_INTEGER  1
103304 #define SQLITE_FLOAT    2
103305 #define SQLITE_BLOB     4
103306 #define SQLITE_NULL     5
103307 #ifdef SQLITE_TEXT
103308 # undef SQLITE_TEXT
103309 #else
103310 # define SQLITE_TEXT     3
103311 #endif
103312 #define SQLITE3_TEXT     3
103313
103314 /*
103315 ** CAPI3REF: Results Values From A Query {F13800}
103316 **
103317 ** These routines return information about
103318 ** a single column of the current result row of a query.  In every
103319 ** case the first argument is a pointer to the 
103320 ** [sqlite3_stmt | SQL statement] that is being
103321 ** evaluated (the [sqlite3_stmt*] that was returned from 
103322 ** [sqlite3_prepare_v2()] or one of its variants) and
103323 ** the second argument is the index of the column for which information 
103324 ** should be returned.  The left-most column of the result set
103325 ** has an index of 0.
103326 **
103327 ** If the SQL statement is not currently point to a valid row, or if the
103328 ** the column index is out of range, the result is undefined. 
103329 ** These routines may only be called when the most recent call to
103330 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
103331 ** [sqlite3_reset()] nor [sqlite3_finalize()] has been call subsequently.
103332 ** If any of these routines are called after [sqlite3_reset()] or
103333 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
103334 ** something other than [SQLITE_ROW], the results are undefined.
103335 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
103336 ** are called from a different thread while any of these routines
103337 ** are pending, then the results are undefined.  
103338 **
103339 ** The sqlite3_column_type() routine returns 
103340 ** [SQLITE_INTEGER | datatype code] for the initial data type
103341 ** of the result column.  The returned value is one of [SQLITE_INTEGER],
103342 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
103343 ** returned by sqlite3_column_type() is only meaningful if no type
103344 ** conversions have occurred as described below.  After a type conversion,
103345 ** the value returned by sqlite3_column_type() is undefined.  Future
103346 ** versions of SQLite may change the behavior of sqlite3_column_type()
103347 ** following a type conversion.
103348 **
103349 ** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() 
103350 ** routine returns the number of bytes in that BLOB or string.
103351 ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
103352 ** the string to UTF-8 and then returns the number of bytes.
103353 ** If the result is a numeric value then sqlite3_column_bytes() uses
103354 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
103355 ** the number of bytes in that string.
103356 ** The value returned does not include the zero terminator at the end
103357 ** of the string.  For clarity: the value returned is the number of
103358 ** bytes in the string, not the number of characters.
103359 **
103360 ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
103361 ** even zero-length strings, are always zero terminated.  The return
103362 ** value from sqlite3_column_blob() for a zero-length blob is an arbitrary
103363 ** pointer, possibly even a NULL pointer.
103364 **
103365 ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
103366 ** but leaves the result in UTF-16 instead of UTF-8.  
103367 ** The zero terminator is not included in this count.
103368 **
103369 ** These routines attempt to convert the value where appropriate.  For
103370 ** example, if the internal representation is FLOAT and a text result
103371 ** is requested, [sqlite3_snprintf()] is used internally to do the conversion
103372 ** automatically.  The following table details the conversions that
103373 ** are applied:
103374 **
103375 ** <blockquote>
103376 ** <table border="1">
103377 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
103378 **
103379 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
103380 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
103381 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
103382 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
103383 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
103384 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
103385 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as for INTEGER->TEXT
103386 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
103387 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
103388 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
103389 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
103390 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
103391 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
103392 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
103393 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
103394 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
103395 ** </table>
103396 ** </blockquote>
103397 **
103398 ** The table above makes reference to standard C library functions atoi()
103399 ** and atof().  SQLite does not really use these functions.  It has its
103400 ** on equavalent internal routines.  The atoi() and atof() names are
103401 ** used in the table for brevity and because they are familiar to most
103402 ** C programmers.
103403 **
103404 ** Note that when type conversions occur, pointers returned by prior
103405 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
103406 ** sqlite3_column_text16() may be invalidated. 
103407 ** Type conversions and pointer invalidations might occur
103408 ** in the following cases:
103409 **
103410 ** <ul>
103411 ** <li><p>  The initial content is a BLOB and sqlite3_column_text() 
103412 **          or sqlite3_column_text16() is called.  A zero-terminator might
103413 **          need to be added to the string.</p></li>
103414 **
103415 ** <li><p>  The initial content is UTF-8 text and sqlite3_column_bytes16() or
103416 **          sqlite3_column_text16() is called.  The content must be converted
103417 **          to UTF-16.</p></li>
103418 **
103419 ** <li><p>  The initial content is UTF-16 text and sqlite3_column_bytes() or
103420 **          sqlite3_column_text() is called.  The content must be converted
103421 **          to UTF-8.</p></li>
103422 ** </ul>
103423 **
103424 ** Conversions between UTF-16be and UTF-16le are always done in place and do
103425 ** not invalidate a prior pointer, though of course the content of the buffer
103426 ** that the prior pointer points to will have been modified.  Other kinds
103427 ** of conversion are done in place when it is possible, but sometime it is
103428 ** not possible and in those cases prior pointers are invalidated.  
103429 **
103430 ** The safest and easiest to remember policy is to invoke these routines
103431 ** in one of the following ways:
103432 **
103433 **  <ul>
103434 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
103435 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
103436 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
103437 **  </ul>
103438 **
103439 ** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(),
103440 ** or sqlite3_column_text16() first to force the result into the desired
103441 ** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to
103442 ** find the size of the result.  Do not mix call to sqlite3_column_text() or
103443 ** sqlite3_column_blob() with calls to sqlite3_column_bytes16().  And do not
103444 ** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes().
103445 **
103446 ** The pointers returned are valid until a type conversion occurs as
103447 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
103448 ** [sqlite3_finalize()] is called.  The memory space used to hold strings
103449 ** and blobs is freed automatically.  Do <b>not</b> pass the pointers returned
103450 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into 
103451 ** [sqlite3_free()].
103452 **
103453 ** If a memory allocation error occurs during the evaluation of any
103454 ** of these routines, a default value is returned.  The default value
103455 ** is either the integer 0, the floating point number 0.0, or a NULL
103456 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
103457 ** [SQLITE_NOMEM].
103458 */
103459 const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
103460 int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
103461 int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
103462 double sqlite3_column_double(sqlite3_stmt*, int iCol);
103463 int sqlite3_column_int(sqlite3_stmt*, int iCol);
103464 sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
103465 const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
103466 const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
103467 int sqlite3_column_type(sqlite3_stmt*, int iCol);
103468 sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
103469
103470 /*
103471 ** CAPI3REF: Destroy A Prepared Statement Object {F13300}
103472 **
103473 ** The sqlite3_finalize() function is called to delete a 
103474 ** [sqlite3_stmt | compiled SQL statement]. If the statement was
103475 ** executed successfully, or not executed at all, then SQLITE_OK is returned.
103476 ** If execution of the statement failed then an 
103477 ** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code]
103478 ** is returned. 
103479 **
103480 ** This routine can be called at any point during the execution of the
103481 ** [sqlite3_stmt | virtual machine].  If the virtual machine has not 
103482 ** completed execution when this routine is called, that is like
103483 ** encountering an error or an interrupt.  (See [sqlite3_interrupt()].) 
103484 ** Incomplete updates may be rolled back and transactions cancelled,  
103485 ** depending on the circumstances, and the 
103486 ** [SQLITE_ERROR | result code] returned will be [SQLITE_ABORT].
103487 */
103488 int sqlite3_finalize(sqlite3_stmt *pStmt);
103489
103490 /*
103491 ** CAPI3REF: Reset A Prepared Statement Object {F13330}
103492 **
103493 ** The sqlite3_reset() function is called to reset a 
103494 ** [sqlite3_stmt | compiled SQL statement] object.
103495 ** back to its initial state, ready to be re-executed.
103496 ** Any SQL statement variables that had values bound to them using
103497 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
103498 ** Use [sqlite3_clear_bindings()] to reset the bindings.
103499 */
103500 int sqlite3_reset(sqlite3_stmt *pStmt);
103501
103502 /*
103503 ** CAPI3REF: Create Or Redefine SQL Functions {F16100}
103504 **
103505 ** The following two functions are used to add SQL functions or aggregates
103506 ** or to redefine the behavior of existing SQL functions or aggregates.  The
103507 ** difference only between the two is that the second parameter, the
103508 ** name of the (scalar) function or aggregate, is encoded in UTF-8 for
103509 ** sqlite3_create_function() and UTF-16 for sqlite3_create_function16().
103510 **
103511 ** The first argument is the [sqlite3 | database handle] that holds the
103512 ** SQL function or aggregate is to be added or redefined. If a single
103513 ** program uses more than one database handle internally, then SQL
103514 ** functions or aggregates must be added individually to each database
103515 ** handle with which they will be used.
103516 **
103517 ** The second parameter is the name of the SQL function to be created
103518 ** or redefined.
103519 ** The length of the name is limited to 255 bytes, exclusive of the 
103520 ** zero-terminator.  Note that the name length limit is in bytes, not
103521 ** characters.  Any attempt to create a function with a longer name
103522 ** will result in an SQLITE_ERROR error.
103523 **
103524 ** The third parameter is the number of arguments that the SQL function or
103525 ** aggregate takes. If this parameter is negative, then the SQL function or
103526 ** aggregate may take any number of arguments.
103527 **
103528 ** The fourth parameter, eTextRep, specifies what 
103529 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
103530 ** its parameters.  Any SQL function implementation should be able to work
103531 ** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
103532 ** more efficient with one encoding than another.  It is allowed to
103533 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
103534 ** times with the same function but with different values of eTextRep.
103535 ** When multiple implementations of the same function are available, SQLite
103536 ** will pick the one that involves the least amount of data conversion.
103537 ** If there is only a single implementation which does not care what
103538 ** text encoding is used, then the fourth argument should be
103539 ** [SQLITE_ANY].
103540 **
103541 ** The fifth parameter is an arbitrary pointer.  The implementation
103542 ** of the function can gain access to this pointer using
103543 ** [sqlite3_user_data()].
103544 **
103545 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
103546 ** pointers to C-language functions that implement the SQL
103547 ** function or aggregate. A scalar SQL function requires an implementation of
103548 ** the xFunc callback only, NULL pointers should be passed as the xStep
103549 ** and xFinal parameters. An aggregate SQL function requires an implementation
103550 ** of xStep and xFinal and NULL should be passed for xFunc. To delete an
103551 ** existing SQL function or aggregate, pass NULL for all three function
103552 ** callback.
103553 **
103554 ** It is permitted to register multiple implementations of the same
103555 ** functions with the same name but with either differing numbers of
103556 ** arguments or differing perferred text encodings.  SQLite will use
103557 ** the implementation most closely matches the way in which the
103558 ** SQL function is used.
103559 */
103560 int sqlite3_create_function(
103561   sqlite3 *,
103562   const char *zFunctionName,
103563   int nArg,
103564   int eTextRep,
103565   void*,
103566   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
103567   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
103568   void (*xFinal)(sqlite3_context*)
103569 );
103570 int sqlite3_create_function16(
103571   sqlite3*,
103572   const void *zFunctionName,
103573   int nArg,
103574   int eTextRep,
103575   void*,
103576   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
103577   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
103578   void (*xFinal)(sqlite3_context*)
103579 );
103580
103581 /*
103582 ** CAPI3REF: Text Encodings {F10267}
103583 **
103584 ** These constant define integer codes that represent the various
103585 ** text encodings supported by SQLite.
103586 */
103587 #define SQLITE_UTF8           1
103588 #define SQLITE_UTF16LE        2
103589 #define SQLITE_UTF16BE        3
103590 #define SQLITE_UTF16          4    /* Use native byte order */
103591 #define SQLITE_ANY            5    /* sqlite3_create_function only */
103592 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
103593
103594 /*
103595 ** CAPI3REF: Obsolete Functions
103596 **
103597 ** These functions are all now obsolete.  In order to maintain
103598 ** backwards compatibility with older code, we continue to support
103599 ** these functions.  However, new development projects should avoid
103600 ** the use of these functions.  To help encourage people to avoid
103601 ** using these functions, we are not going to tell you want they do.
103602 */
103603 int sqlite3_aggregate_count(sqlite3_context*);
103604 int sqlite3_expired(sqlite3_stmt*);
103605 int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
103606 int sqlite3_global_recover(void);
103607 void sqlite3_thread_cleanup(void);
103608 int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
103609
103610 /*
103611 ** CAPI3REF: Obtaining SQL Function Parameter Values {F15100}
103612 **
103613 ** The C-language implementation of SQL functions and aggregates uses
103614 ** this set of interface routines to access the parameter values on
103615 ** the function or aggregate.
103616 **
103617 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
103618 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
103619 ** define callbacks that implement the SQL functions and aggregates.
103620 ** The 4th parameter to these callbacks is an array of pointers to
103621 ** [sqlite3_value] objects.  There is one [sqlite3_value] object for
103622 ** each parameter to the SQL function.  These routines are used to
103623 ** extract values from the [sqlite3_value] objects.
103624 **
103625 ** These routines work just like the corresponding 
103626 ** [sqlite3_column_blob | sqlite3_column_* routines] except that 
103627 ** these routines take a single [sqlite3_value*] pointer instead
103628 ** of an [sqlite3_stmt*] pointer and an integer column number.
103629 **
103630 ** The sqlite3_value_text16() interface extracts a UTF16 string
103631 ** in the native byte-order of the host machine.  The
103632 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
103633 ** extract UTF16 strings as big-endian and little-endian respectively.
103634 **
103635 ** The sqlite3_value_numeric_type() interface attempts to apply
103636 ** numeric affinity to the value.  This means that an attempt is
103637 ** made to convert the value to an integer or floating point.  If
103638 ** such a conversion is possible without loss of information (in other
103639 ** words if the value is a string that looks like a number)
103640 ** then the conversion is done.  Otherwise no conversion occurs.  The 
103641 ** [SQLITE_INTEGER | datatype] after conversion is returned.
103642 **
103643 ** Please pay particular attention to the fact that the pointer that
103644 ** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or
103645 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
103646 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
103647 ** or [sqlite3_value_text16()].  
103648 **
103649 ** These routines must be called from the same thread as
103650 ** the SQL function that supplied the sqlite3_value* parameters.
103651 ** Or, if the sqlite3_value* argument comes from the [sqlite3_column_value()]
103652 ** interface, then these routines should be called from the same thread
103653 ** that ran [sqlite3_column_value()].
103654 **
103655 */
103656 const void *sqlite3_value_blob(sqlite3_value*);
103657 int sqlite3_value_bytes(sqlite3_value*);
103658 int sqlite3_value_bytes16(sqlite3_value*);
103659 double sqlite3_value_double(sqlite3_value*);
103660 int sqlite3_value_int(sqlite3_value*);
103661 sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
103662 const unsigned char *sqlite3_value_text(sqlite3_value*);
103663 const void *sqlite3_value_text16(sqlite3_value*);
103664 const void *sqlite3_value_text16le(sqlite3_value*);
103665 const void *sqlite3_value_text16be(sqlite3_value*);
103666 int sqlite3_value_type(sqlite3_value*);
103667 int sqlite3_value_numeric_type(sqlite3_value*);
103668
103669 /*
103670 ** CAPI3REF: Obtain Aggregate Function Context {F16210}
103671 **
103672 ** The implementation of aggregate SQL functions use this routine to allocate
103673 ** a structure for storing their state.  
103674 ** {F16211} The first time the sqlite3_aggregate_context() routine is
103675 ** is called for a particular aggregate, SQLite allocates nBytes of memory
103676 ** zeros that memory, and returns a pointer to it.
103677 ** {F16212} On second and subsequent calls to sqlite3_aggregate_context()
103678 ** for the same aggregate function index, the same buffer is returned. {END}
103679 ** The implementation
103680 ** of the aggregate can use the returned buffer to accumulate data.
103681 **
103682 ** {F16213} SQLite automatically frees the allocated buffer when the aggregate
103683 ** query concludes. {END}
103684 **
103685 ** The first parameter should be a copy of the 
103686 ** [sqlite3_context | SQL function context] that is the first
103687 ** parameter to the callback routine that implements the aggregate
103688 ** function.
103689 **
103690 ** This routine must be called from the same thread in which
103691 ** the aggregate SQL function is running.
103692 */
103693 void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
103694
103695 /*
103696 ** CAPI3REF: User Data For Functions {F16240}
103697 **
103698 ** {F16241} The sqlite3_user_data() interface returns a copy of
103699 ** the pointer that was the pUserData parameter (the 5th parameter)
103700 ** of the the [sqlite3_create_function()]
103701 ** and [sqlite3_create_function16()] routines that originally
103702 ** registered the application defined function. {END}
103703 **
103704 ** {U16243} This routine must be called from the same thread in which
103705 ** the application-defined function is running.
103706 */
103707 void *sqlite3_user_data(sqlite3_context*);
103708
103709 /*
103710 ** CAPI3REF: Function Auxiliary Data {F16270}
103711 **
103712 ** The following two functions may be used by scalar SQL functions to
103713 ** associate meta-data with argument values. If the same value is passed to
103714 ** multiple invocations of the same SQL function during query execution, under
103715 ** some circumstances the associated meta-data may be preserved. This may
103716 ** be used, for example, to add a regular-expression matching scalar
103717 ** function. The compiled version of the regular expression is stored as
103718 ** meta-data associated with the SQL value passed as the regular expression
103719 ** pattern.  The compiled regular expression can be reused on multiple
103720 ** invocations of the same function so that the original pattern string
103721 ** does not need to be recompiled on each invocation.
103722 **
103723 ** {F16271}
103724 ** The sqlite3_get_auxdata() interface returns a pointer to the meta-data
103725 ** associated by the sqlite3_set_auxdata() function with the Nth argument
103726 ** value to the application-defined function.
103727 ** {F16272} If no meta-data has been ever been set for the Nth
103728 ** argument of the function, or if the cooresponding function parameter
103729 ** has changed since the meta-data was set, then sqlite3_get_auxdata()
103730 ** returns a NULL pointer.
103731 **
103732 ** {F16275} The sqlite3_set_auxdata() interface saves the meta-data
103733 ** pointed to by its 3rd parameter as the meta-data for the N-th
103734 ** argument of the application-defined function. {END} Subsequent
103735 ** calls to sqlite3_get_auxdata() might return this data, if it has
103736 ** not been destroyed. 
103737 ** {F16277} If it is not NULL, SQLite will invoke the destructor 
103738 ** function given by the 4th parameter to sqlite3_set_auxdata() on
103739 ** the meta-data when the corresponding function parameter changes
103740 ** or when the SQL statement completes, whichever comes first. {END}
103741 **
103742 ** In practice, meta-data is preserved between function calls for
103743 ** expressions that are constant at compile time. This includes literal
103744 ** values and SQL variables.
103745 **
103746 ** These routines must be called from the same thread in which
103747 ** the SQL function is running.
103748 */
103749 void *sqlite3_get_auxdata(sqlite3_context*, int N);
103750 void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
103751
103752
103753 /*
103754 ** CAPI3REF: Constants Defining Special Destructor Behavior {F10280}
103755 **
103756 ** These are special value for the destructor that is passed in as the
103757 ** final argument to routines like [sqlite3_result_blob()].  If the destructor
103758 ** argument is SQLITE_STATIC, it means that the content pointer is constant
103759 ** and will never change.  It does not need to be destroyed.  The 
103760 ** SQLITE_TRANSIENT value means that the content will likely change in
103761 ** the near future and that SQLite should make its own private copy of
103762 ** the content before returning.
103763 **
103764 ** The typedef is necessary to work around problems in certain
103765 ** C++ compilers.  See ticket #2191.
103766 */
103767 typedef void (*sqlite3_destructor_type)(void*);
103768 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
103769 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
103770
103771 /*
103772 ** CAPI3REF: Setting The Result Of An SQL Function {F16400}
103773 **
103774 ** These routines are used by the xFunc or xFinal callbacks that
103775 ** implement SQL functions and aggregates.  See
103776 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
103777 ** for additional information.
103778 **
103779 ** These functions work very much like the 
103780 ** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used
103781 ** to bind values to host parameters in prepared statements.
103782 ** Refer to the
103783 ** [sqlite3_bind_blob | sqlite3_bind_* documentation] for
103784 ** additional information.
103785 **
103786 ** {F16402} The sqlite3_result_blob() interface sets the result from
103787 ** an application defined function to be the BLOB whose content is pointed
103788 ** to by the second parameter and which is N bytes long where N is the
103789 ** third parameter. 
103790 ** {F16403} The sqlite3_result_zeroblob() inerfaces set the result of
103791 ** the application defined function to be a BLOB containing all zero
103792 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
103793 **
103794 ** {F16407} The sqlite3_result_double() interface sets the result from
103795 ** an application defined function to be a floating point value specified
103796 ** by its 2nd argument.
103797 **
103798 ** {F16409} The sqlite3_result_error() and sqlite3_result_error16() functions
103799 ** cause the implemented SQL function to throw an exception.
103800 ** {F16411} SQLite uses the string pointed to by the
103801 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
103802 ** as the text of an error message. {F16412} SQLite interprets the error
103803 ** message string from sqlite3_result_error() as UTF8.  {F16413} SQLite
103804 ** interprets the string from sqlite3_result_error16() as UTF16 in native
103805 ** byte order.  {F16414} If the third parameter to sqlite3_result_error()
103806 ** or sqlite3_result_error16() is negative then SQLite takes as the error
103807 ** message all text up through the first zero character.
103808 ** {F16415} If the third parameter to sqlite3_result_error() or
103809 ** sqlite3_result_error16() is non-negative then SQLite takes that many
103810 ** bytes (not characters) from the 2nd parameter as the error message.
103811 ** {F16417} The sqlite3_result_error() and sqlite3_result_error16()
103812 ** routines make a copy private copy of the error message text before
103813 ** they return.  {END} Hence, the calling function can deallocate or
103814 ** modify the text after they return without harm.
103815 **
103816 ** {F16421} The sqlite3_result_toobig() interface causes SQLite
103817 ** to throw an error indicating that a string or BLOB is to long
103818 ** to represent.  {F16422} The sqlite3_result_nomem() interface
103819 ** causes SQLite to throw an exception indicating that the a
103820 ** memory allocation failed.
103821 **
103822 ** {F16431} The sqlite3_result_int() interface sets the return value
103823 ** of the application-defined function to be the 32-bit signed integer
103824 ** value given in the 2nd argument.
103825 ** {F16432} The sqlite3_result_int64() interface sets the return value
103826 ** of the application-defined function to be the 64-bit signed integer
103827 ** value given in the 2nd argument.
103828 **
103829 ** {F16437} The sqlite3_result_null() interface sets the return value
103830 ** of the application-defined function to be NULL.
103831 **
103832 ** {F16441} The sqlite3_result_text(), sqlite3_result_text16(), 
103833 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
103834 ** set the return value of the application-defined function to be
103835 ** a text string which is represented as UTF-8, UTF-16 native byte order,
103836 ** UTF-16 little endian, or UTF-16 big endian, respectively.
103837 ** {F16442} SQLite takes the text result from the application from
103838 ** the 2nd parameter of the sqlite3_result_text* interfaces.
103839 ** {F16444} If the 3rd parameter to the sqlite3_result_text* interfaces
103840 ** is negative, then SQLite takes result text from the 2nd parameter 
103841 ** through the first zero character.
103842 ** {F16447} If the 3rd parameter to the sqlite3_result_text* interfaces
103843 ** is non-negative, then as many bytes (not characters) of the text
103844 ** pointed to by the 2nd parameter are taken as the application-defined
103845 ** function result.
103846 ** {F16451} If the 4th parameter to the sqlite3_result_text* interfaces
103847 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
103848 ** function as the destructor on the text or blob result when it has
103849 ** finished using that result.
103850 ** {F16453} If the 4th parameter to the sqlite3_result_text* interfaces
103851 ** or sqlite3_result_blob is the special constant SQLITE_STATIC, then
103852 ** SQLite assumes that the text or blob result is constant space and
103853 ** does not copy the space or call a destructor when it has
103854 ** finished using that result.
103855 ** {F16454} If the 4th parameter to the sqlite3_result_text* interfaces
103856 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
103857 ** then SQLite makes a copy of the result into space obtained from
103858 ** from [sqlite3_malloc()] before it returns.
103859 **
103860 ** {F16461} The sqlite3_result_value() interface sets the result of
103861 ** the application-defined function to be a copy the [sqlite3_value]
103862 ** object specified by the 2nd parameter.  {F16463} The
103863 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
103864 ** so that [sqlite3_value] specified in the parameter may change or
103865 ** be deallocated after sqlite3_result_value() returns without harm.
103866 **
103867 ** {U16491} These routines are called from within the different thread 
103868 ** than the one containing the application-defined function that recieved
103869 ** the [sqlite3_context] pointer, the results are undefined.
103870 */
103871 void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
103872 void sqlite3_result_double(sqlite3_context*, double);
103873 void sqlite3_result_error(sqlite3_context*, const char*, int);
103874 void sqlite3_result_error16(sqlite3_context*, const void*, int);
103875 void sqlite3_result_error_toobig(sqlite3_context*);
103876 void sqlite3_result_error_nomem(sqlite3_context*);
103877 void sqlite3_result_int(sqlite3_context*, int);
103878 void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
103879 void sqlite3_result_null(sqlite3_context*);
103880 void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
103881 void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
103882 void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
103883 void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
103884 void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
103885 void sqlite3_result_zeroblob(sqlite3_context*, int n);
103886
103887 /*
103888 ** CAPI3REF: Define New Collating Sequences {F16600}
103889 **
103890 ** {F16601}
103891 ** These functions are used to add new collation sequences to the
103892 ** [sqlite3*] handle specified as the first argument. 
103893 **
103894 ** {F16602}
103895 ** The name of the new collation sequence is specified as a UTF-8 string
103896 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
103897 ** and a UTF-16 string for sqlite3_create_collation16(). {F16603} In all cases
103898 ** the name is passed as the second function argument.
103899 **
103900 ** {F16604}
103901 ** The third argument may be one of the constants [SQLITE_UTF8],
103902 ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
103903 ** routine expects to be passed pointers to strings encoded using UTF-8,
103904 ** UTF-16 little-endian or UTF-16 big-endian respectively. {F16605} The
103905 ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that
103906 ** the routine expects pointers to 16-bit word aligned strings
103907 ** of UTF16 in the native byte order of the host computer.
103908 **
103909 ** {F16607}
103910 ** A pointer to the user supplied routine must be passed as the fifth
103911 ** argument. {F16609} If it is NULL, this is the same as deleting the collation
103912 ** sequence (so that SQLite cannot call it anymore).
103913 ** {F16611} Each time the application
103914 ** supplied function is invoked, it is passed a copy of the void* passed as
103915 ** the fourth argument to sqlite3_create_collation() or
103916 ** sqlite3_create_collation16() as its first parameter.
103917 **
103918 ** {F16612}
103919 ** The remaining arguments to the application-supplied routine are two strings,
103920 ** each represented by a [length, data] pair and encoded in the encoding
103921 ** that was passed as the third argument when the collation sequence was
103922 ** registered. {END} The application defined collation routine should
103923 ** return negative, zero or positive if
103924 ** the first string is less than, equal to, or greater than the second
103925 ** string. i.e. (STRING1 - STRING2).
103926 **
103927 ** {F16615}
103928 ** The sqlite3_create_collation_v2() works like sqlite3_create_collation()
103929 ** excapt that it takes an extra argument which is a destructor for
103930 ** the collation.  {F16617} The destructor is called when the collation is
103931 ** destroyed and is passed a copy of the fourth parameter void* pointer
103932 ** of the sqlite3_create_collation_v2().
103933 ** {F16618}  Collations are destroyed when
103934 ** they are overridden by later calls to the collation creation functions
103935 ** or when the [sqlite3*] database handle is closed using [sqlite3_close()].
103936 */
103937 int sqlite3_create_collation(
103938   sqlite3*, 
103939   const char *zName, 
103940   int eTextRep, 
103941   void*,
103942   int(*xCompare)(void*,int,const void*,int,const void*)
103943 );
103944 int sqlite3_create_collation_v2(
103945   sqlite3*, 
103946   const char *zName, 
103947   int eTextRep, 
103948   void*,
103949   int(*xCompare)(void*,int,const void*,int,const void*),
103950   void(*xDestroy)(void*)
103951 );
103952 int sqlite3_create_collation16(
103953   sqlite3*, 
103954   const char *zName, 
103955   int eTextRep, 
103956   void*,
103957   int(*xCompare)(void*,int,const void*,int,const void*)
103958 );
103959
103960 /*
103961 ** CAPI3REF: Collation Needed Callbacks {F16700}
103962 **
103963 ** {F16701}
103964 ** To avoid having to register all collation sequences before a database
103965 ** can be used, a single callback function may be registered with the
103966 ** database handle to be called whenever an undefined collation sequence is
103967 ** required.
103968 **
103969 ** {F16702}
103970 ** If the function is registered using the sqlite3_collation_needed() API,
103971 ** then it is passed the names of undefined collation sequences as strings
103972 ** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, the names
103973 ** are passed as UTF-16 in machine native byte order. {F16704} A call to either
103974 ** function replaces any existing callback.
103975 **
103976 ** {F16705} When the callback is invoked, the first argument passed is a copy
103977 ** of the second argument to sqlite3_collation_needed() or
103978 ** sqlite3_collation_needed16(). {F16706} The second argument is the database
103979 ** handle.  {F16707} The third argument is one of [SQLITE_UTF8],
103980 ** [SQLITE_UTF16BE], or [SQLITE_UTF16LE], indicating the most
103981 ** desirable form of the collation sequence function required.
103982 ** {F16708} The fourth parameter is the name of the
103983 ** required collation sequence. {END}
103984 **
103985 ** The callback function should register the desired collation using
103986 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
103987 ** [sqlite3_create_collation_v2()].
103988 */
103989 int sqlite3_collation_needed(
103990   sqlite3*, 
103991   void*, 
103992   void(*)(void*,sqlite3*,int eTextRep,const char*)
103993 );
103994 int sqlite3_collation_needed16(
103995   sqlite3*, 
103996   void*,
103997   void(*)(void*,sqlite3*,int eTextRep,const void*)
103998 );
103999
104000 /*
104001 ** Specify the key for an encrypted database.  This routine should be
104002 ** called right after sqlite3_open().
104003 **
104004 ** The code to implement this API is not available in the public release
104005 ** of SQLite.
104006 */
104007 int sqlite3_key(
104008   sqlite3 *db,                   /* Database to be rekeyed */
104009   const void *pKey, int nKey     /* The key */
104010 );
104011
104012 /*
104013 ** Change the key on an open database.  If the current database is not
104014 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
104015 ** database is decrypted.
104016 **
104017 ** The code to implement this API is not available in the public release
104018 ** of SQLite.
104019 */
104020 int sqlite3_rekey(
104021   sqlite3 *db,                   /* Database to be rekeyed */
104022   const void *pKey, int nKey     /* The new key */
104023 );
104024
104025 /*
104026 ** CAPI3REF:  Suspend Execution For A Short Time {F10530}
104027 **
104028 ** {F10531} The sqlite3_sleep() function
104029 ** causes the current thread to suspend execution
104030 ** for at least a number of milliseconds specified in its parameter.
104031 **
104032 ** {F10532} If the operating system does not support sleep requests with 
104033 ** millisecond time resolution, then the time will be rounded up to 
104034 ** the nearest second. {F10533} The number of milliseconds of sleep actually 
104035 ** requested from the operating system is returned.
104036 **
104037 ** {F10534} SQLite implements this interface by calling the xSleep()
104038 ** method of the default [sqlite3_vfs] object. {END}
104039 */
104040 int sqlite3_sleep(int);
104041
104042 /*
104043 ** CAPI3REF:  Name Of The Folder Holding Temporary Files {F10310}
104044 **
104045 ** If this global variable is made to point to a string which is
104046 ** the name of a folder (a.ka. directory), then all temporary files
104047 ** created by SQLite will be placed in that directory.  If this variable
104048 ** is NULL pointer, then SQLite does a search for an appropriate temporary
104049 ** file directory.
104050 **
104051 ** It is not safe to modify this variable once a database connection
104052 ** has been opened.  It is intended that this variable be set once
104053 ** as part of process initialization and before any SQLite interface
104054 ** routines have been call and remain unchanged thereafter.
104055 */
104056 SQLITE_EXTERN char *sqlite3_temp_directory;
104057
104058 /*
104059 ** CAPI3REF:  Test To See If The Database Is In Auto-Commit Mode {F12930}
104060 **
104061 ** {F12931} The sqlite3_get_autocommit() interfaces returns non-zero or
104062 ** zero if the given database connection is or is not in autocommit mode,
104063 ** respectively. {F12932}  Autocommit mode is on
104064 ** by default.  {F12933} Autocommit mode is disabled by a BEGIN statement.
104065 ** {F12934} Autocommit mode is reenabled by a COMMIT or ROLLBACK. {END}
104066 **
104067 ** If certain kinds of errors occur on a statement within a multi-statement
104068 ** transactions (errors including [SQLITE_FULL], [SQLITE_IOERR], 
104069 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
104070 ** transaction might be rolled back automatically.  {F12935} The only way to
104071 ** find out if SQLite automatically rolled back the transaction after
104072 ** an error is to use this function. {END}
104073 **
104074 ** {U12936} If another thread changes the autocommit status of the database
104075 ** connection while this routine is running, then the return value
104076 ** is undefined. {END}
104077 */
104078 int sqlite3_get_autocommit(sqlite3*);
104079
104080 /*
104081 ** CAPI3REF:  Find The Database Handle Of A Prepared Statement {F13120}
104082 **
104083 ** {F13121} The sqlite3_db_handle interface
104084 ** returns the [sqlite3*] database handle to which a
104085 ** [sqlite3_stmt | prepared statement] belongs.
104086 ** {F13122} the database handle returned by sqlite3_db_handle
104087 ** is the same database handle that was
104088 ** the first argument to the [sqlite3_prepare_v2()] or its variants
104089 ** that was used to create the statement in the first place.
104090 */
104091 sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
104092
104093
104094 /*
104095 ** CAPI3REF: Commit And Rollback Notification Callbacks {F12950}
104096 **
104097 ** {F12951} The sqlite3_commit_hook() interface registers a callback
104098 ** function to be invoked whenever a transaction is committed.
104099 ** {F12952} Any callback set by a previous call to sqlite3_commit_hook()
104100 ** for the same database connection is overridden.
104101 ** {F12953} The sqlite3_rollback_hook() interface registers a callback
104102 ** function to be invoked whenever a transaction is committed.
104103 ** {F12954} Any callback set by a previous call to sqlite3_commit_hook()
104104 ** for the same database connection is overridden.
104105 ** {F12956} The pArg argument is passed through
104106 ** to the callback.  {F12957} If the callback on a commit hook function 
104107 ** returns non-zero, then the commit is converted into a rollback.
104108 **
104109 ** {F12958} If another function was previously registered, its
104110 ** pArg value is returned.  Otherwise NULL is returned.
104111 **
104112 ** {F12959} Registering a NULL function disables the callback.
104113 **
104114 ** {F12961} For the purposes of this API, a transaction is said to have been 
104115 ** rolled back if an explicit "ROLLBACK" statement is executed, or
104116 ** an error or constraint causes an implicit rollback to occur.
104117 ** {F12962} The rollback callback is not invoked if a transaction is
104118 ** automatically rolled back because the database connection is closed.
104119 ** {F12964} The rollback callback is not invoked if a transaction is
104120 ** rolled back because a commit callback returned non-zero.
104121 ** <todo> Check on this </todo> {END}
104122 **
104123 ** These are experimental interfaces and are subject to change.
104124 */
104125 void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
104126 void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
104127
104128 /*
104129 ** CAPI3REF: Data Change Notification Callbacks {F12970}
104130 **
104131 ** {F12971} The sqlite3_update_hook() interface
104132 ** registers a callback function with the database connection identified by the 
104133 ** first argument to be invoked whenever a row is updated, inserted or deleted.
104134 ** {F12972} Any callback set by a previous call to this function for the same 
104135 ** database connection is overridden.
104136 **
104137 ** {F12974} The second argument is a pointer to the function to invoke when a 
104138 ** row is updated, inserted or deleted. 
104139 ** {F12976} The first argument to the callback is
104140 ** a copy of the third argument to sqlite3_update_hook().
104141 ** {F12977} The second callback 
104142 ** argument is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
104143 ** depending on the operation that caused the callback to be invoked.
104144 ** {F12978} The third and 
104145 ** fourth arguments to the callback contain pointers to the database and 
104146 ** table name containing the affected row.
104147 ** {F12979} The final callback parameter is 
104148 ** the rowid of the row.
104149 ** {F12981} In the case of an update, this is the rowid after 
104150 ** the update takes place.
104151 **
104152 ** {F12983} The update hook is not invoked when internal system tables are
104153 ** modified (i.e. sqlite_master and sqlite_sequence).
104154 **
104155 ** {F12984} If another function was previously registered, its pArg value
104156 ** is returned.  {F12985} Otherwise NULL is returned.
104157 */
104158 void *sqlite3_update_hook(
104159   sqlite3*, 
104160   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
104161   void*
104162 );
104163
104164 /*
104165 ** CAPI3REF:  Enable Or Disable Shared Pager Cache {F10330}
104166 **
104167 ** {F10331}
104168 ** This routine enables or disables the sharing of the database cache
104169 ** and schema data structures between connections to the same database.
104170 ** {F10332}
104171 ** Sharing is enabled if the argument is true and disabled if the argument
104172 ** is false.
104173 **
104174 ** {F10333} Cache sharing is enabled and disabled
104175 ** for an entire process. {END} This is a change as of SQLite version 3.5.0.
104176 ** In prior versions of SQLite, sharing was
104177 ** enabled or disabled for each thread separately.
104178 **
104179 ** {F10334}
104180 ** The cache sharing mode set by this interface effects all subsequent
104181 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
104182 ** {F10335} Existing database connections continue use the sharing mode
104183 ** that was in effect at the time they were opened. {END}
104184 **
104185 ** Virtual tables cannot be used with a shared cache.  {F10336} When shared
104186 ** cache is enabled, the [sqlite3_create_module()] API used to register
104187 ** virtual tables will always return an error. {END}
104188 **
104189 ** {F10337} This routine returns [SQLITE_OK] if shared cache was
104190 ** enabled or disabled successfully.  {F10338} An [SQLITE_ERROR | error code]
104191 ** is returned otherwise. {END}
104192 **
104193 ** {F10339} Shared cache is disabled by default. {END} But this might change in
104194 ** future releases of SQLite.  Applications that care about shared
104195 ** cache setting should set it explicitly.
104196 */
104197 int sqlite3_enable_shared_cache(int);
104198
104199 /*
104200 ** CAPI3REF:  Attempt To Free Heap Memory {F17340}
104201 **
104202 ** {F17341} The sqlite3_release_memory() interface attempts to
104203 ** free N bytes of heap memory by deallocating non-essential memory
104204 ** allocations held by the database labrary. {END}  Memory used
104205 ** to cache database pages to improve performance is an example of
104206 ** non-essential memory.  {F16342} sqlite3_release_memory() returns
104207 ** the number of bytes actually freed, which might be more or less
104208 ** than the amount requested.
104209 */
104210 int sqlite3_release_memory(int);
104211
104212 /*
104213 ** CAPI3REF:  Impose A Limit On Heap Size {F17350}
104214 **
104215 ** {F16351} The sqlite3_soft_heap_limit() interface
104216 ** places a "soft" limit on the amount of heap memory that may be allocated
104217 ** by SQLite. {F16352} If an internal allocation is requested 
104218 ** that would exceed the soft heap limit, [sqlite3_release_memory()] is
104219 ** invoked one or more times to free up some space before the allocation
104220 ** is made. {END}
104221 **
104222 ** {F16353} The limit is called "soft", because if
104223 ** [sqlite3_release_memory()] cannot
104224 ** free sufficient memory to prevent the limit from being exceeded,
104225 ** the memory is allocated anyway and the current operation proceeds.
104226 **
104227 ** {F16354}
104228 ** A negative or zero value for N means that there is no soft heap limit and
104229 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
104230 ** {F16355} The default value for the soft heap limit is zero.
104231 **
104232 ** SQLite makes a best effort to honor the soft heap limit.  
104233 ** {F16356} But if the soft heap limit cannot honored, execution will
104234 ** continue without error or notification. {END}  This is why the limit is 
104235 ** called a "soft" limit.  It is advisory only.
104236 **
104237 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
104238 ** allocated by a single thread - the same thread in which this routine
104239 ** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
104240 ** applied to all threads. {F16357} The value specified for the soft heap limit
104241 ** is an upper bound on the total memory allocation for all threads. {END}  In
104242 ** version 3.5.0 there is no mechanism for limiting the heap usage for
104243 ** individual threads.
104244 */
104245 void sqlite3_soft_heap_limit(int);
104246
104247 /*
104248 ** CAPI3REF:  Extract Metadata About A Column Of A Table {F12850}
104249 **
104250 ** This routine
104251 ** returns meta-data about a specific column of a specific database
104252 ** table accessible using the connection handle passed as the first function 
104253 ** argument.
104254 **
104255 ** The column is identified by the second, third and fourth parameters to 
104256 ** this function. The second parameter is either the name of the database
104257 ** (i.e. "main", "temp" or an attached database) containing the specified
104258 ** table or NULL. If it is NULL, then all attached databases are searched
104259 ** for the table using the same algorithm as the database engine uses to 
104260 ** resolve unqualified table references.
104261 **
104262 ** The third and fourth parameters to this function are the table and column 
104263 ** name of the desired column, respectively. Neither of these parameters 
104264 ** may be NULL.
104265 **
104266 ** Meta information is returned by writing to the memory locations passed as
104267 ** the 5th and subsequent parameters to this function. Any of these 
104268 ** arguments may be NULL, in which case the corresponding element of meta 
104269 ** information is ommitted.
104270 **
104271 ** <pre>
104272 ** Parameter     Output Type      Description
104273 ** -----------------------------------
104274 **
104275 **   5th         const char*      Data type
104276 **   6th         const char*      Name of the default collation sequence 
104277 **   7th         int              True if the column has a NOT NULL constraint
104278 **   8th         int              True if the column is part of the PRIMARY KEY
104279 **   9th         int              True if the column is AUTOINCREMENT
104280 ** </pre>
104281 **
104282 **
104283 ** The memory pointed to by the character pointers returned for the 
104284 ** declaration type and collation sequence is valid only until the next 
104285 ** call to any sqlite API function.
104286 **
104287 ** If the specified table is actually a view, then an error is returned.
104288 **
104289 ** If the specified column is "rowid", "oid" or "_rowid_" and an 
104290 ** INTEGER PRIMARY KEY column has been explicitly declared, then the output 
104291 ** parameters are set for the explicitly declared column. If there is no
104292 ** explicitly declared IPK column, then the output parameters are set as 
104293 ** follows:
104294 **
104295 ** <pre>
104296 **     data type: "INTEGER"
104297 **     collation sequence: "BINARY"
104298 **     not null: 0
104299 **     primary key: 1
104300 **     auto increment: 0
104301 ** </pre>
104302 **
104303 ** This function may load one or more schemas from database files. If an
104304 ** error occurs during this process, or if the requested table or column
104305 ** cannot be found, an SQLITE error code is returned and an error message
104306 ** left in the database handle (to be retrieved using sqlite3_errmsg()).
104307 **
104308 ** This API is only available if the library was compiled with the
104309 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
104310 */
104311 int sqlite3_table_column_metadata(
104312   sqlite3 *db,                /* Connection handle */
104313   const char *zDbName,        /* Database name or NULL */
104314   const char *zTableName,     /* Table name */
104315   const char *zColumnName,    /* Column name */
104316   char const **pzDataType,    /* OUTPUT: Declared data type */
104317   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
104318   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
104319   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
104320   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
104321 );
104322
104323 /*
104324 ** CAPI3REF: Load An Extension {F12600}
104325 **
104326 ** {F12601} The sqlite3_load_extension() interface
104327 ** attempts to load an SQLite extension library contained in the file
104328 ** zFile. {F12602} The entry point is zProc. {F12603} zProc may be 0
104329 ** in which case the name of the entry point defaults
104330 ** to "sqlite3_extension_init".
104331 **
104332 ** {F12604} The sqlite3_load_extension() interface shall
104333 ** return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
104334 **
104335 ** {F12605}
104336 ** If an error occurs and pzErrMsg is not 0, then the
104337 ** sqlite3_load_extension() interface shall attempt to fill *pzErrMsg with 
104338 ** error message text stored in memory obtained from [sqlite3_malloc()].
104339 ** {END}  The calling function should free this memory
104340 ** by calling [sqlite3_free()].
104341 **
104342 ** {F12606}
104343 ** Extension loading must be enabled using [sqlite3_enable_load_extension()]
104344 ** prior to calling this API or an error will be returned.
104345 */
104346 int sqlite3_load_extension(
104347   sqlite3 *db,          /* Load the extension into this database connection */
104348   const char *zFile,    /* Name of the shared library containing extension */
104349   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
104350   char **pzErrMsg       /* Put error message here if not 0 */
104351 );
104352
104353 /*
104354 ** CAPI3REF:  Enable Or Disable Extension Loading {F12620}
104355 **
104356 ** So as not to open security holes in older applications that are
104357 ** unprepared to deal with extension loading, and as a means of disabling
104358 ** extension loading while evaluating user-entered SQL, the following
104359 ** API is provided to turn the [sqlite3_load_extension()] mechanism on and
104360 ** off.  {F12622} It is off by default. {END} See ticket #1863.
104361 **
104362 ** {F12621} Call the sqlite3_enable_load_extension() routine
104363 ** with onoff==1 to turn extension loading on
104364 ** and call it with onoff==0 to turn it back off again. {END}
104365 */
104366 int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
104367
104368 /*
104369 ** CAPI3REF: Make Arrangements To Automatically Load An Extension {F12640}
104370 **
104371 ** {F12641} This function
104372 ** registers an extension entry point that is automatically invoked
104373 ** whenever a new database connection is opened using
104374 ** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. {END}
104375 **
104376 ** This API can be invoked at program startup in order to register
104377 ** one or more statically linked extensions that will be available
104378 ** to all new database connections.
104379 **
104380 ** {F12642} Duplicate extensions are detected so calling this routine multiple
104381 ** times with the same extension is harmless.
104382 **
104383 ** {F12643} This routine stores a pointer to the extension in an array
104384 ** that is obtained from sqlite_malloc(). {END} If you run a memory leak
104385 ** checker on your program and it reports a leak because of this
104386 ** array, then invoke [sqlite3_reset_auto_extension()] prior
104387 ** to shutdown to free the memory.
104388 **
104389 ** {F12644} Automatic extensions apply across all threads. {END}
104390 **
104391 ** This interface is experimental and is subject to change or
104392 ** removal in future releases of SQLite.
104393 */
104394 int sqlite3_auto_extension(void *xEntryPoint);
104395
104396
104397 /*
104398 ** CAPI3REF: Reset Automatic Extension Loading {F12660}
104399 **
104400 ** {F12661} This function disables all previously registered
104401 ** automatic extensions. {END}  This
104402 ** routine undoes the effect of all prior [sqlite3_automatic_extension()]
104403 ** calls.
104404 **
104405 ** {F12662} This call disabled automatic extensions in all threads. {END}
104406 **
104407 ** This interface is experimental and is subject to change or
104408 ** removal in future releases of SQLite.
104409 */
104410 void sqlite3_reset_auto_extension(void);
104411
104412
104413 /*
104414 ****** EXPERIMENTAL - subject to change without notice **************
104415 **
104416 ** The interface to the virtual-table mechanism is currently considered
104417 ** to be experimental.  The interface might change in incompatible ways.
104418 ** If this is a problem for you, do not use the interface at this time.
104419 **
104420 ** When the virtual-table mechanism stablizes, we will declare the
104421 ** interface fixed, support it indefinitely, and remove this comment.
104422 */
104423
104424 /*
104425 ** Structures used by the virtual table interface
104426 */
104427 typedef struct sqlite3_vtab sqlite3_vtab;
104428 typedef struct sqlite3_index_info sqlite3_index_info;
104429 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
104430 typedef struct sqlite3_module sqlite3_module;
104431
104432 /*
104433 ** A module is a class of virtual tables.  Each module is defined
104434 ** by an instance of the following structure.  This structure consists
104435 ** mostly of methods for the module.
104436 */
104437 struct sqlite3_module {
104438   int iVersion;
104439   int (*xCreate)(sqlite3*, void *pAux,
104440                int argc, const char *const*argv,
104441                sqlite3_vtab **ppVTab, char**);
104442   int (*xConnect)(sqlite3*, void *pAux,
104443                int argc, const char *const*argv,
104444                sqlite3_vtab **ppVTab, char**);
104445   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
104446   int (*xDisconnect)(sqlite3_vtab *pVTab);
104447   int (*xDestroy)(sqlite3_vtab *pVTab);
104448   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
104449   int (*xClose)(sqlite3_vtab_cursor*);
104450   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
104451                 int argc, sqlite3_value **argv);
104452   int (*xNext)(sqlite3_vtab_cursor*);
104453   int (*xEof)(sqlite3_vtab_cursor*);
104454   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
104455   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
104456   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
104457   int (*xBegin)(sqlite3_vtab *pVTab);
104458   int (*xSync)(sqlite3_vtab *pVTab);
104459   int (*xCommit)(sqlite3_vtab *pVTab);
104460   int (*xRollback)(sqlite3_vtab *pVTab);
104461   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
104462                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
104463                        void **ppArg);
104464
104465   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
104466 };
104467
104468 /*
104469 ** The sqlite3_index_info structure and its substructures is used to
104470 ** pass information into and receive the reply from the xBestIndex
104471 ** method of an sqlite3_module.  The fields under **Inputs** are the
104472 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
104473 ** results into the **Outputs** fields.
104474 **
104475 ** The aConstraint[] array records WHERE clause constraints of the
104476 ** form:
104477 **
104478 **         column OP expr
104479 **
104480 ** Where OP is =, &lt;, &lt;=, &gt;, or &gt;=.  
104481 ** The particular operator is stored
104482 ** in aConstraint[].op.  The index of the column is stored in 
104483 ** aConstraint[].iColumn.  aConstraint[].usable is TRUE if the
104484 ** expr on the right-hand side can be evaluated (and thus the constraint
104485 ** is usable) and false if it cannot.
104486 **
104487 ** The optimizer automatically inverts terms of the form "expr OP column"
104488 ** and makes other simplifications to the WHERE clause in an attempt to
104489 ** get as many WHERE clause terms into the form shown above as possible.
104490 ** The aConstraint[] array only reports WHERE clause terms in the correct
104491 ** form that refer to the particular virtual table being queried.
104492 **
104493 ** Information about the ORDER BY clause is stored in aOrderBy[].
104494 ** Each term of aOrderBy records a column of the ORDER BY clause.
104495 **
104496 ** The xBestIndex method must fill aConstraintUsage[] with information
104497 ** about what parameters to pass to xFilter.  If argvIndex>0 then
104498 ** the right-hand side of the corresponding aConstraint[] is evaluated
104499 ** and becomes the argvIndex-th entry in argv.  If aConstraintUsage[].omit
104500 ** is true, then the constraint is assumed to be fully handled by the
104501 ** virtual table and is not checked again by SQLite.
104502 **
104503 ** The idxNum and idxPtr values are recorded and passed into xFilter.
104504 ** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
104505 **
104506 ** The orderByConsumed means that output from xFilter will occur in
104507 ** the correct order to satisfy the ORDER BY clause so that no separate
104508 ** sorting step is required.
104509 **
104510 ** The estimatedCost value is an estimate of the cost of doing the
104511 ** particular lookup.  A full scan of a table with N entries should have
104512 ** a cost of N.  A binary search of a table of N entries should have a
104513 ** cost of approximately log(N).
104514 */
104515 struct sqlite3_index_info {
104516   /* Inputs */
104517   int nConstraint;           /* Number of entries in aConstraint */
104518   struct sqlite3_index_constraint {
104519      int iColumn;              /* Column on left-hand side of constraint */
104520      unsigned char op;         /* Constraint operator */
104521      unsigned char usable;     /* True if this constraint is usable */
104522      int iTermOffset;          /* Used internally - xBestIndex should ignore */
104523   } *aConstraint;            /* Table of WHERE clause constraints */
104524   int nOrderBy;              /* Number of terms in the ORDER BY clause */
104525   struct sqlite3_index_orderby {
104526      int iColumn;              /* Column number */
104527      unsigned char desc;       /* True for DESC.  False for ASC. */
104528   } *aOrderBy;               /* The ORDER BY clause */
104529
104530   /* Outputs */
104531   struct sqlite3_index_constraint_usage {
104532     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
104533     unsigned char omit;      /* Do not code a test for this constraint */
104534   } *aConstraintUsage;
104535   int idxNum;                /* Number used to identify the index */
104536   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
104537   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
104538   int orderByConsumed;       /* True if output is already ordered */
104539   double estimatedCost;      /* Estimated cost of using this index */
104540 };
104541 #define SQLITE_INDEX_CONSTRAINT_EQ    2
104542 #define SQLITE_INDEX_CONSTRAINT_GT    4
104543 #define SQLITE_INDEX_CONSTRAINT_LE    8
104544 #define SQLITE_INDEX_CONSTRAINT_LT    16
104545 #define SQLITE_INDEX_CONSTRAINT_GE    32
104546 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
104547
104548 /*
104549 ** This routine is used to register a new module name with an SQLite
104550 ** connection.  Module names must be registered before creating new
104551 ** virtual tables on the module, or before using preexisting virtual
104552 ** tables of the module.
104553 */
104554 int sqlite3_create_module(
104555   sqlite3 *db,               /* SQLite connection to register module with */
104556   const char *zName,         /* Name of the module */
104557   const sqlite3_module *,    /* Methods for the module */
104558   void *                     /* Client data for xCreate/xConnect */
104559 );
104560
104561 /*
104562 ** This routine is identical to the sqlite3_create_module() method above,
104563 ** except that it allows a destructor function to be specified. It is
104564 ** even more experimental than the rest of the virtual tables API.
104565 */
104566 int sqlite3_create_module_v2(
104567   sqlite3 *db,               /* SQLite connection to register module with */
104568   const char *zName,         /* Name of the module */
104569   const sqlite3_module *,    /* Methods for the module */
104570   void *,                    /* Client data for xCreate/xConnect */
104571   void(*xDestroy)(void*)     /* Module destructor function */
104572 );
104573
104574 /*
104575 ** Every module implementation uses a subclass of the following structure
104576 ** to describe a particular instance of the module.  Each subclass will
104577 ** be tailored to the specific needs of the module implementation.   The
104578 ** purpose of this superclass is to define certain fields that are common
104579 ** to all module implementations.
104580 **
104581 ** Virtual tables methods can set an error message by assigning a
104582 ** string obtained from sqlite3_mprintf() to zErrMsg.  The method should
104583 ** take care that any prior string is freed by a call to sqlite3_free()
104584 ** prior to assigning a new string to zErrMsg.  After the error message
104585 ** is delivered up to the client application, the string will be automatically
104586 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.  Note
104587 ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
104588 ** since virtual tables are commonly implemented in loadable extensions which
104589 ** do not have access to sqlite3MPrintf() or sqlite3Free().
104590 */
104591 struct sqlite3_vtab {
104592   const sqlite3_module *pModule;  /* The module for this virtual table */
104593   int nRef;                       /* Used internally */
104594   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
104595   /* Virtual table implementations will typically add additional fields */
104596 };
104597
104598 /* Every module implementation uses a subclass of the following structure
104599 ** to describe cursors that point into the virtual table and are used
104600 ** to loop through the virtual table.  Cursors are created using the
104601 ** xOpen method of the module.  Each module implementation will define
104602 ** the content of a cursor structure to suit its own needs.
104603 **
104604 ** This superclass exists in order to define fields of the cursor that
104605 ** are common to all implementations.
104606 */
104607 struct sqlite3_vtab_cursor {
104608   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
104609   /* Virtual table implementations will typically add additional fields */
104610 };
104611
104612 /*
104613 ** The xCreate and xConnect methods of a module use the following API
104614 ** to declare the format (the names and datatypes of the columns) of
104615 ** the virtual tables they implement.
104616 */
104617 int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
104618
104619 /*
104620 ** Virtual tables can provide alternative implementations of functions
104621 ** using the xFindFunction method.  But global versions of those functions
104622 ** must exist in order to be overloaded.
104623 **
104624 ** This API makes sure a global version of a function with a particular
104625 ** name and number of parameters exists.  If no such function exists
104626 ** before this API is called, a new function is created.  The implementation
104627 ** of the new function always causes an exception to be thrown.  So
104628 ** the new function is not good for anything by itself.  Its only
104629 ** purpose is to be a place-holder function that can be overloaded
104630 ** by virtual tables.
104631 **
104632 ** This API should be considered part of the virtual table interface,
104633 ** which is experimental and subject to change.
104634 */
104635 int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
104636
104637 /*
104638 ** The interface to the virtual-table mechanism defined above (back up
104639 ** to a comment remarkably similar to this one) is currently considered
104640 ** to be experimental.  The interface might change in incompatible ways.
104641 ** If this is a problem for you, do not use the interface at this time.
104642 **
104643 ** When the virtual-table mechanism stabilizes, we will declare the
104644 ** interface fixed, support it indefinitely, and remove this comment.
104645 **
104646 ****** EXPERIMENTAL - subject to change without notice **************
104647 */
104648
104649 /*
104650 ** CAPI3REF: A Handle To An Open BLOB {F17800}
104651 **
104652 ** An instance of the following opaque structure is used to 
104653 ** represent an blob-handle.  A blob-handle is created by
104654 ** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()].
104655 ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
104656 ** can be used to read or write small subsections of the blob.
104657 ** The [sqlite3_blob_bytes()] interface returns the size of the
104658 ** blob in bytes.
104659 */
104660 typedef struct sqlite3_blob sqlite3_blob;
104661
104662 /*
104663 ** CAPI3REF: Open A BLOB For Incremental I/O {F17810}
104664 **
104665 ** {F17811} This interfaces opens a handle to the blob located
104666 ** in row iRow,, column zColumn, table zTable in database zDb;
104667 ** in other words,  the same blob that would be selected by:
104668 **
104669 ** <pre>
104670 **     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
104671 ** </pre> {END}
104672 **
104673 ** {F17812} If the flags parameter is non-zero, the blob is opened for 
104674 ** read and write access. If it is zero, the blob is opened for read 
104675 ** access. {END}
104676 **
104677 ** {F17813} On success, [SQLITE_OK] is returned and the new 
104678 ** [sqlite3_blob | blob handle] is written to *ppBlob. 
104679 ** {F17814} Otherwise an error code is returned and 
104680 ** any value written to *ppBlob should not be used by the caller.
104681 ** {F17815} This function sets the database-handle error code and message
104682 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()].
104683 ** <todo>We should go through and mark all interfaces that behave this
104684 ** way with a similar statement</todo>
104685 */
104686 int sqlite3_blob_open(
104687   sqlite3*,
104688   const char *zDb,
104689   const char *zTable,
104690   const char *zColumn,
104691   sqlite3_int64 iRow,
104692   int flags,
104693   sqlite3_blob **ppBlob
104694 );
104695
104696 /*
104697 ** CAPI3REF:  Close A BLOB Handle {F17830}
104698 **
104699 ** Close an open [sqlite3_blob | blob handle].
104700 **
104701 ** {F17831} Closing a BLOB shall cause the current transaction to commit
104702 ** if there are no other BLOBs, no pending prepared statements, and the
104703 ** database connection is in autocommit mode.
104704 ** {F17832} If any writes were made to the BLOB, they might be held in cache
104705 ** until the close operation if they will fit. {END}
104706 ** Closing the BLOB often forces the changes
104707 ** out to disk and so if any I/O errors occur, they will likely occur
104708 ** at the time when the BLOB is closed.  {F17833} Any errors that occur during
104709 ** closing are reported as a non-zero return value.
104710 **
104711 ** {F17839} The BLOB is closed unconditionally.  Even if this routine returns
104712 ** an error code, the BLOB is still closed.
104713 */
104714 int sqlite3_blob_close(sqlite3_blob *);
104715
104716 /*
104717 ** CAPI3REF:  Return The Size Of An Open BLOB {F17805}
104718 **
104719 ** {F16806} Return the size in bytes of the blob accessible via the open 
104720 ** [sqlite3_blob | blob-handle] passed as an argument.
104721 */
104722 int sqlite3_blob_bytes(sqlite3_blob *);
104723
104724 /*
104725 ** CAPI3REF:  Read Data From A BLOB Incrementally {F17850}
104726 **
104727 ** This function is used to read data from an open 
104728 ** [sqlite3_blob | blob-handle] into a caller supplied buffer.
104729 ** {F17851} n bytes of data are copied into buffer
104730 ** z from the open blob, starting at offset iOffset.
104731 **
104732 ** {F17852} If offset iOffset is less than n bytes from the end of the blob, 
104733 ** [SQLITE_ERROR] is returned and no data is read.  {F17853} If n is
104734 ** less than zero [SQLITE_ERROR] is returned and no data is read.
104735 **
104736 ** {F17854} On success, SQLITE_OK is returned. Otherwise, an 
104737 ** [SQLITE_ERROR | SQLite error code] or an
104738 ** [SQLITE_IOERR_READ | extended error code] is returned.
104739 */
104740 int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset);
104741
104742 /*
104743 ** CAPI3REF:  Write Data Into A BLOB Incrementally {F17870}
104744 **
104745 ** This function is used to write data into an open 
104746 ** [sqlite3_blob | blob-handle] from a user supplied buffer.
104747 ** {F17871} n bytes of data are copied from the buffer
104748 ** pointed to by z into the open blob, starting at offset iOffset.
104749 **
104750 ** {F17872} If the [sqlite3_blob | blob-handle] passed as the first argument
104751 ** was not opened for writing (the flags parameter to [sqlite3_blob_open()]
104752 *** was zero), this function returns [SQLITE_READONLY].
104753 **
104754 ** {F17873} This function may only modify the contents of the blob; it is
104755 ** not possible to increase the size of a blob using this API.
104756 ** {F17874} If offset iOffset is less than n bytes from the end of the blob, 
104757 ** [SQLITE_ERROR] is returned and no data is written.  {F17875} If n is
104758 ** less than zero [SQLITE_ERROR] is returned and no data is written.
104759 **
104760 ** {F17876} On success, SQLITE_OK is returned. Otherwise, an 
104761 ** [SQLITE_ERROR | SQLite error code] or an
104762 ** [SQLITE_IOERR_READ | extended error code] is returned.
104763 */
104764 int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
104765
104766 /*
104767 ** CAPI3REF:  Virtual File System Objects {F11200}
104768 **
104769 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
104770 ** that SQLite uses to interact
104771 ** with the underlying operating system.  Most builds come with a
104772 ** single default VFS that is appropriate for the host computer.
104773 ** New VFSes can be registered and existing VFSes can be unregistered.
104774 ** The following interfaces are provided.
104775 **
104776 ** {F11201} The sqlite3_vfs_find() interface returns a pointer to 
104777 ** a VFS given its name.  {F11202} Names are case sensitive.
104778 ** {F11203} Names are zero-terminated UTF-8 strings.
104779 ** {F11204} If there is no match, a NULL
104780 ** pointer is returned. {F11205} If zVfsName is NULL then the default 
104781 ** VFS is returned. {END}
104782 **
104783 ** {F11210} New VFSes are registered with sqlite3_vfs_register().
104784 ** {F11211} Each new VFS becomes the default VFS if the makeDflt flag is set.
104785 ** {F11212} The same VFS can be registered multiple times without injury.
104786 ** {F11213} To make an existing VFS into the default VFS, register it again
104787 ** with the makeDflt flag set. {U11214} If two different VFSes with the
104788 ** same name are registered, the behavior is undefined.  {U11215} If a
104789 ** VFS is registered with a name that is NULL or an empty string,
104790 ** then the behavior is undefined.
104791 ** 
104792 ** {F11220} Unregister a VFS with the sqlite3_vfs_unregister() interface.
104793 ** {F11221} If the default VFS is unregistered, another VFS is chosen as
104794 ** the default.  The choice for the new VFS is arbitrary.
104795 */
104796 sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
104797 int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
104798 int sqlite3_vfs_unregister(sqlite3_vfs*);
104799
104800 /*
104801 ** CAPI3REF: Mutexes {F17000}
104802 **
104803 ** The SQLite core uses these routines for thread
104804 ** synchronization.  Though they are intended for internal
104805 ** use by SQLite, code that links against SQLite is
104806 ** permitted to use any of these routines.
104807 **
104808 ** The SQLite source code contains multiple implementations 
104809 ** of these mutex routines.  An appropriate implementation
104810 ** is selected automatically at compile-time.  The following
104811 ** implementations are available in the SQLite core:
104812 **
104813 ** <ul>
104814 ** <li>   SQLITE_MUTEX_OS2
104815 ** <li>   SQLITE_MUTEX_PTHREAD
104816 ** <li>   SQLITE_MUTEX_W32
104817 ** <li>   SQLITE_MUTEX_NOOP
104818 ** </ul>
104819 **
104820 ** The SQLITE_MUTEX_NOOP implementation is a set of routines 
104821 ** that does no real locking and is appropriate for use in 
104822 ** a single-threaded application.  The SQLITE_MUTEX_OS2,
104823 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
104824 ** are appropriate for use on os/2, unix, and windows.
104825 ** 
104826 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
104827 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
104828 ** implementation is included with the library.  The
104829 ** mutex interface routines defined here become external
104830 ** references in the SQLite library for which implementations
104831 ** must be provided by the application.  This facility allows an
104832 ** application that links against SQLite to provide its own mutex
104833 ** implementation without having to modify the SQLite core.
104834 **
104835 ** {F17011} The sqlite3_mutex_alloc() routine allocates a new
104836 ** mutex and returns a pointer to it. {F17012} If it returns NULL
104837 ** that means that a mutex could not be allocated. {F17013} SQLite
104838 ** will unwind its stack and return an error. {F17014} The argument
104839 ** to sqlite3_mutex_alloc() is one of these integer constants:
104840 **
104841 ** <ul>
104842 ** <li>  SQLITE_MUTEX_FAST
104843 ** <li>  SQLITE_MUTEX_RECURSIVE
104844 ** <li>  SQLITE_MUTEX_STATIC_MASTER
104845 ** <li>  SQLITE_MUTEX_STATIC_MEM
104846 ** <li>  SQLITE_MUTEX_STATIC_MEM2
104847 ** <li>  SQLITE_MUTEX_STATIC_PRNG
104848 ** <li>  SQLITE_MUTEX_STATIC_LRU
104849 ** </ul> {END}
104850 **
104851 ** {F17015} The first two constants cause sqlite3_mutex_alloc() to create
104852 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
104853 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END}
104854 ** The mutex implementation does not need to make a distinction
104855 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
104856 ** not want to.  {F17016} But SQLite will only request a recursive mutex in
104857 ** cases where it really needs one.  {END} If a faster non-recursive mutex
104858 ** implementation is available on the host platform, the mutex subsystem
104859 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
104860 **
104861 ** {F17017} The other allowed parameters to sqlite3_mutex_alloc() each return
104862 ** a pointer to a static preexisting mutex. {END}  Four static mutexes are
104863 ** used by the current version of SQLite.  Future versions of SQLite
104864 ** may add additional static mutexes.  Static mutexes are for internal
104865 ** use by SQLite only.  Applications that use SQLite mutexes should
104866 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
104867 ** SQLITE_MUTEX_RECURSIVE.
104868 **
104869 ** {F17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
104870 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
104871 ** returns a different mutex on every call.  {F17034} But for the static 
104872 ** mutex types, the same mutex is returned on every call that has
104873 ** the same type number. {END}
104874 **
104875 ** {F17019} The sqlite3_mutex_free() routine deallocates a previously
104876 ** allocated dynamic mutex. {F17020} SQLite is careful to deallocate every
104877 ** dynamic mutex that it allocates. {U17021} The dynamic mutexes must not be in 
104878 ** use when they are deallocated. {U17022} Attempting to deallocate a static
104879 ** mutex results in undefined behavior. {F17023} SQLite never deallocates
104880 ** a static mutex. {END}
104881 **
104882 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
104883 ** to enter a mutex. {F17024} If another thread is already within the mutex,
104884 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
104885 ** SQLITE_BUSY. {F17025}  The sqlite3_mutex_try() interface returns SQLITE_OK
104886 ** upon successful entry.  {F17026} Mutexes created using
104887 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
104888 ** {F17027} In such cases the,
104889 ** mutex must be exited an equal number of times before another thread
104890 ** can enter.  {U17028} If the same thread tries to enter any other
104891 ** kind of mutex more than once, the behavior is undefined.
104892 ** {F17029} SQLite will never exhibit
104893 ** such behavior in its own use of mutexes. {END}
104894 **
104895 ** Some systems (ex: windows95) do not the operation implemented by
104896 ** sqlite3_mutex_try().  On those systems, sqlite3_mutex_try() will
104897 ** always return SQLITE_BUSY.  {F17030} The SQLite core only ever uses
104898 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior. {END}
104899 **
104900 ** {F17031} The sqlite3_mutex_leave() routine exits a mutex that was
104901 ** previously entered by the same thread.  {U17032} The behavior
104902 ** is undefined if the mutex is not currently entered by the
104903 ** calling thread or is not currently allocated.  {F17033} SQLite will
104904 ** never do either. {END}
104905 **
104906 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
104907 */
104908 sqlite3_mutex *sqlite3_mutex_alloc(int);
104909 void sqlite3_mutex_free(sqlite3_mutex*);
104910 void sqlite3_mutex_enter(sqlite3_mutex*);
104911 int sqlite3_mutex_try(sqlite3_mutex*);
104912 void sqlite3_mutex_leave(sqlite3_mutex*);
104913
104914 /*
104915 ** CAPI3REF: Mutex Verifcation Routines {F17080}
104916 **
104917 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
104918 ** are intended for use inside assert() statements. {F17081} The SQLite core
104919 ** never uses these routines except inside an assert() and applications
104920 ** are advised to follow the lead of the core.  {F17082} The core only
104921 ** provides implementations for these routines when it is compiled
104922 ** with the SQLITE_DEBUG flag.  {U17087} External mutex implementations
104923 ** are only required to provide these routines if SQLITE_DEBUG is
104924 ** defined and if NDEBUG is not defined.
104925 **
104926 ** {F17083} These routines should return true if the mutex in their argument
104927 ** is held or not held, respectively, by the calling thread. {END}
104928 **
104929 ** {X17084} The implementation is not required to provided versions of these
104930 ** routines that actually work.
104931 ** If the implementation does not provide working
104932 ** versions of these routines, it should at least provide stubs
104933 ** that always return true so that one does not get spurious
104934 ** assertion failures. {END}
104935 **
104936 ** {F17085} If the argument to sqlite3_mutex_held() is a NULL pointer then
104937 ** the routine should return 1.  {END} This seems counter-intuitive since
104938 ** clearly the mutex cannot be held if it does not exist.  But the
104939 ** the reason the mutex does not exist is because the build is not
104940 ** using mutexes.  And we do not want the assert() containing the
104941 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
104942 ** the appropriate thing to do.  {F17086} The sqlite3_mutex_notheld() 
104943 ** interface should also return 1 when given a NULL pointer.
104944 */
104945 int sqlite3_mutex_held(sqlite3_mutex*);
104946 int sqlite3_mutex_notheld(sqlite3_mutex*);
104947
104948 /*
104949 ** CAPI3REF: Mutex Types {F17001}
104950 **
104951 ** {F17002} The [sqlite3_mutex_alloc()] interface takes a single argument
104952 ** which is one of these integer constants. {END}
104953 */
104954 #define SQLITE_MUTEX_FAST             0
104955 #define SQLITE_MUTEX_RECURSIVE        1
104956 #define SQLITE_MUTEX_STATIC_MASTER    2
104957 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
104958 #define SQLITE_MUTEX_STATIC_MEM2      4  /* sqlite3_release_memory() */
104959 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
104960 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
104961
104962 /*
104963 ** CAPI3REF: Low-Level Control Of Database Files {F11300}
104964 **
104965 ** {F11301} The [sqlite3_file_control()] interface makes a direct call to the
104966 ** xFileControl method for the [sqlite3_io_methods] object associated
104967 ** with a particular database identified by the second argument. {F11302} The
104968 ** name of the database is the name assigned to the database by the
104969 ** <a href="lang_attach.html">ATTACH</a> SQL command that opened the
104970 ** database. {F11303} To control the main database file, use the name "main"
104971 ** or a NULL pointer. {F11304} The third and fourth parameters to this routine
104972 ** are passed directly through to the second and third parameters of
104973 ** the xFileControl method.  {F11305} The return value of the xFileControl
104974 ** method becomes the return value of this routine.
104975 **
104976 ** {F11306} If the second parameter (zDbName) does not match the name of any
104977 ** open database file, then SQLITE_ERROR is returned. {F11307} This error
104978 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
104979 ** or [sqlite3_errmsg()]. {U11308} The underlying xFileControl method might
104980 ** also return SQLITE_ERROR.  {U11309} There is no way to distinguish between
104981 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
104982 ** xFileControl method. {END}
104983 **
104984 ** See also: [SQLITE_FCNTL_LOCKSTATE]
104985 */
104986 int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
104987
104988 /*
104989 ** Undo the hack that converts floating point types to integer for
104990 ** builds on processors without floating point support.
104991 */
104992 #ifdef SQLITE_OMIT_FLOATING_POINT
104993 # undef double
104994 #endif
104995
104996 #if 0
104997 }  /* End of the 'extern "C"' block */
104998 #endif
104999 #endif
105000
105001 /************** End of sqlite3.h *********************************************/
105002 /************** Continuing where we left off in fts3_tokenizer.h *************/
105003
105004 /*
105005 ** Structures used by the tokenizer interface. When a new tokenizer
105006 ** implementation is registered, the caller provides a pointer to
105007 ** an sqlite3_tokenizer_module containing pointers to the callback
105008 ** functions that make up an implementation.
105009 **
105010 ** When an fts3 table is created, it passes any arguments passed to
105011 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
105012 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
105013 ** implementation. The xCreate() function in turn returns an 
105014 ** sqlite3_tokenizer structure representing the specific tokenizer to
105015 ** be used for the fts3 table (customized by the tokenizer clause arguments).
105016 **
105017 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
105018 ** method is called. It returns an sqlite3_tokenizer_cursor object
105019 ** that may be used to tokenize a specific input buffer based on
105020 ** the tokenization rules supplied by a specific sqlite3_tokenizer
105021 ** object.
105022 */
105023 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
105024 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
105025 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
105026
105027 struct sqlite3_tokenizer_module {
105028
105029   /*
105030   ** Structure version. Should always be set to 0.
105031   */
105032   int iVersion;
105033
105034   /*
105035   ** Create a new tokenizer. The values in the argv[] array are the
105036   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
105037   ** TABLE statement that created the fts3 table. For example, if
105038   ** the following SQL is executed:
105039   **
105040   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
105041   **
105042   ** then argc is set to 2, and the argv[] array contains pointers
105043   ** to the strings "arg1" and "arg2".
105044   **
105045   ** This method should return either SQLITE_OK (0), or an SQLite error 
105046   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
105047   ** to point at the newly created tokenizer structure. The generic
105048   ** sqlite3_tokenizer.pModule variable should not be initialised by
105049   ** this callback. The caller will do so.
105050   */
105051   int (*xCreate)(
105052     int argc,                           /* Size of argv array */
105053     const char *const*argv,             /* Tokenizer argument strings */
105054     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
105055   );
105056
105057   /*
105058   ** Destroy an existing tokenizer. The fts3 module calls this method
105059   ** exactly once for each successful call to xCreate().
105060   */
105061   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
105062
105063   /*
105064   ** Create a tokenizer cursor to tokenize an input buffer. The caller
105065   ** is responsible for ensuring that the input buffer remains valid
105066   ** until the cursor is closed (using the xClose() method). 
105067   */
105068   int (*xOpen)(
105069     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
105070     const char *pInput, int nBytes,      /* Input buffer */
105071     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
105072   );
105073
105074   /*
105075   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
105076   ** method exactly once for each successful call to xOpen().
105077   */
105078   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
105079
105080   /*
105081   ** Retrieve the next token from the tokenizer cursor pCursor. This
105082   ** method should either return SQLITE_OK and set the values of the
105083   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
105084   ** the end of the buffer has been reached, or an SQLite error code.
105085   **
105086   ** *ppToken should be set to point at a buffer containing the 
105087   ** normalized version of the token (i.e. after any case-folding and/or
105088   ** stemming has been performed). *pnBytes should be set to the length
105089   ** of this buffer in bytes. The input text that generated the token is
105090   ** identified by the byte offsets returned in *piStartOffset and
105091   ** *piEndOffset.
105092   **
105093   ** The buffer *ppToken is set to point at is managed by the tokenizer
105094   ** implementation. It is only required to be valid until the next call
105095   ** to xNext() or xClose(). 
105096   */
105097   /* TODO(shess) current implementation requires pInput to be
105098   ** nul-terminated.  This should either be fixed, or pInput/nBytes
105099   ** should be converted to zInput.
105100   */
105101   int (*xNext)(
105102     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
105103     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
105104     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
105105     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
105106     int *piPosition      /* OUT: Number of tokens returned before this one */
105107   );
105108 };
105109
105110 struct sqlite3_tokenizer {
105111   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
105112   /* Tokenizer implementations will typically add additional fields */
105113 };
105114
105115 struct sqlite3_tokenizer_cursor {
105116   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
105117   /* Tokenizer implementations will typically add additional fields */
105118 };
105119
105120 #endif /* _FTS3_TOKENIZER_H_ */
105121
105122 /************** End of fts3_tokenizer.h **************************************/
105123 /************** Continuing where we left off in fts3_tokenizer.c *************/
105124
105125 /*
105126 ** Implementation of the SQL scalar function for accessing the underlying 
105127 ** hash table. This function may be called as follows:
105128 **
105129 **   SELECT <function-name>(<key-name>);
105130 **   SELECT <function-name>(<key-name>, <pointer>);
105131 **
105132 ** where <function-name> is the name passed as the second argument
105133 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
105134 **
105135 ** If the <pointer> argument is specified, it must be a blob value
105136 ** containing a pointer to be stored as the hash data corresponding
105137 ** to the string <key-name>. If <pointer> is not specified, then
105138 ** the string <key-name> must already exist in the has table. Otherwise,
105139 ** an error is returned.
105140 **
105141 ** Whether or not the <pointer> argument is specified, the value returned
105142 ** is a blob containing the pointer stored as the hash data corresponding
105143 ** to string <key-name> (after the hash-table is updated, if applicable).
105144 */
105145 static void scalarFunc(
105146   sqlite3_context *context,
105147   int argc,
105148   sqlite3_value **argv
105149 ){
105150   fts3Hash *pHash;
105151   void *pPtr = 0;
105152   const unsigned char *zName;
105153   int nName;
105154
105155   assert( argc==1 || argc==2 );
105156
105157   pHash = (fts3Hash *)sqlite3_user_data(context);
105158
105159   zName = sqlite3_value_text(argv[0]);
105160   nName = sqlite3_value_bytes(argv[0])+1;
105161
105162   if( argc==2 ){
105163     void *pOld;
105164     int n = sqlite3_value_bytes(argv[1]);
105165     if( n!=sizeof(pPtr) ){
105166       sqlite3_result_error(context, "argument type mismatch", -1);
105167       return;
105168     }
105169     pPtr = *(void **)sqlite3_value_blob(argv[1]);
105170     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
105171     if( pOld==pPtr ){
105172       sqlite3_result_error(context, "out of memory", -1);
105173       return;
105174     }
105175   }else{
105176     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
105177     if( !pPtr ){
105178       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
105179       sqlite3_result_error(context, zErr, -1);
105180       sqlite3_free(zErr);
105181       return;
105182     }
105183   }
105184
105185   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
105186 }
105187
105188 #ifdef SQLITE_TEST
105189
105190 #include <tcl.h>
105191
105192 /*
105193 ** Implementation of a special SQL scalar function for testing tokenizers 
105194 ** designed to be used in concert with the Tcl testing framework. This
105195 ** function must be called with two arguments:
105196 **
105197 **   SELECT <function-name>(<key-name>, <input-string>);
105198 **   SELECT <function-name>(<key-name>, <pointer>);
105199 **
105200 ** where <function-name> is the name passed as the second argument
105201 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
105202 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
105203 **
105204 ** The return value is a string that may be interpreted as a Tcl
105205 ** list. For each token in the <input-string>, three elements are
105206 ** added to the returned list. The first is the token position, the 
105207 ** second is the token text (folded, stemmed, etc.) and the third is the
105208 ** substring of <input-string> associated with the token. For example, 
105209 ** using the built-in "simple" tokenizer:
105210 **
105211 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
105212 **
105213 ** will return the string:
105214 **
105215 **   "{0 i I 1 dont don't 2 see see 3 how how}"
105216 **   
105217 */
105218 static void testFunc(
105219   sqlite3_context *context,
105220   int argc,
105221   sqlite3_value **argv
105222 ){
105223   fts3Hash *pHash;
105224   sqlite3_tokenizer_module *p;
105225   sqlite3_tokenizer *pTokenizer = 0;
105226   sqlite3_tokenizer_cursor *pCsr = 0;
105227
105228   const char *zErr = 0;
105229
105230   const char *zName;
105231   int nName;
105232   const char *zInput;
105233   int nInput;
105234
105235   const char *zArg = 0;
105236
105237   const char *zToken;
105238   int nToken;
105239   int iStart;
105240   int iEnd;
105241   int iPos;
105242
105243   Tcl_Obj *pRet;
105244
105245   assert( argc==2 || argc==3 );
105246
105247   nName = sqlite3_value_bytes(argv[0]);
105248   zName = (const char *)sqlite3_value_text(argv[0]);
105249   nInput = sqlite3_value_bytes(argv[argc-1]);
105250   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
105251
105252   if( argc==3 ){
105253     zArg = (const char *)sqlite3_value_text(argv[1]);
105254   }
105255
105256   pHash = (fts3Hash *)sqlite3_user_data(context);
105257   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
105258
105259   if( !p ){
105260     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
105261     sqlite3_result_error(context, zErr, -1);
105262     sqlite3_free(zErr);
105263     return;
105264   }
105265
105266   pRet = Tcl_NewObj();
105267   Tcl_IncrRefCount(pRet);
105268
105269   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
105270     zErr = "error in xCreate()";
105271     goto finish;
105272   }
105273   pTokenizer->pModule = p;
105274   if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
105275     zErr = "error in xOpen()";
105276     goto finish;
105277   }
105278   pCsr->pTokenizer = pTokenizer;
105279
105280   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
105281     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
105282     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
105283     zToken = &zInput[iStart];
105284     nToken = iEnd-iStart;
105285     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
105286   }
105287
105288   if( SQLITE_OK!=p->xClose(pCsr) ){
105289     zErr = "error in xClose()";
105290     goto finish;
105291   }
105292   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
105293     zErr = "error in xDestroy()";
105294     goto finish;
105295   }
105296
105297 finish:
105298   if( zErr ){
105299     sqlite3_result_error(context, zErr, -1);
105300   }else{
105301     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
105302   }
105303   Tcl_DecrRefCount(pRet);
105304 }
105305
105306 static
105307 int registerTokenizer(
105308   sqlite3 *db, 
105309   char *zName, 
105310   const sqlite3_tokenizer_module *p
105311 ){
105312   int rc;
105313   sqlite3_stmt *pStmt;
105314   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
105315
105316   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
105317   if( rc!=SQLITE_OK ){
105318     return rc;
105319   }
105320
105321   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
105322   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
105323   sqlite3_step(pStmt);
105324
105325   return sqlite3_finalize(pStmt);
105326 }
105327
105328 static
105329 int queryTokenizer(
105330   sqlite3 *db, 
105331   char *zName,  
105332   const sqlite3_tokenizer_module **pp
105333 ){
105334   int rc;
105335   sqlite3_stmt *pStmt;
105336   const char zSql[] = "SELECT fts3_tokenizer(?)";
105337
105338   *pp = 0;
105339   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
105340   if( rc!=SQLITE_OK ){
105341     return rc;
105342   }
105343
105344   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
105345   if( SQLITE_ROW==sqlite3_step(pStmt) ){
105346     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
105347       memcpy(pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
105348     }
105349   }
105350
105351   return sqlite3_finalize(pStmt);
105352 }
105353
105354 void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
105355
105356 /*
105357 ** Implementation of the scalar function fts3_tokenizer_internal_test().
105358 ** This function is used for testing only, it is not included in the
105359 ** build unless SQLITE_TEST is defined.
105360 **
105361 ** The purpose of this is to test that the fts3_tokenizer() function
105362 ** can be used as designed by the C-code in the queryTokenizer and
105363 ** registerTokenizer() functions above. These two functions are repeated
105364 ** in the README.tokenizer file as an example, so it is important to
105365 ** test them.
105366 **
105367 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
105368 ** function with no arguments. An assert() will fail if a problem is
105369 ** detected. i.e.:
105370 **
105371 **     SELECT fts3_tokenizer_internal_test();
105372 **
105373 */
105374 static void intTestFunc(
105375   sqlite3_context *context,
105376   int argc,
105377   sqlite3_value **argv
105378 ){
105379   int rc;
105380   const sqlite3_tokenizer_module *p1;
105381   const sqlite3_tokenizer_module *p2;
105382   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
105383
105384   /* Test the query function */
105385   sqlite3Fts3SimpleTokenizerModule(&p1);
105386   rc = queryTokenizer(db, "simple", &p2);
105387   assert( rc==SQLITE_OK );
105388   assert( p1==p2 );
105389   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
105390   assert( rc==SQLITE_ERROR );
105391   assert( p2==0 );
105392   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
105393
105394   /* Test the storage function */
105395   rc = registerTokenizer(db, "nosuchtokenizer", p1);
105396   assert( rc==SQLITE_OK );
105397   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
105398   assert( rc==SQLITE_OK );
105399   assert( p2==p1 );
105400
105401   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
105402 }
105403
105404 #endif
105405
105406 /*
105407 ** Set up SQL objects in database db used to access the contents of
105408 ** the hash table pointed to by argument pHash. The hash table must
105409 ** been initialised to use string keys, and to take a private copy 
105410 ** of the key when a value is inserted. i.e. by a call similar to:
105411 **
105412 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
105413 **
105414 ** This function adds a scalar function (see header comment above
105415 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
105416 ** defined at compilation time, a temporary virtual table (see header 
105417 ** comment above struct HashTableVtab) to the database schema. Both 
105418 ** provide read/write access to the contents of *pHash.
105419 **
105420 ** The third argument to this function, zName, is used as the name
105421 ** of both the scalar and, if created, the virtual table.
105422 */
105423 int sqlite3Fts3InitHashTable(
105424   sqlite3 *db, 
105425   fts3Hash *pHash, 
105426   const char *zName
105427 ){
105428   int rc = SQLITE_OK;
105429   void *p = (void *)pHash;
105430   const int any = SQLITE_ANY;
105431   char *zTest = 0;
105432   char *zTest2 = 0;
105433
105434 #ifdef SQLITE_TEST
105435   void *pdb = (void *)db;
105436   zTest = sqlite3_mprintf("%s_test", zName);
105437   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
105438   if( !zTest || !zTest2 ){
105439     rc = SQLITE_NOMEM;
105440   }
105441 #endif
105442
105443   if( rc!=SQLITE_OK
105444    || (rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
105445    || (rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
105446 #ifdef SQLITE_TEST
105447    || (rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
105448    || (rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
105449    || (rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
105450 #endif
105451   );
105452
105453   sqlite3_free(zTest);
105454   sqlite3_free(zTest2);
105455   return rc;
105456 }
105457
105458 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
105459
105460 /************** End of fts3_tokenizer.c **************************************/
105461 /************** Begin file fts3_tokenizer1.c *********************************/
105462 /*
105463 ** 2006 Oct 10
105464 **
105465 ** The author disclaims copyright to this source code.  In place of
105466 ** a legal notice, here is a blessing:
105467 **
105468 **    May you do good and not evil.
105469 **    May you find forgiveness for yourself and forgive others.
105470 **    May you share freely, never taking more than you give.
105471 **
105472 ******************************************************************************
105473 **
105474 ** Implementation of the "simple" full-text-search tokenizer.
105475 */
105476
105477 /*
105478 ** The code in this file is only compiled if:
105479 **
105480 **     * The FTS3 module is being built as an extension
105481 **       (in which case SQLITE_CORE is not defined), or
105482 **
105483 **     * The FTS3 module is being built into the core of
105484 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
105485 */
105486 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
105487
105488
105489
105490 /************** Include fts3_tokenizer.h in the middle of fts3_tokenizer1.c **/
105491 /************** Begin file fts3_tokenizer.h **********************************/
105492 /*
105493 ** 2006 July 10
105494 **
105495 ** The author disclaims copyright to this source code.
105496 **
105497 *************************************************************************
105498 ** Defines the interface to tokenizers used by fulltext-search.  There
105499 ** are three basic components:
105500 **
105501 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
105502 ** interface functions.  This is essentially the class structure for
105503 ** tokenizers.
105504 **
105505 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
105506 ** including customization information defined at creation time.
105507 **
105508 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
105509 ** tokens from a particular input.
105510 */
105511 #ifndef _FTS3_TOKENIZER_H_
105512 #define _FTS3_TOKENIZER_H_
105513
105514 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
105515 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
105516 ** we will need a way to register the API consistently.
105517 */
105518 /************** Include sqlite3.h in the middle of fts3_tokenizer.h **********/
105519 /************** Begin file sqlite3.h *****************************************/
105520 /*
105521 ** 2001 September 15
105522 **
105523 ** The author disclaims copyright to this source code.  In place of
105524 ** a legal notice, here is a blessing:
105525 **
105526 **    May you do good and not evil.
105527 **    May you find forgiveness for yourself and forgive others.
105528 **    May you share freely, never taking more than you give.
105529 **
105530 *************************************************************************
105531 ** This header file defines the interface that the SQLite library
105532 ** presents to client programs.  If a C-function, structure, datatype,
105533 ** or constant definition does not appear in this file, then it is
105534 ** not a published API of SQLite, is subject to change without
105535 ** notice, and should not be referenced by programs that use SQLite.
105536 **
105537 ** Some of the definitions that are in this file are marked as
105538 ** "experimental".  Experimental interfaces are normally new
105539 ** features recently added to SQLite.  We do not anticipate changes 
105540 ** to experimental interfaces but reserve to make minor changes if
105541 ** experience from use "in the wild" suggest such changes are prudent.
105542 **
105543 ** The official C-language API documentation for SQLite is derived
105544 ** from comments in this file.  This file is the authoritative source
105545 ** on how SQLite interfaces are suppose to operate.
105546 **
105547 ** The name of this file under configuration management is "sqlite.h.in".
105548 ** The makefile makes some minor changes to this file (such as inserting
105549 ** the version number) and changes its name to "sqlite3.h" as
105550 ** part of the build process.
105551 **
105552 ** @(#) $Id: sqlite.h.in,v 1.278 2007/12/13 21:54:11 drh Exp $
105553 */
105554 #ifndef _SQLITE3_H_
105555 #define _SQLITE3_H_
105556
105557 /*
105558 ** Make sure we can call this stuff from C++.
105559 */
105560 #if 0
105561 extern "C" {
105562 #endif
105563
105564
105565 /*
105566 ** Add the ability to override 'extern'
105567 */
105568 #ifndef SQLITE_EXTERN
105569 # define SQLITE_EXTERN extern
105570 #endif
105571
105572 /*
105573 ** Make sure these symbols where not defined by some previous header
105574 ** file.
105575 */
105576 #ifdef SQLITE_VERSION
105577 # undef SQLITE_VERSION
105578 #endif
105579 #ifdef SQLITE_VERSION_NUMBER
105580 # undef SQLITE_VERSION_NUMBER
105581 #endif
105582
105583 /*
105584 ** CAPI3REF: Compile-Time Library Version Numbers {F10010}
105585 **
105586 ** {F10011} The #define in the sqlite3.h header file named
105587 ** SQLITE_VERSION resolves to a string literal that identifies
105588 ** the version of the SQLite library in the format "X.Y.Z", where
105589 ** X is the major version number, Y is the minor version number and Z
105590 ** is the release number.  The X.Y.Z might be followed by "alpha" or "beta".
105591 ** {END} For example "3.1.1beta".
105592 **
105593 ** The X value is always 3 in SQLite.  The X value only changes when
105594 ** backwards compatibility is broken and we intend to never break
105595 ** backwards compatibility.  The Y value only changes when
105596 ** there are major feature enhancements that are forwards compatible
105597 ** but not backwards compatible.  The Z value is incremented with
105598 ** each release but resets back to 0 when Y is incremented.
105599 **
105600 ** {F10014} The SQLITE_VERSION_NUMBER #define resolves to an integer
105601 ** with the value  (X*1000000 + Y*1000 + Z) where X, Y, and Z are as
105602 ** with SQLITE_VERSION. {END} For example, for version "3.1.1beta", 
105603 ** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using 
105604 ** version 3.1.1 or greater at compile time, programs may use the test 
105605 ** (SQLITE_VERSION_NUMBER>=3001001).
105606 **
105607 ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
105608 */
105609 #define SQLITE_VERSION         "3.5.4"
105610 #define SQLITE_VERSION_NUMBER 3005004
105611
105612 /*
105613 ** CAPI3REF: Run-Time Library Version Numbers {F10020}
105614 **
105615 ** {F10021} The sqlite3_libversion_number() interface returns an integer
105616 ** equal to [SQLITE_VERSION_NUMBER].  {END} The value returned
105617 ** by this routine should only be different from the header values
105618 ** if the application is compiled using an sqlite3.h header from a
105619 ** different version of SQLite than library.  Cautious programmers might
105620 ** include a check in their application to verify that 
105621 ** sqlite3_libversion_number() always returns the value 
105622 ** [SQLITE_VERSION_NUMBER].
105623 **
105624 ** {F10022} The sqlite3_version[] string constant contains the text of the
105625 ** [SQLITE_VERSION] string. {F10023} The sqlite3_libversion() function returns
105626 ** a pointer to the sqlite3_version[] string constant. {END} The 
105627 ** sqlite3_libversion() function
105628 ** is provided for DLL users who can only access functions and not
105629 ** constants within the DLL.
105630 */
105631 SQLITE_EXTERN const char sqlite3_version[];
105632 const char *sqlite3_libversion(void);
105633 int sqlite3_libversion_number(void);
105634
105635 /*
105636 ** CAPI3REF: Test To See If The Library Is Threadsafe {F10100}
105637 **
105638 ** {F10101} The sqlite3_threadsafe() routine returns nonzero
105639 ** if SQLite was compiled with its mutexes enabled or zero if
105640 ** SQLite was compiled with mutexes disabled. {END}  If this
105641 ** routine returns false, then it is not safe for simultaneously
105642 ** running threads to both invoke SQLite interfaces.
105643 **
105644 ** Really all this routine does is return true if SQLite was
105645 ** compiled with the -DSQLITE_THREADSAFE=1 option and false if
105646 ** compiled with -DSQLITE_THREADSAFE=0.  If SQLite uses an
105647 ** application-defined mutex subsystem, malloc subsystem, collating
105648 ** sequence, VFS, SQL function, progress callback, commit hook,
105649 ** extension, or other accessories and these add-ons are not
105650 ** threadsafe, then clearly the combination will not be threadsafe
105651 ** either.  Hence, this routine never reports that the library
105652 ** is guaranteed to be threadsafe, only when it is guaranteed not
105653 ** to be.
105654 */
105655 int sqlite3_threadsafe(void);
105656
105657 /*
105658 ** CAPI3REF: Database Connection Handle {F12000}
105659 **
105660 ** Each open SQLite database is represented by pointer to an instance of the
105661 ** opaque structure named "sqlite3".  It is useful to think of an sqlite3
105662 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
105663 ** [sqlite3_open_v2()] interfaces are its constructors
105664 ** and [sqlite3_close()] is its destructor.  There are many other interfaces
105665 ** (such as [sqlite3_prepare_v2()], [sqlite3_create_function()], and
105666 ** [sqlite3_busy_timeout()] to name but three) that are methods on this
105667 ** object.
105668 */
105669 typedef struct sqlite3 sqlite3;
105670
105671
105672 /*
105673 ** CAPI3REF: 64-Bit Integer Types {F10200}
105674 **
105675 ** Because there is no cross-platform way to specify such types
105676 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
105677 ** {F10201} The sqlite_int64 and sqlite3_int64 types specify a
105678 ** 64-bit signed integer. {F10202} The sqlite_uint64 and
105679 ** sqlite3_uint64 types specify a 64-bit unsigned integer. {END}
105680 **
105681 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type
105682 ** definitions.  The sqlite_int64 and sqlite_uint64 types are
105683 ** supported for backwards compatibility only.
105684 */
105685 #ifdef SQLITE_INT64_TYPE
105686   typedef SQLITE_INT64_TYPE sqlite_int64;
105687   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
105688 #elif defined(_MSC_VER) || defined(__BORLANDC__)
105689   typedef __int64 sqlite_int64;
105690   typedef unsigned __int64 sqlite_uint64;
105691 #else
105692   typedef long long int sqlite_int64;
105693   typedef unsigned long long int sqlite_uint64;
105694 #endif
105695 typedef sqlite_int64 sqlite3_int64;
105696 typedef sqlite_uint64 sqlite3_uint64;
105697
105698 /*
105699 ** If compiling for a processor that lacks floating point support,
105700 ** substitute integer for floating-point
105701 */
105702 #ifdef SQLITE_OMIT_FLOATING_POINT
105703 # define double sqlite3_int64
105704 #endif
105705
105706 /*
105707 ** CAPI3REF: Closing A Database Connection {F12010}
105708 **
105709 ** {F12011} The sqlite3_close() interfaces destroys an [sqlite3] object
105710 ** allocated by a prior call to [sqlite3_open()], [sqlite3_open16()], or
105711 ** [sqlite3_open_v2()]. {F12012} Sqlite3_close() releases all
105712 ** memory used by the connection and closes all open files. {END}.
105713 **
105714 ** {F12013} If the database connection contains
105715 ** [sqlite3_stmt | prepared statements] that have not been finalized
105716 ** by [sqlite3_finalize()], then sqlite3_close() returns SQLITE_BUSY
105717 ** and leaves the connection open.  {F12014} Giving sqlite3_close()
105718 ** a NULL pointer is a harmless no-op. {END}
105719 **
105720 ** {U12015} Passing this routine a database connection that has already been
105721 ** closed results in undefined behavior. {U12016} If other interfaces that
105722 ** reference the same database connection are pending (either in the
105723 ** same thread or in different threads) when this routine is called,
105724 ** then the behavior is undefined and is almost certainly undesirable.
105725 */
105726 int sqlite3_close(sqlite3 *);
105727
105728 /*
105729 ** The type for a callback function.
105730 ** This is legacy and deprecated.  It is included for historical
105731 ** compatibility and is not documented.
105732 */
105733 typedef int (*sqlite3_callback)(void*,int,char**, char**);
105734
105735 /*
105736 ** CAPI3REF: One-Step Query Execution Interface {F12100}
105737 **
105738 ** {F12101} The sqlite3_exec() interface evaluates zero or more 
105739 ** UTF-8 encoded, semicolon-separated SQL statements in the zero-terminated
105740 ** string of its second argument.  {F12102} The SQL
105741 ** statements are evaluated in the context of the database connection
105742 ** specified by in the first argument.
105743 ** {F12103} SQL statements are prepared one by one using
105744 ** [sqlite3_prepare()] or the equivalent, evaluated
105745 ** using one or more calls to [sqlite3_step()], then destroyed
105746 ** using [sqlite3_finalize()]. {F12104} The return value of
105747 ** sqlite3_exec() is SQLITE_OK if all SQL statement run
105748 ** successfully.
105749 **
105750 ** {F12105} If one or more of the SQL statements handed to
105751 ** sqlite3_exec() are queries, then
105752 ** the callback function specified by the 3rd parameter is
105753 ** invoked once for each row of the query result. {F12106}
105754 ** If the callback returns a non-zero value then the query
105755 ** is aborted, all subsequent SQL statements
105756 ** are skipped and the sqlite3_exec() function returns the [SQLITE_ABORT].
105757 **
105758 ** {F12107} The 4th parameter to sqlite3_exec() is an arbitrary pointer
105759 ** that is passed through to the callback function as its first parameter.
105760 **
105761 ** {F12108} The 2nd parameter to the callback function is the number of
105762 ** columns in the query result.  {F12109} The 3rd parameter to the callback
105763 ** is an array of pointers to strings holding the values for each column
105764 ** as extracted using [sqlite3_column_text()].  NULL values in the result
105765 ** set result in a NULL pointer.  All other value are in their UTF-8
105766 ** string representation. {F12117}
105767 ** The 4th parameter to the callback is an array of strings
105768 ** obtained using [sqlite3_column_name()] and holding
105769 ** the names of each column, also in UTF-8.
105770 **
105771 ** {F12110} The callback function may be NULL, even for queries.  A NULL
105772 ** callback is not an error.  It just means that no callback
105773 ** will be invoked. 
105774 **
105775 ** {F12112} If an error occurs while parsing or evaluating the SQL
105776 ** then an appropriate error message is written into memory obtained
105777 ** from [sqlite3_malloc()] and *errmsg is made to point to that message
105778 ** assuming errmsg is not NULL.  
105779 ** {U12113} The calling function is responsible for freeing the memory
105780 ** using [sqlite3_free()].
105781 ** {F12116} If [sqlite3_malloc()] fails while attempting to generate
105782 ** the error message, *errmsg is set to NULL.
105783 ** {F12114} If errmsg is NULL then no attempt is made to generate an
105784 ** error message. <todo>Is the return code SQLITE_NOMEM or the original
105785 ** error code?</todo> <todo>What happens if there are multiple errors?
105786 ** Do we get code for the first error, or is the choice of reported
105787 ** error arbitrary?</todo>
105788 **
105789 ** {F12115} The return value is is SQLITE_OK if there are no errors and
105790 ** some other [SQLITE_OK | return code] if there is an error.  
105791 ** The particular return value depends on the type of error.  {END}
105792 */
105793 int sqlite3_exec(
105794   sqlite3*,                                  /* An open database */
105795   const char *sql,                           /* SQL to be evaluted */
105796   int (*callback)(void*,int,char**,char**),  /* Callback function */
105797   void *,                                    /* 1st argument to callback */
105798   char **errmsg                              /* Error msg written here */
105799 );
105800
105801 /*
105802 ** CAPI3REF: Result Codes {F10210}
105803 ** KEYWORDS: SQLITE_OK
105804 **
105805 ** Many SQLite functions return an integer result code from the set shown
105806 ** above in order to indicates success or failure.
105807 **
105808 ** {F10211} The result codes shown here are the only ones returned 
105809 ** by SQLite in its default configuration. {F10212} However, the
105810 ** [sqlite3_extended_result_codes()] API can be used to set a database
105811 ** connectoin to return more detailed result codes. {END}
105812 **
105813 ** See also: [SQLITE_IOERR_READ | extended result codes]
105814 **
105815 */
105816 #define SQLITE_OK           0   /* Successful result */
105817 /* beginning-of-error-codes */
105818 #define SQLITE_ERROR        1   /* SQL error or missing database */
105819 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
105820 #define SQLITE_PERM         3   /* Access permission denied */
105821 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
105822 #define SQLITE_BUSY         5   /* The database file is locked */
105823 #define SQLITE_LOCKED       6   /* A table in the database is locked */
105824 #define SQLITE_NOMEM        7   /* A malloc() failed */
105825 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
105826 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
105827 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
105828 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
105829 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
105830 #define SQLITE_FULL        13   /* Insertion failed because database is full */
105831 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
105832 #define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
105833 #define SQLITE_EMPTY       16   /* Database is empty */
105834 #define SQLITE_SCHEMA      17   /* The database schema changed */
105835 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
105836 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
105837 #define SQLITE_MISMATCH    20   /* Data type mismatch */
105838 #define SQLITE_MISUSE      21   /* Library used incorrectly */
105839 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
105840 #define SQLITE_AUTH        23   /* Authorization denied */
105841 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
105842 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
105843 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
105844 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
105845 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
105846 /* end-of-error-codes */
105847
105848 /*
105849 ** CAPI3REF: Extended Result Codes {F10220}
105850 **
105851 ** In its default configuration, SQLite API routines return one of 26 integer
105852 ** [SQLITE_OK | result codes].  However, experience has shown that
105853 ** many of these result codes are too course-grained.  They do not provide as
105854 ** much information about problems as programmers might like.  In an effort to
105855 ** address this, newer versions of SQLite (version 3.3.8 and later) include
105856 ** support for additional result codes that provide more detailed information
105857 ** about errors. {F10221} The extended result codes are enabled or disabled
105858 ** for each database connection using the [sqlite3_extended_result_codes()]
105859 ** API. {END}
105860 ** 
105861 ** Some of the available extended result codes are listed above.
105862 ** We expect the number of extended result codes will be expand
105863 ** over time.  {U10422} Software that uses extended result codes should expect
105864 ** to see new result codes in future releases of SQLite. {END}
105865 ** 
105866 ** {F10223} The symbolic name for an extended result code always contains
105867 ** a related primary result code as a prefix. {F10224} Primary result
105868 ** codes contain a single "_" character.  {F10225} Extended result codes
105869 ** contain two or more "_" characters. {F10226} The numeric value of an
105870 ** extended result code can be converted to its
105871 ** corresponding primary result code by masking off the lower 8 bytes. {END}
105872 **
105873 ** The SQLITE_OK result code will never be extended.  It will always
105874 ** be exactly zero.
105875 */
105876 #define SQLITE_IOERR_READ          (SQLITE_IOERR | (1<<8))
105877 #define SQLITE_IOERR_SHORT_READ    (SQLITE_IOERR | (2<<8))
105878 #define SQLITE_IOERR_WRITE         (SQLITE_IOERR | (3<<8))
105879 #define SQLITE_IOERR_FSYNC         (SQLITE_IOERR | (4<<8))
105880 #define SQLITE_IOERR_DIR_FSYNC     (SQLITE_IOERR | (5<<8))
105881 #define SQLITE_IOERR_TRUNCATE      (SQLITE_IOERR | (6<<8))
105882 #define SQLITE_IOERR_FSTAT         (SQLITE_IOERR | (7<<8))
105883 #define SQLITE_IOERR_UNLOCK        (SQLITE_IOERR | (8<<8))
105884 #define SQLITE_IOERR_RDLOCK        (SQLITE_IOERR | (9<<8))
105885 #define SQLITE_IOERR_DELETE        (SQLITE_IOERR | (10<<8))
105886 #define SQLITE_IOERR_BLOCKED       (SQLITE_IOERR | (11<<8))
105887 #define SQLITE_IOERR_NOMEM         (SQLITE_IOERR | (12<<8))
105888
105889 /*
105890 ** CAPI3REF: Flags For File Open Operations {F10230}
105891 **
105892 ** {F10231} Some combination of the these bit values are used as the
105893 ** third argument to the [sqlite3_open_v2()] interface and
105894 ** as fourth argument to the xOpen method of the
105895 ** [sqlite3_vfs] object.
105896 */
105897 #define SQLITE_OPEN_READONLY         0x00000001
105898 #define SQLITE_OPEN_READWRITE        0x00000002
105899 #define SQLITE_OPEN_CREATE           0x00000004
105900 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008
105901 #define SQLITE_OPEN_EXCLUSIVE        0x00000010
105902 #define SQLITE_OPEN_MAIN_DB          0x00000100
105903 #define SQLITE_OPEN_TEMP_DB          0x00000200
105904 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400
105905 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800
105906 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000
105907 #define SQLITE_OPEN_SUBJOURNAL       0x00002000
105908 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000
105909
105910 /*
105911 ** CAPI3REF: Device Characteristics {F10240}
105912 **
105913 ** {F10241} The xDeviceCapabilities method of the [sqlite3_io_methods]
105914 ** object returns an integer which is a vector of the these
105915 ** bit values expressing I/O characteristics of the mass storage
105916 ** device that holds the file that the [sqlite3_io_methods]
105917 ** refers to. {END}
105918 **
105919 ** {F10242} The SQLITE_IOCAP_ATOMIC property means that all writes of
105920 ** any size are atomic.  {F10243} The SQLITE_IOCAP_ATOMICnnn values
105921 ** mean that writes of blocks that are nnn bytes in size and
105922 ** are aligned to an address which is an integer multiple of
105923 ** nnn are atomic.  {F10244} The SQLITE_IOCAP_SAFE_APPEND value means
105924 ** that when data is appended to a file, the data is appended
105925 ** first then the size of the file is extended, never the other
105926 ** way around.  {F10245} The SQLITE_IOCAP_SEQUENTIAL property means that
105927 ** information is written to disk in the same order as calls
105928 ** to xWrite().
105929 */
105930 #define SQLITE_IOCAP_ATOMIC          0x00000001
105931 #define SQLITE_IOCAP_ATOMIC512       0x00000002
105932 #define SQLITE_IOCAP_ATOMIC1K        0x00000004
105933 #define SQLITE_IOCAP_ATOMIC2K        0x00000008
105934 #define SQLITE_IOCAP_ATOMIC4K        0x00000010
105935 #define SQLITE_IOCAP_ATOMIC8K        0x00000020
105936 #define SQLITE_IOCAP_ATOMIC16K       0x00000040
105937 #define SQLITE_IOCAP_ATOMIC32K       0x00000080
105938 #define SQLITE_IOCAP_ATOMIC64K       0x00000100
105939 #define SQLITE_IOCAP_SAFE_APPEND     0x00000200
105940 #define SQLITE_IOCAP_SEQUENTIAL      0x00000400
105941
105942 /*
105943 ** CAPI3REF: File Locking Levels {F10250}
105944 **
105945 ** {F10251} SQLite uses one of the following integer values as the second
105946 ** argument to calls it makes to the xLock() and xUnlock() methods
105947 ** of an [sqlite3_io_methods] object. {END}
105948 */
105949 #define SQLITE_LOCK_NONE          0
105950 #define SQLITE_LOCK_SHARED        1
105951 #define SQLITE_LOCK_RESERVED      2
105952 #define SQLITE_LOCK_PENDING       3
105953 #define SQLITE_LOCK_EXCLUSIVE     4
105954
105955 /*
105956 ** CAPI3REF: Synchronization Type Flags {F10260}
105957 **
105958 ** {F10261} When SQLite invokes the xSync() method of an
105959 ** [sqlite3_io_methods] object it uses a combination of the
105960 ** these integer values as the second argument.
105961 **
105962 ** {F10262} When the SQLITE_SYNC_DATAONLY flag is used, it means that the
105963 ** sync operation only needs to flush data to mass storage.  Inode
105964 ** information need not be flushed. {F10263} The SQLITE_SYNC_NORMAL means 
105965 ** to use normal fsync() semantics. {F10264} The SQLITE_SYNC_FULL flag means 
105966 ** to use Mac OS-X style fullsync instead of fsync().
105967 */
105968 #define SQLITE_SYNC_NORMAL        0x00002
105969 #define SQLITE_SYNC_FULL          0x00003
105970 #define SQLITE_SYNC_DATAONLY      0x00010
105971
105972
105973 /*
105974 ** CAPI3REF: OS Interface Open File Handle {F11110}
105975 **
105976 ** An [sqlite3_file] object represents an open file in the OS
105977 ** interface layer.  Individual OS interface implementations will
105978 ** want to subclass this object by appending additional fields
105979 ** for their own use.  The pMethods entry is a pointer to an
105980 ** [sqlite3_io_methods] object that defines methods for performing
105981 ** I/O operations on the open file.
105982 */
105983 typedef struct sqlite3_file sqlite3_file;
105984 struct sqlite3_file {
105985   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
105986 };
105987
105988 /*
105989 ** CAPI3REF: OS Interface File Virtual Methods Object {F11120}
105990 **
105991 ** Every file opened by the [sqlite3_vfs] xOpen method contains a pointer to
105992 ** an instance of the this object.  This object defines the
105993 ** methods used to perform various operations against the open file.
105994 **
105995 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
105996 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
105997 *  The second choice is an
105998 ** OS-X style fullsync.  The SQLITE_SYNC_DATA flag may be ORed in to
105999 ** indicate that only the data of the file and not its inode needs to be
106000 ** synced.
106001 ** 
106002 ** The integer values to xLock() and xUnlock() are one of
106003 ** <ul>
106004 ** <li> [SQLITE_LOCK_NONE],
106005 ** <li> [SQLITE_LOCK_SHARED],
106006 ** <li> [SQLITE_LOCK_RESERVED],
106007 ** <li> [SQLITE_LOCK_PENDING], or
106008 ** <li> [SQLITE_LOCK_EXCLUSIVE].
106009 ** </ul>
106010 ** xLock() increases the lock. xUnlock() decreases the lock.  
106011 ** The xCheckReservedLock() method looks
106012 ** to see if any database connection, either in this
106013 ** process or in some other process, is holding an RESERVED,
106014 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
106015 ** if such a lock exists and false if not.
106016 ** 
106017 ** The xFileControl() method is a generic interface that allows custom
106018 ** VFS implementations to directly control an open file using the
106019 ** [sqlite3_file_control()] interface.  The second "op" argument
106020 ** is an integer opcode.   The third
106021 ** argument is a generic pointer which is intended to be a pointer
106022 ** to a structure that may contain arguments or space in which to
106023 ** write return values.  Potential uses for xFileControl() might be
106024 ** functions to enable blocking locks with timeouts, to change the
106025 ** locking strategy (for example to use dot-file locks), to inquire
106026 ** about the status of a lock, or to break stale locks.  The SQLite
106027 ** core reserves opcodes less than 100 for its own use. 
106028 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
106029 ** Applications that define a custom xFileControl method should use opcodes 
106030 ** greater than 100 to avoid conflicts.
106031 **
106032 ** The xSectorSize() method returns the sector size of the
106033 ** device that underlies the file.  The sector size is the
106034 ** minimum write that can be performed without disturbing
106035 ** other bytes in the file.  The xDeviceCharacteristics()
106036 ** method returns a bit vector describing behaviors of the
106037 ** underlying device:
106038 **
106039 ** <ul>
106040 ** <li> [SQLITE_IOCAP_ATOMIC]
106041 ** <li> [SQLITE_IOCAP_ATOMIC512]
106042 ** <li> [SQLITE_IOCAP_ATOMIC1K]
106043 ** <li> [SQLITE_IOCAP_ATOMIC2K]
106044 ** <li> [SQLITE_IOCAP_ATOMIC4K]
106045 ** <li> [SQLITE_IOCAP_ATOMIC8K]
106046 ** <li> [SQLITE_IOCAP_ATOMIC16K]
106047 ** <li> [SQLITE_IOCAP_ATOMIC32K]
106048 ** <li> [SQLITE_IOCAP_ATOMIC64K]
106049 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
106050 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
106051 ** </ul>
106052 **
106053 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
106054 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
106055 ** mean that writes of blocks that are nnn bytes in size and
106056 ** are aligned to an address which is an integer multiple of
106057 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
106058 ** that when data is appended to a file, the data is appended
106059 ** first then the size of the file is extended, never the other
106060 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
106061 ** information is written to disk in the same order as calls
106062 ** to xWrite().
106063 */
106064 typedef struct sqlite3_io_methods sqlite3_io_methods;
106065 struct sqlite3_io_methods {
106066   int iVersion;
106067   int (*xClose)(sqlite3_file*);
106068   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
106069   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
106070   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
106071   int (*xSync)(sqlite3_file*, int flags);
106072   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
106073   int (*xLock)(sqlite3_file*, int);
106074   int (*xUnlock)(sqlite3_file*, int);
106075   int (*xCheckReservedLock)(sqlite3_file*);
106076   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
106077   int (*xSectorSize)(sqlite3_file*);
106078   int (*xDeviceCharacteristics)(sqlite3_file*);
106079   /* Additional methods may be added in future releases */
106080 };
106081
106082 /*
106083 ** CAPI3REF: Standard File Control Opcodes {F11310}
106084 **
106085 ** These integer constants are opcodes for the xFileControl method
106086 ** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()]
106087 ** interface.
106088 **
106089 ** {F11311} The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
106090 ** opcode cases the xFileControl method to write the current state of
106091 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
106092 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
106093 ** into an integer that the pArg argument points to. {F11312} This capability
106094 ** is used during testing and only needs to be supported when SQLITE_TEST
106095 ** is defined.
106096 */
106097 #define SQLITE_FCNTL_LOCKSTATE        1
106098
106099 /*
106100 ** CAPI3REF: Mutex Handle {F17110}
106101 **
106102 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
106103 ** abstract type for a mutex object.  {F17111} The SQLite core never looks
106104 ** at the internal representation of an [sqlite3_mutex]. {END} It only
106105 ** deals with pointers to the [sqlite3_mutex] object.
106106 **
106107 ** Mutexes are created using [sqlite3_mutex_alloc()].
106108 */
106109 typedef struct sqlite3_mutex sqlite3_mutex;
106110
106111 /*
106112 ** CAPI3REF: OS Interface Object {F11140}
106113 **
106114 ** An instance of this object defines the interface between the
106115 ** SQLite core and the underlying operating system.  The "vfs"
106116 ** in the name of the object stands for "virtual file system".
106117 **
106118 ** The iVersion field is initially 1 but may be larger for future
106119 ** versions of SQLite.  Additional fields may be appended to this
106120 ** object when the iVersion value is increased.
106121 **
106122 ** The szOsFile field is the size of the subclassed [sqlite3_file]
106123 ** structure used by this VFS.  mxPathname is the maximum length of
106124 ** a pathname in this VFS.
106125 **
106126 ** Registered vfs modules are kept on a linked list formed by
106127 ** the pNext pointer.  The [sqlite3_vfs_register()]
106128 ** and [sqlite3_vfs_unregister()] interfaces manage this list
106129 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
106130 ** searches the list.
106131 **
106132 ** The pNext field is the only fields in the sqlite3_vfs 
106133 ** structure that SQLite will ever modify.  SQLite will only access
106134 ** or modify this field while holding a particular static mutex.
106135 ** The application should never modify anything within the sqlite3_vfs
106136 ** object once the object has been registered.
106137 **
106138 ** The zName field holds the name of the VFS module.  The name must
106139 ** be unique across all VFS modules.
106140 **
106141 ** {F11141} SQLite will guarantee that the zFilename string passed to
106142 ** xOpen() is a full pathname as generated by xFullPathname() and
106143 ** that the string will be valid and unchanged until xClose() is
106144 ** called.  {END} So the [sqlite3_file] can store a pointer to the
106145 ** filename if it needs to remember the filename for some reason.
106146 **
106147 ** {F11142} The flags argument to xOpen() includes all bits set in
106148 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
106149 ** or [sqlite3_open16()] is used, then flags includes at least
106150 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END}
106151 ** If xOpen() opens a file read-only then it sets *pOutFlags to
106152 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be
106153 ** set.
106154 ** 
106155 ** {F11143} SQLite will also add one of the following flags to the xOpen()
106156 ** call, depending on the object being opened:
106157 ** 
106158 ** <ul>
106159 ** <li>  [SQLITE_OPEN_MAIN_DB]
106160 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
106161 ** <li>  [SQLITE_OPEN_TEMP_DB]
106162 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
106163 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
106164 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
106165 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
106166 ** </ul> {END}
106167 **
106168 ** The file I/O implementation can use the object type flags to
106169 ** changes the way it deals with files.  For example, an application
106170 ** that does not care about crash recovery or rollback, might make
106171 ** the open of a journal file a no-op.  Writes to this journal are
106172 ** also a no-op.  Any attempt to read the journal return SQLITE_IOERR.
106173 ** Or the implementation might recognize the a database file will
106174 ** be doing page-aligned sector reads and writes in a random order
106175 ** and set up its I/O subsystem accordingly.
106176 ** 
106177 ** {F11144} SQLite might also add one of the following flags to the xOpen
106178 ** method:
106179 ** 
106180 ** <ul>
106181 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
106182 ** <li> [SQLITE_OPEN_EXCLUSIVE]
106183 ** </ul>
106184 ** 
106185 ** {F11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
106186 ** deleted when it is closed.  {F11146} The [SQLITE_OPEN_DELETEONCLOSE]
106187 ** will be set for TEMP  databases, journals and for subjournals. 
106188 ** {F11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened
106189 ** for exclusive access.  This flag is set for all files except
106190 ** for the main database file. {END}
106191 ** 
106192 ** {F11148} At least szOsFile bytes of memory is allocated by SQLite 
106193 ** to hold the  [sqlite3_file] structure passed as the third 
106194 ** argument to xOpen.  {END}  The xOpen method does not have to
106195 ** allocate the structure; it should just fill it in.
106196 ** 
106197 ** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] 
106198 ** to test for the existance of a file,
106199 ** or [SQLITE_ACCESS_READWRITE] to test to see
106200 ** if a file is readable and writable, or [SQLITE_ACCESS_READ]
106201 ** to test to see if a file is at least readable.  {END} The file can be a 
106202 ** directory.
106203 ** 
106204 ** {F11150} SQLite will always allocate at least mxPathname+1 byte for
106205 ** the output buffers for xGetTempname and xFullPathname. {F11151} The exact
106206 ** size of the output buffer is also passed as a parameter to both 
106207 ** methods. {END} If the output buffer is not large enough, SQLITE_CANTOPEN
106208 ** should be returned. As this is handled as a fatal error by SQLite,
106209 ** vfs implementations should endeavor to prevent this by setting 
106210 ** mxPathname to a sufficiently large value.
106211 ** 
106212 ** The xRandomness(), xSleep(), and xCurrentTime() interfaces
106213 ** are not strictly a part of the filesystem, but they are
106214 ** included in the VFS structure for completeness.
106215 ** The xRandomness() function attempts to return nBytes bytes
106216 ** of good-quality randomness into zOut.  The return value is
106217 ** the actual number of bytes of randomness obtained.  The
106218 ** xSleep() method cause the calling thread to sleep for at
106219 ** least the number of microseconds given.  The xCurrentTime()
106220 ** method returns a Julian Day Number for the current date and
106221 ** time.
106222 */
106223 typedef struct sqlite3_vfs sqlite3_vfs;
106224 struct sqlite3_vfs {
106225   int iVersion;            /* Structure version number */
106226   int szOsFile;            /* Size of subclassed sqlite3_file */
106227   int mxPathname;          /* Maximum file pathname length */
106228   sqlite3_vfs *pNext;      /* Next registered VFS */
106229   const char *zName;       /* Name of this virtual file system */
106230   void *pAppData;          /* Pointer to application-specific data */
106231   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
106232                int flags, int *pOutFlags);
106233   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
106234   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags);
106235   int (*xGetTempname)(sqlite3_vfs*, int nOut, char *zOut);
106236   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
106237   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
106238   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
106239   void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol);
106240   void (*xDlClose)(sqlite3_vfs*, void*);
106241   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
106242   int (*xSleep)(sqlite3_vfs*, int microseconds);
106243   int (*xCurrentTime)(sqlite3_vfs*, double*);
106244   /* New fields may be appended in figure versions.  The iVersion
106245   ** value will increment whenever this happens. */
106246 };
106247
106248 /*
106249 ** CAPI3REF: Flags for the xAccess VFS method {F11190}
106250 **
106251 ** {F11191} These integer constants can be used as the third parameter to
106252 ** the xAccess method of an [sqlite3_vfs] object. {END}  They determine
106253 ** the kind of what kind of permissions the xAccess method is
106254 ** looking for.  {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method
106255 ** simply checks to see if the file exists. {F11193} With
106256 ** SQLITE_ACCESS_READWRITE, the xAccess method checks to see
106257 ** if the file is both readable and writable.  {F11194} With
106258 ** SQLITE_ACCESS_READ the xAccess method
106259 ** checks to see if the file is readable.
106260 */
106261 #define SQLITE_ACCESS_EXISTS    0
106262 #define SQLITE_ACCESS_READWRITE 1
106263 #define SQLITE_ACCESS_READ      2
106264
106265 /*
106266 ** CAPI3REF: Enable Or Disable Extended Result Codes {F12200}
106267 **
106268 ** {F12201} The sqlite3_extended_result_codes() routine enables or disables the
106269 ** [SQLITE_IOERR_READ | extended result codes] feature on a database
106270 ** connection if its 2nd parameter is
106271 ** non-zero or zero, respectively. {F12202}
106272 ** By default, SQLite API routines return one of only 26 integer
106273 ** [SQLITE_OK | result codes].  {F12203} When extended result codes
106274 ** are enabled by this routine, the repetoire of result codes can be
106275 ** much larger and can (hopefully) provide more detailed information
106276 ** about the cause of an error.
106277 **
106278 ** {F12204} The second argument is a boolean value that turns extended result
106279 ** codes on and off. {F12205} Extended result codes are off by default for
106280 ** backwards compatibility with older versions of SQLite.
106281 */
106282 int sqlite3_extended_result_codes(sqlite3*, int onoff);
106283
106284 /*
106285 ** CAPI3REF: Last Insert Rowid {F12220}
106286 **
106287 ** {F12221} Each entry in an SQLite table has a unique 64-bit signed
106288 ** integer key called the "rowid".  {F12222} The rowid is always available
106289 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
106290 ** names are not also used by explicitly declared columns. {F12223} If
106291 ** the table has a column of type INTEGER PRIMARY KEY then that column
106292 ** is another an alias for the rowid.
106293 **
106294 ** {F12224} This routine returns the rowid of the most recent
106295 ** successful INSERT into the database from the database connection
106296 ** shown in the first argument.  {F12225} If no successful inserts
106297 ** have ever occurred on this database connection, zero is returned.
106298 **
106299 ** {F12226} If an INSERT occurs within a trigger, then the rowid of the
106300 ** inserted row is returned by this routine as long as the trigger
106301 ** is running.  {F12227} But once the trigger terminates, the value returned
106302 ** by this routine reverts to the last value inserted before the
106303 ** trigger fired.
106304 **
106305 ** {F12228} An INSERT that fails due to a constraint violation is not a
106306 ** successful insert and does not change the value returned by this
106307 ** routine.  {F12229} Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
106308 ** and INSERT OR ABORT make no changes to the return value of this
106309 ** routine when their insertion fails.  {F12231} When INSERT OR REPLACE 
106310 ** encounters a constraint violation, it does not fail.  The
106311 ** INSERT continues to completion after deleting rows that caused
106312 ** the constraint problem so INSERT OR REPLACE will always change
106313 ** the return value of this interface. 
106314 **
106315 ** {UF12232} If another thread does a new insert on the same database connection
106316 ** while this routine is running and thus changes the last insert rowid,
106317 ** then the return value of this routine is undefined.
106318 */
106319 sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
106320
106321 /*
106322 ** CAPI3REF: Count The Number Of Rows Modified {F12240}
106323 **
106324 ** {F12241} This function returns the number of database rows that were changed
106325 ** or inserted or deleted by the most recently completed SQL statement
106326 ** on the connection specified by the first parameter. {F12242} Only
106327 ** changes that are directly specified by the INSERT, UPDATE, or
106328 ** DELETE statement are counted.  Auxiliary changes caused by
106329 ** triggers are not counted. {F12243} Use the [sqlite3_total_changes()] function
106330 ** to find the total number of changes including changes caused by triggers.
106331 **
106332 ** {F12244} Within the body of a trigger, the sqlite3_changes() interface
106333 ** can be called to find the number of
106334 ** changes in the most recently completed INSERT, UPDATE, or DELETE
106335 ** statement within the body of the same trigger.
106336 **
106337 ** {F12245} All changes are counted, even if they are later undone by a
106338 ** ROLLBACK or ABORT.  {F12246} Except, changes associated with creating and
106339 ** dropping tables are not counted.
106340 **
106341 ** {F12247} If a callback invokes [sqlite3_exec()] or [sqlite3_step()]
106342 ** recursively, then the changes in the inner, recursive call are
106343 ** counted together with the changes in the outer call.
106344 **
106345 ** {F12248} SQLite implements the command "DELETE FROM table" without
106346 ** a WHERE clause by dropping and recreating the table.  (This is much
106347 ** faster than going through and deleting individual elements from the
106348 ** table.)  Because of this optimization, the change count for 
106349 ** "DELETE FROM table" will be zero regardless of the number of elements
106350 ** that were originally in the table. {F12251} To get an accurate count
106351 ** of the number of rows deleted, use
106352 ** "DELETE FROM table WHERE 1" instead.
106353 **
106354 ** {UF12252} If another thread makes changes on the same database connection
106355 ** while this routine is running then the return value of this routine
106356 ** is undefined.
106357 */
106358 int sqlite3_changes(sqlite3*);
106359
106360 /*
106361 ** CAPI3REF: Total Number Of Rows Modified {F12260}
106362 ***
106363 ** {F12261} This function returns the number of database rows that have been
106364 ** modified by INSERT, UPDATE or DELETE statements since the database handle
106365 ** was opened. {F12262} The count includes UPDATE, INSERT and DELETE 
106366 ** statements executed as part of trigger programs.  {F12263} All changes
106367 ** are counted as soon as the statement that makes them is completed 
106368 ** (when the statement handle is passed to [sqlite3_reset()] or 
106369 ** [sqlite3_finalize()]). {END}
106370 **
106371 ** See also the [sqlite3_change()] interface.
106372 **
106373 ** {F12265} SQLite implements the command "DELETE FROM table" without
106374 ** a WHERE clause by dropping and recreating the table.  (This is much
106375 ** faster than going
106376 ** through and deleting individual elements form the table.)  Because of
106377 ** this optimization, the change count for "DELETE FROM table" will be
106378 ** zero regardless of the number of elements that were originally in the
106379 ** table. To get an accurate count of the number of rows deleted, use
106380 ** "DELETE FROM table WHERE 1" instead.
106381 **
106382 ** {U12264} If another thread makes changes on the same database connection
106383 ** while this routine is running then the return value of this routine
106384 ** is undefined. {END}
106385 */
106386 int sqlite3_total_changes(sqlite3*);
106387
106388 /*
106389 ** CAPI3REF: Interrupt A Long-Running Query {F12270}
106390 **
106391 ** {F12271} This function causes any pending database operation to abort and
106392 ** return at its earliest opportunity. {END} This routine is typically
106393 ** called in response to a user action such as pressing "Cancel"
106394 ** or Ctrl-C where the user wants a long query operation to halt
106395 ** immediately.
106396 **
106397 ** {F12272} It is safe to call this routine from a thread different from the
106398 ** thread that is currently running the database operation. {U12273} But it
106399 ** is not safe to call this routine with a database connection that
106400 ** is closed or might close before sqlite3_interrupt() returns.
106401 **
106402 ** If an SQL is very nearly finished at the time when sqlite3_interrupt()
106403 ** is called, then it might not have an opportunity to be interrupted.
106404 ** It might continue to completion.
106405 ** {F12274} The SQL operation that is interrupted will return
106406 ** [SQLITE_INTERRUPT].  {F12275} If the interrupted SQL operation is an
106407 ** INSERT, UPDATE, or DELETE that is inside an explicit transaction, 
106408 ** then the entire transaction will be rolled back automatically.
106409 ** {F12276} A call to sqlite3_interrupt() has no effect on SQL statements
106410 ** that are started after sqlite3_interrupt() returns.
106411 */
106412 void sqlite3_interrupt(sqlite3*);
106413
106414 /*
106415 ** CAPI3REF: Determine If An SQL Statement Is Complete {F10510}
106416 **
106417 ** These routines are useful for command-line input to determine if the
106418 ** currently entered text seems to form complete a SQL statement or
106419 ** if additional input is needed before sending the text into
106420 ** SQLite for parsing.  These routines return true if the input string
106421 ** appears to be a complete SQL statement.  A statement is judged to be
106422 ** complete if it ends with a semicolon and is not a fragment of a
106423 ** CREATE TRIGGER statement.  These routines do not parse the SQL and
106424 ** so will not detect syntactically incorrect SQL.
106425 **
106426 ** {F10511} These functions return true if the given input string 
106427 ** ends with a semicolon optionally followed by whitespace or
106428 ** comments. {F10512} For sqlite3_complete(),
106429 ** the parameter must be a zero-terminated UTF-8 string. {F10513} For
106430 ** sqlite3_complete16(), a zero-terminated machine byte order UTF-16 string
106431 ** is required.  {F10514} These routines return false if the terminal
106432 ** semicolon is within a comment, a string literal or a quoted identifier
106433 ** (in other words if the final semicolon is not really a separate token
106434 ** but part of a larger token) or if the final semicolon is
106435 ** in between the BEGIN and END keywords of a CREATE TRIGGER statement.
106436 ** {END}
106437 */
106438 int sqlite3_complete(const char *sql);
106439 int sqlite3_complete16(const void *sql);
106440
106441 /*
106442 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310}
106443 **
106444 ** {F12311} This routine identifies a callback function that might be
106445 ** invoked whenever an attempt is made to open a database table 
106446 ** that another thread or process has locked.
106447 ** {F12312} If the busy callback is NULL, then [SQLITE_BUSY]
106448 ** or [SQLITE_IOERR_BLOCKED]
106449 ** is returned immediately upon encountering the lock.
106450 ** {F12313} If the busy callback is not NULL, then the
106451 ** callback will be invoked with two arguments.  {F12314} The
106452 ** first argument to the handler is a copy of the void* pointer which
106453 ** is the third argument to this routine.  {F12315} The second argument to
106454 ** the handler is the number of times that the busy handler has
106455 ** been invoked for this locking event.  {F12316} If the
106456 ** busy callback returns 0, then no additional attempts are made to
106457 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
106458 ** {F12317} If the callback returns non-zero, then another attempt
106459 ** is made to open the database for reading and the cycle repeats.
106460 **
106461 ** The presence of a busy handler does not guarantee that
106462 ** it will be invoked when there is lock contention. {F12319}
106463 ** If SQLite determines that invoking the busy handler could result in
106464 ** a deadlock, it will go ahead and return [SQLITE_BUSY] or
106465 ** [SQLITE_IOERR_BLOCKED] instead of invoking the
106466 ** busy handler. {END}
106467 ** Consider a scenario where one process is holding a read lock that
106468 ** it is trying to promote to a reserved lock and
106469 ** a second process is holding a reserved lock that it is trying
106470 ** to promote to an exclusive lock.  The first process cannot proceed
106471 ** because it is blocked by the second and the second process cannot
106472 ** proceed because it is blocked by the first.  If both processes
106473 ** invoke the busy handlers, neither will make any progress.  Therefore,
106474 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
106475 ** will induce the first process to release its read lock and allow
106476 ** the second process to proceed.
106477 **
106478 ** {F12321} The default busy callback is NULL. {END}
106479 **
106480 ** {F12322} The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
106481 ** when SQLite is in the middle of a large transaction where all the
106482 ** changes will not fit into the in-memory cache.  {F12323} SQLite will
106483 ** already hold a RESERVED lock on the database file, but it needs
106484 ** to promote this lock to EXCLUSIVE so that it can spill cache
106485 ** pages into the database file without harm to concurrent
106486 ** readers.  {F12324} If it is unable to promote the lock, then the in-memory
106487 ** cache will be left in an inconsistent state and so the error
106488 ** code is promoted from the relatively benign [SQLITE_BUSY] to
106489 ** the more severe [SQLITE_IOERR_BLOCKED].  {F12325} This error code promotion
106490 ** forces an automatic rollback of the changes. {END} See the
106491 ** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError">
106492 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
106493 ** this is important.
106494 **      
106495 ** {F12326} Sqlite is re-entrant, so the busy handler may start a new
106496 ** query. {END} (It is not clear why anyone would every want to do this,
106497 ** but it is allowed, in theory.) {U12327} But the busy handler may not
106498 ** close the database.  Closing the database from a busy handler will delete 
106499 ** data structures out from under the executing query and will 
106500 ** probably result in a segmentation fault or other runtime error. {END}
106501 **
106502 ** {F12328} There can only be a single busy handler defined for each database
106503 ** connection.  Setting a new busy handler clears any previous one. 
106504 ** {F12329} Note that calling [sqlite3_busy_timeout()] will also set or clear
106505 ** the busy handler.
106506 **
106507 ** {F12331} When operating in [sqlite3_enable_shared_cache | shared cache mode],
106508 ** only a single busy handler can be defined for each database file.
106509 ** So if two database connections share a single cache, then changing
106510 ** the busy handler on one connection will also change the busy
106511 ** handler in the other connection.  {F12332} The busy handler is invoked
106512 ** in the thread that was running when the lock contention occurs.
106513 */
106514 int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
106515
106516 /*
106517 ** CAPI3REF: Set A Busy Timeout {F12340}
106518 **
106519 ** {F12341} This routine sets a [sqlite3_busy_handler | busy handler]
106520 ** that sleeps for a while when a
106521 ** table is locked.  {F12342} The handler will sleep multiple times until 
106522 ** at least "ms" milliseconds of sleeping have been done. {F12343} After
106523 ** "ms" milliseconds of sleeping, the handler returns 0 which
106524 ** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
106525 **
106526 ** {F12344} Calling this routine with an argument less than or equal to zero
106527 ** turns off all busy handlers.
106528 **
106529 ** {F12345} There can only be a single busy handler for a particular database
106530 ** connection.  If another busy handler was defined  
106531 ** (using [sqlite3_busy_handler()]) prior to calling
106532 ** this routine, that other busy handler is cleared.
106533 */
106534 int sqlite3_busy_timeout(sqlite3*, int ms);
106535
106536 /*
106537 ** CAPI3REF: Convenience Routines For Running Queries {F12370}
106538 **
106539 ** This next routine is a convenience wrapper around [sqlite3_exec()].
106540 ** {F12371} Instead of invoking a user-supplied callback for each row of the
106541 ** result, this routine remembers each row of the result in memory
106542 ** obtained from [sqlite3_malloc()], then returns all of the result after the
106543 ** query has finished. {F12372}
106544 **
106545 ** As an example, suppose the query result where this table:
106546 **
106547 ** <blockquote><pre>
106548 **        Name        | Age
106549 **        -----------------------
106550 **        Alice       | 43
106551 **        Bob         | 28
106552 **        Cindy       | 21
106553 ** </pre></blockquote>
106554 **
106555 ** If the 3rd argument were &azResult then after the function returns
106556 ** azResult will contain the following data:
106557 **
106558 ** <blockquote><pre>
106559 **        azResult&#91;0] = "Name";
106560 **        azResult&#91;1] = "Age";
106561 **        azResult&#91;2] = "Alice";
106562 **        azResult&#91;3] = "43";
106563 **        azResult&#91;4] = "Bob";
106564 **        azResult&#91;5] = "28";
106565 **        azResult&#91;6] = "Cindy";
106566 **        azResult&#91;7] = "21";
106567 ** </pre></blockquote>
106568 **
106569 ** Notice that there is an extra row of data containing the column
106570 ** headers.  But the *nrow return value is still 3.  *ncolumn is
106571 ** set to 2.  In general, the number of values inserted into azResult
106572 ** will be ((*nrow) + 1)*(*ncolumn).
106573 **
106574 ** {U12374} After the calling function has finished using the result, it should 
106575 ** pass the result data pointer to sqlite3_free_table() in order to 
106576 ** release the memory that was malloc-ed.  Because of the way the 
106577 ** [sqlite3_malloc()] happens, the calling function must not try to call 
106578 ** [sqlite3_free()] directly.  Only [sqlite3_free_table()] is able to release 
106579 ** the memory properly and safely. {END}
106580 **
106581 ** {F12373} The return value of this routine is the same as
106582 ** from [sqlite3_exec()].
106583 */
106584 int sqlite3_get_table(
106585   sqlite3*,              /* An open database */
106586   const char *sql,       /* SQL to be executed */
106587   char ***resultp,       /* Result written to a char *[]  that this points to */
106588   int *nrow,             /* Number of result rows written here */
106589   int *ncolumn,          /* Number of result columns written here */
106590   char **errmsg          /* Error msg written here */
106591 );
106592 void sqlite3_free_table(char **result);
106593
106594 /*
106595 ** CAPI3REF: Formatted String Printing Functions {F17400}
106596 **
106597 ** These routines are workalikes of the "printf()" family of functions
106598 ** from the standard C library.
106599 **
106600 ** {F17401} The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
106601 ** results into memory obtained from [sqlite3_malloc()].
106602 ** {U17402} The strings returned by these two routines should be
106603 ** released by [sqlite3_free()]. {F17403}  Both routines return a
106604 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
106605 ** memory to hold the resulting string.
106606 **
106607 ** {F17404} In sqlite3_snprintf() routine is similar to "snprintf()" from
106608 ** the standard C library.  The result is written into the
106609 ** buffer supplied as the second parameter whose size is given by
106610 ** the first parameter. {END} Note that the order of the
106611 ** first two parameters is reversed from snprintf().  This is an
106612 ** historical accident that cannot be fixed without breaking
106613 ** backwards compatibility.  {F17405} Note also that sqlite3_snprintf()
106614 ** returns a pointer to its buffer instead of the number of
106615 ** characters actually written into the buffer. {END} We admit that
106616 ** the number of characters written would be a more useful return
106617 ** value but we cannot change the implementation of sqlite3_snprintf()
106618 ** now without breaking compatibility.
106619 **
106620 ** {F17406} As long as the buffer size is greater than zero, sqlite3_snprintf()
106621 ** guarantees that the buffer is always zero-terminated. {F17407} The first
106622 ** parameter "n" is the total size of the buffer, including space for
106623 ** the zero terminator.  {END} So the longest string that can be completely
106624 ** written will be n-1 characters.
106625 **
106626 ** These routines all implement some additional formatting
106627 ** options that are useful for constructing SQL statements.
106628 ** All of the usual printf formatting options apply.  In addition, there
106629 ** is are "%q", "%Q", and "%z" options.
106630 **
106631 ** {F17410} The %q option works like %s in that it substitutes a null-terminated
106632 ** string from the argument list.  But %q also doubles every '\'' character.
106633 ** %q is designed for use inside a string literal. {END} By doubling each '\''
106634 ** character it escapes that character and allows it to be inserted into
106635 ** the string.
106636 **
106637 ** For example, so some string variable contains text as follows:
106638 **
106639 ** <blockquote><pre>
106640 **  char *zText = "It's a happy day!";
106641 ** </pre></blockquote>
106642 **
106643 ** One can use this text in an SQL statement as follows:
106644 **
106645 ** <blockquote><pre>
106646 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
106647 **  sqlite3_exec(db, zSQL, 0, 0, 0);
106648 **  sqlite3_free(zSQL);
106649 ** </pre></blockquote>
106650 **
106651 ** Because the %q format string is used, the '\'' character in zText
106652 ** is escaped and the SQL generated is as follows:
106653 **
106654 ** <blockquote><pre>
106655 **  INSERT INTO table1 VALUES('It''s a happy day!')
106656 ** </pre></blockquote>
106657 **
106658 ** This is correct.  Had we used %s instead of %q, the generated SQL
106659 ** would have looked like this:
106660 **
106661 ** <blockquote><pre>
106662 **  INSERT INTO table1 VALUES('It's a happy day!');
106663 ** </pre></blockquote>
106664 **
106665 ** This second example is an SQL syntax error.  As a general rule you
106666 ** should always use %q instead of %s when inserting text into a string 
106667 ** literal.
106668 **
106669 ** {F17411} The %Q option works like %q except it also adds single quotes around
106670 ** the outside of the total string.  Or if the parameter in the argument
106671 ** list is a NULL pointer, %Q substitutes the text "NULL" (without single
106672 ** quotes) in place of the %Q option. {END}  So, for example, one could say:
106673 **
106674 ** <blockquote><pre>
106675 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
106676 **  sqlite3_exec(db, zSQL, 0, 0, 0);
106677 **  sqlite3_free(zSQL);
106678 ** </pre></blockquote>
106679 **
106680 ** The code above will render a correct SQL statement in the zSQL
106681 ** variable even if the zText variable is a NULL pointer.
106682 **
106683 ** {F17412} The "%z" formatting option works exactly like "%s" with the
106684 ** addition that after the string has been read and copied into
106685 ** the result, [sqlite3_free()] is called on the input string. {END}
106686 */
106687 char *sqlite3_mprintf(const char*,...);
106688 char *sqlite3_vmprintf(const char*, va_list);
106689 char *sqlite3_snprintf(int,char*,const char*, ...);
106690
106691 /*
106692 ** CAPI3REF: Memory Allocation Subsystem {F17300}
106693 **
106694 ** {F17301} The SQLite core  uses these three routines for all of its own
106695 ** internal memory allocation needs. {END}  "Core" in the previous sentence
106696 ** does not include operating-system specific VFS implementation.  The
106697 ** windows VFS uses native malloc and free for some operations.
106698 **
106699 ** {F17302} The sqlite3_malloc() routine returns a pointer to a block
106700 ** of memory at least N bytes in length, where N is the parameter.
106701 ** {F17303} If sqlite3_malloc() is unable to obtain sufficient free
106702 ** memory, it returns a NULL pointer.  {F17304} If the parameter N to
106703 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
106704 ** a NULL pointer.
106705 **
106706 ** {F17305} Calling sqlite3_free() with a pointer previously returned
106707 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
106708 ** that it might be reused.  {F17306} The sqlite3_free() routine is
106709 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
106710 ** to sqlite3_free() is harmless.  {U17307} After being freed, memory
106711 ** should neither be read nor written.  Even reading previously freed
106712 ** memory might result in a segmentation fault or other severe error.
106713 ** {U17309} Memory corruption, a segmentation fault, or other severe error
106714 ** might result if sqlite3_free() is called with a non-NULL pointer that
106715 ** was not obtained from sqlite3_malloc() or sqlite3_free().
106716 **
106717 ** {F17310} The sqlite3_realloc() interface attempts to resize a
106718 ** prior memory allocation to be at least N bytes, where N is the
106719 ** second parameter.  The memory allocation to be resized is the first
106720 ** parameter.  {F17311} If the first parameter to sqlite3_realloc()
106721 ** is a NULL pointer then its behavior is identical to calling
106722 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
106723 ** {F17312} If the second parameter to sqlite3_realloc() is zero or
106724 ** negative then the behavior is exactly the same as calling
106725 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
106726 ** {F17313} Sqlite3_realloc() returns a pointer to a memory allocation
106727 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
106728 ** {F17314} If M is the size of the prior allocation, then min(N,M) bytes
106729 ** of the prior allocation are copied into the beginning of buffer returned
106730 ** by sqlite3_realloc() and the prior allocation is freed.
106731 ** {F17315} If sqlite3_realloc() returns NULL, then the prior allocation
106732 ** is not freed.
106733 **
106734 ** {F17316} The memory returned by sqlite3_malloc() and sqlite3_realloc()
106735 ** is always aligned to at least an 8 byte boundary. {END}
106736 **
106737 ** {F17381} The default implementation
106738 ** of the memory allocation subsystem uses the malloc(), realloc()
106739 ** and free() provided by the standard C library. {F17382} However, if 
106740 ** SQLite is compiled with the following C preprocessor macro
106741 **
106742 ** <blockquote> SQLITE_MEMORY_SIZE=<i>NNN</i> </blockquote>
106743 **
106744 ** where <i>NNN</i> is an integer, then SQLite create a static
106745 ** array of at least <i>NNN</i> bytes in size and use that array
106746 ** for all of its dynamic memory allocation needs. {END}  Additional
106747 ** memory allocator options may be added in future releases.
106748 **
106749 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
106750 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
106751 ** implementation of these routines to be omitted.  That capability
106752 ** is no longer provided.  Only built-in memory allocators can be
106753 ** used.
106754 **
106755 ** The windows OS interface layer calls
106756 ** the system malloc() and free() directly when converting
106757 ** filenames between the UTF-8 encoding used by SQLite
106758 ** and whatever filename encoding is used by the particular windows
106759 ** installation.  Memory allocation errors are detected, but
106760 ** they are reported back as [SQLITE_CANTOPEN] or
106761 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
106762 */
106763 void *sqlite3_malloc(int);
106764 void *sqlite3_realloc(void*, int);
106765 void sqlite3_free(void*);
106766
106767 /*
106768 ** CAPI3REF: Memory Allocator Statistics {F17370}
106769 **
106770 ** In addition to the basic three allocation routines 
106771 ** [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()],
106772 ** the memory allocation subsystem included with the SQLite
106773 ** sources provides the interfaces shown here.
106774 **
106775 ** {F17371} The sqlite3_memory_used() routine returns the
106776 ** number of bytes of memory currently outstanding (malloced but not freed).
106777 ** {F17372} The value returned by sqlite3_memory_used() includes
106778 ** any overhead added by SQLite, but not overhead added by the
106779 ** library malloc() that backs the sqlite3_malloc() implementation.
106780 ** {F17373} The sqlite3_memory_highwater() routines returns the
106781 ** maximum number of bytes that have been outstanding at any time
106782 ** since the highwater mark was last reset.
106783 ** {F17374} The byte count returned by sqlite3_memory_highwater()
106784 ** uses the same byte counting rules as sqlite3_memory_used(). {END}
106785 ** In other words, overhead added internally by SQLite is counted,
106786 ** but overhead from the underlying system malloc is not.
106787 ** {F17375} If the parameter to sqlite3_memory_highwater() is true,
106788 ** then the highwater mark is reset to the current value of
106789 ** sqlite3_memory_used() and the prior highwater mark (before the
106790 ** reset) is returned.  {F17376}  If the parameter to 
106791 ** sqlite3_memory_highwater() is zero, then the highwater mark is
106792 ** unchanged.
106793 */
106794 sqlite3_int64 sqlite3_memory_used(void);
106795 sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
106796
106797 /*
106798 ** CAPI3REF: Compile-Time Authorization Callbacks {F12500}
106799 **
106800 ** {F12501} This routine registers a authorizer callback with a particular
106801 ** database connection, supplied in the first argument. {F12502}
106802 ** The authorizer callback is invoked as SQL statements are being compiled
106803 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
106804 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  {F12503} At various
106805 ** points during the compilation process, as logic is being created
106806 ** to perform various actions, the authorizer callback is invoked to
106807 ** see if those actions are allowed.  The authorizer callback should
106808 ** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the
106809 ** specific action but allow the SQL statement to continue to be
106810 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
106811 ** rejected with an error.  {F12504} If the authorizer callback returns
106812 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
106813 ** then [sqlite3_prepare_v2()] or equivalent call that triggered
106814 ** the authorizer shall
106815 ** fail with an SQLITE_ERROR error code and an appropriate error message. {END}
106816 **
106817 ** When the callback returns [SQLITE_OK], that means the operation
106818 ** requested is ok.  {F12505} When the callback returns [SQLITE_DENY], the
106819 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
106820 ** authorizer shall fail
106821 ** with an SQLITE_ERROR error code and an error message explaining that
106822 ** access is denied. {F12506} If the authorizer code (the 2nd parameter
106823 ** to the authorizer callback is anything other than [SQLITE_READ], then
106824 ** a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. 
106825 ** If the authorizer code is [SQLITE_READ] and the callback returns
106826 ** [SQLITE_IGNORE] then the prepared statement is constructed to
106827 ** insert a NULL value in place of the table column that would have
106828 ** been read if [SQLITE_OK] had been returned. {END}
106829 **
106830 ** {F12510} The first parameter to the authorizer callback is a copy of
106831 ** the third parameter to the sqlite3_set_authorizer() interface.
106832 ** {F12511} The second parameter to the callback is an integer 
106833 ** [SQLITE_COPY | action code] that specifies the particular action
106834 ** to be authorized. {END} The available action codes are
106835 ** [SQLITE_COPY | documented separately].  {F12512} The third through sixth
106836 ** parameters to the callback are zero-terminated strings that contain 
106837 ** additional details about the action to be authorized. {END}
106838 **
106839 ** An authorizer is used when preparing SQL statements from an untrusted
106840 ** source, to ensure that the SQL statements do not try to access data
106841 ** that they are not allowed to see, or that they do not try to
106842 ** execute malicious statements that damage the database.  For
106843 ** example, an application may allow a user to enter arbitrary
106844 ** SQL queries for evaluation by a database.  But the application does
106845 ** not want the user to be able to make arbitrary changes to the
106846 ** database.  An authorizer could then be put in place while the
106847 ** user-entered SQL is being prepared that disallows everything
106848 ** except SELECT statements.  
106849 **
106850 ** {F12520} Only a single authorizer can be in place on a database connection
106851 ** at a time.  Each call to sqlite3_set_authorizer overrides the
106852 ** previous call. {F12521}  A NULL authorizer means that no authorization
106853 ** callback is invoked.  {F12522} The default authorizer is NULL. {END}
106854 **
106855 ** Note that the authorizer callback is invoked only during 
106856 ** [sqlite3_prepare()] or its variants.  {F12523} Authorization is not
106857 ** performed during statement evaluation in [sqlite3_step()]. {END}
106858 */
106859 int sqlite3_set_authorizer(
106860   sqlite3*,
106861   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
106862   void *pUserData
106863 );
106864
106865 /*
106866 ** CAPI3REF: Authorizer Return Codes {F12590}
106867 **
106868 ** The [sqlite3_set_authorizer | authorizer callback function] must
106869 ** return either [SQLITE_OK] or one of these two constants in order
106870 ** to signal SQLite whether or not the action is permitted.  See the
106871 ** [sqlite3_set_authorizer | authorizer documentation] for additional
106872 ** information.
106873 */
106874 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
106875 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
106876
106877 /*
106878 ** CAPI3REF: Authorizer Action Codes {F12550}
106879 **
106880 ** The [sqlite3_set_authorizer()] interface registers a callback function
106881 ** that is invoked to authorizer certain SQL statement actions.  {F12551} The
106882 ** second parameter to the callback is an integer code that specifies
106883 ** what action is being authorized.  These are the integer action codes that
106884 ** the authorizer callback may be passed. {END}
106885 **
106886 ** These action code values signify what kind of operation is to be 
106887 ** authorized.  {F12552} The 3rd and 4th parameters to the authorization
106888 ** callback function will be parameters or NULL depending on which of these
106889 ** codes is used as the second parameter. {F12553} The 5th parameter to the
106890 ** authorizer callback is the name of the database ("main", "temp", 
106891 ** etc.) if applicable. {F12554} The 6th parameter to the authorizer callback
106892 ** is the name of the inner-most trigger or view that is responsible for
106893 ** the access attempt or NULL if this access attempt is directly from 
106894 ** top-level SQL code.
106895 */
106896 /******************************************* 3rd ************ 4th ***********/
106897 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
106898 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
106899 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
106900 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
106901 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
106902 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
106903 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
106904 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
106905 #define SQLITE_DELETE                9   /* Table Name      NULL            */
106906 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
106907 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
106908 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
106909 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
106910 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
106911 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
106912 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
106913 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
106914 #define SQLITE_INSERT               18   /* Table Name      NULL            */
106915 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
106916 #define SQLITE_READ                 20   /* Table Name      Column Name     */
106917 #define SQLITE_SELECT               21   /* NULL            NULL            */
106918 #define SQLITE_TRANSACTION          22   /* NULL            NULL            */
106919 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
106920 #define SQLITE_ATTACH               24   /* Filename        NULL            */
106921 #define SQLITE_DETACH               25   /* Database Name   NULL            */
106922 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
106923 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
106924 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
106925 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
106926 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
106927 #define SQLITE_FUNCTION             31   /* Function Name   NULL            */
106928 #define SQLITE_COPY                  0   /* No longer used */
106929
106930 /*
106931 ** CAPI3REF: Tracing And Profiling Functions {F12280}
106932 **
106933 ** These routines register callback functions that can be used for
106934 ** tracing and profiling the execution of SQL statements.
106935 **
106936 ** {F12281} The callback function registered by sqlite3_trace() is invoked
106937 ** at the first [sqlite3_step()] for the evaluation of an SQL statement.
106938 ** {F12282} Only a single trace callback can be registered at a time.
106939 ** Each call to sqlite3_trace() overrides the previous.  {F12283} A
106940 ** NULL callback for sqlite3_trace() disables tracing.  {F12284} The
106941 ** first argument to the trace callback is a copy of the pointer which
106942 ** was the 3rd argument to sqlite3_trace.  {F12285} The second argument
106943 ** to the trace callback is a zero-terminated UTF8 string containing
106944 ** the original text of the SQL statement as it was passed into
106945 ** [sqlite3_prepare_v2()] or the equivalent. {END}  Note that the
106946 ** host parameter are not expanded in the SQL statement text.
106947 **
106948 ** {F12287} The callback function registered by sqlite3_profile() is invoked
106949 ** as each SQL statement finishes.  {F12288} The first parameter to the
106950 ** profile callback is a copy of the 3rd parameter to sqlite3_profile().
106951 ** {F12289} The second parameter to the profile callback is a
106952 ** zero-terminated UTF-8 string that contains the complete text of
106953 ** the SQL statement as it was processed by [sqlite3_prepare_v2()] or
106954 ** the equivalent.  {F12290} The third parameter to the profile 
106955 ** callback is an estimate of the number of nanoseconds of
106956 ** wall-clock time required to run the SQL statement from start
106957 ** to finish. {END}  
106958 **
106959 ** The sqlite3_profile() API is currently considered experimental and
106960 ** is subject to change.
106961 */
106962 void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
106963 void *sqlite3_profile(sqlite3*,
106964    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
106965
106966 /*
106967 ** CAPI3REF: Query Progress Callbacks {F12910}
106968 **
106969 ** {F12911} This routine configures a callback function - the
106970 ** progress callback - that is invoked periodically during long
106971 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
106972 ** [sqlite3_get_table()]. {END}  An example use for this 
106973 ** interface is to keep a GUI updated during a large query.
106974 **
106975 ** {F12912} The progress callback is invoked once for every N virtual
106976 ** machine opcodes, where N is the second argument to this function.
106977 ** {F12913} The progress callback itself is identified by the third
106978 ** argument to this function. {F12914} The fourth argument to this
106979 ** function is a void pointer passed to the progress callback
106980 ** function each time it is invoked. {END}
106981 **
106982 ** {F12915} If a call to [sqlite3_exec()], [sqlite3_step()], or
106983 ** [sqlite3_get_table()] results in fewer than N opcodes being executed,
106984 ** then the progress callback is never invoked. {END}
106985 ** 
106986 ** {F12916} Only a single progress callback function may be registered for each
106987 ** open database connection.  Every call to sqlite3_progress_handler()
106988 ** overwrites the results of the previous call. {F12917}
106989 ** To remove the progress callback altogether, pass NULL as the third
106990 ** argument to this function. {END}
106991 **
106992 ** {F12918} If the progress callback returns a result other than 0, then
106993 ** the current query is immediately terminated and any database changes
106994 ** rolled back. {F12919}
106995 ** The containing [sqlite3_exec()], [sqlite3_step()], or
106996 ** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. {END}  This feature
106997 ** can be used, for example, to implement the "Cancel" button on a
106998 ** progress dialog box in a GUI.
106999 */
107000 void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
107001
107002 /*
107003 ** CAPI3REF: Opening A New Database Connection {F12700}
107004 **
107005 ** {F12701} These routines open an SQLite database file whose name
107006 ** is given by the filename argument.
107007 ** {F12702} The filename argument is interpreted as UTF-8
107008 ** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16
107009 ** in the native byte order for [sqlite3_open16()].
107010 ** {F12703} An [sqlite3*] handle is returned in *ppDb, even
107011 ** if an error occurs.  {F12723} (Exception: if SQLite is unable
107012 ** to allocate memory to hold the [sqlite3] object, a NULL will
107013 ** be written into *ppDb instead of a pointer to the [sqlite3] object.)
107014 ** {F12704} If the database is opened (and/or created)
107015 ** successfully, then [SQLITE_OK] is returned.  {F12705} Otherwise an
107016 ** error code is returned.  {F12706} The
107017 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()]  routines can be used to obtain
107018 ** an English language description of the error.
107019 **
107020 ** {F12707} The default encoding for the database will be UTF-8 if
107021 ** [sqlite3_open()] or [sqlite3_open_v2()] is called and
107022 ** UTF-16 in the native byte order if [sqlite3_open16()] is used.
107023 **
107024 ** {F12708} Whether or not an error occurs when it is opened, resources
107025 ** associated with the [sqlite3*] handle should be released by passing it
107026 ** to [sqlite3_close()] when it is no longer required.
107027 **
107028 ** {F12709} The [sqlite3_open_v2()] interface works like [sqlite3_open()] 
107029 ** except that it acccepts two additional parameters for additional control
107030 ** over the new database connection.  {F12710} The flags parameter can be
107031 ** one of:
107032 **
107033 ** <ol>
107034 ** <li>  [SQLITE_OPEN_READONLY]
107035 ** <li>  [SQLITE_OPEN_READWRITE]
107036 ** <li>  [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
107037 ** </ol>
107038 **
107039 ** {F12711} The first value opens the database read-only. 
107040 ** {F12712} If the database does not previously exist, an error is returned.
107041 ** {F12713} The second option opens
107042 ** the database for reading and writing if possible, or reading only if
107043 ** if the file is write protected.  {F12714} In either case the database
107044 ** must already exist or an error is returned.  {F12715} The third option
107045 ** opens the database for reading and writing and creates it if it does
107046 ** not already exist. {F12716}
107047 ** The third options is behavior that is always used for [sqlite3_open()]
107048 ** and [sqlite3_open16()].
107049 **
107050 ** {F12717} If the filename is ":memory:", then an private
107051 ** in-memory database is created for the connection. {F12718} This in-memory
107052 ** database will vanish when the database connection is closed. {END}  Future
107053 ** version of SQLite might make use of additional special filenames
107054 ** that begin with the ":" character.  It is recommended that 
107055 ** when a database filename really does begin with
107056 ** ":" that you prefix the filename with a pathname like "./" to
107057 ** avoid ambiguity.
107058 **
107059 ** {F12719} If the filename is an empty string, then a private temporary
107060 ** on-disk database will be created.  {F12720} This private database will be
107061 ** automatically deleted as soon as the database connection is closed.
107062 **
107063 ** {F12721} The fourth parameter to sqlite3_open_v2() is the name of the
107064 ** [sqlite3_vfs] object that defines the operating system 
107065 ** interface that the new database connection should use.  {F12722} If the
107066 ** fourth parameter is a NULL pointer then the default [sqlite3_vfs]
107067 ** object is used. {END}
107068 **
107069 ** <b>Note to windows users:</b>  The encoding used for the filename argument
107070 ** of [sqlite3_open()] and [sqlite3_open_v2()] must be UTF-8, not whatever
107071 ** codepage is currently defined.  Filenames containing international
107072 ** characters must be converted to UTF-8 prior to passing them into
107073 ** [sqlite3_open()] or [sqlite3_open_v2()].
107074 */
107075 int sqlite3_open(
107076   const char *filename,   /* Database filename (UTF-8) */
107077   sqlite3 **ppDb          /* OUT: SQLite db handle */
107078 );
107079 int sqlite3_open16(
107080   const void *filename,   /* Database filename (UTF-16) */
107081   sqlite3 **ppDb          /* OUT: SQLite db handle */
107082 );
107083 int sqlite3_open_v2(
107084   const char *filename,   /* Database filename (UTF-8) */
107085   sqlite3 **ppDb,         /* OUT: SQLite db handle */
107086   int flags,              /* Flags */
107087   const char *zVfs        /* Name of VFS module to use */
107088 );
107089
107090 /*
107091 ** CAPI3REF: Error Codes And Messages {F12800}
107092 **
107093 ** {F12801} The sqlite3_errcode() interface returns the numeric
107094 ** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code]
107095 ** for the most recent failed sqlite3_* API call associated
107096 ** with [sqlite3] handle 'db'. {U12802} If a prior API call failed but the
107097 ** most recent API call succeeded, the return value from sqlite3_errcode()
107098 ** is undefined. {END}
107099 **
107100 ** {F12803} The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
107101 ** text that describes the error, as either UTF8 or UTF16 respectively.
107102 ** {F12804} Memory to hold the error message string is managed internally.
107103 ** {U12805} The 
107104 ** string may be overwritten or deallocated by subsequent calls to SQLite
107105 ** interface functions. {END}
107106 **
107107 ** {F12806} Calls to many sqlite3_* functions set the error code and
107108 ** string returned by [sqlite3_errcode()], [sqlite3_errmsg()], and
107109 ** [sqlite3_errmsg16()] overwriting the previous values.  {F12807}
107110 ** Except, calls to [sqlite3_errcode()],
107111 ** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the
107112 ** results of future invocations.  {F12808} Calls to API routines that
107113 ** do not return an error code (example: [sqlite3_data_count()]) do not
107114 ** change the error code returned by this routine.  {F12809} Interfaces that
107115 ** are not associated with a specific database connection (examples:
107116 ** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change
107117 ** the return code. {END}
107118 **
107119 ** {F12810} Assuming no other intervening sqlite3_* API calls are made,
107120 ** the error code returned by this function is associated with the same
107121 ** error as the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()].
107122 */
107123 int sqlite3_errcode(sqlite3 *db);
107124 const char *sqlite3_errmsg(sqlite3*);
107125 const void *sqlite3_errmsg16(sqlite3*);
107126
107127 /*
107128 ** CAPI3REF: SQL Statement Object {F13000}
107129 **
107130 ** An instance of this object represent single SQL statements.  This
107131 ** object is variously known as a "prepared statement" or a 
107132 ** "compiled SQL statement" or simply as a "statement".
107133 ** 
107134 ** The life of a statement object goes something like this:
107135 **
107136 ** <ol>
107137 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
107138 **      function.
107139 ** <li> Bind values to host parameters using
107140 **      [sqlite3_bind_blob | sqlite3_bind_* interfaces].
107141 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
107142 ** <li> Reset the statement using [sqlite3_reset()] then go back
107143 **      to step 2.  Do this zero or more times.
107144 ** <li> Destroy the object using [sqlite3_finalize()].
107145 ** </ol>
107146 **
107147 ** Refer to documentation on individual methods above for additional
107148 ** information.
107149 */
107150 typedef struct sqlite3_stmt sqlite3_stmt;
107151
107152 /*
107153 ** CAPI3REF: Compiling An SQL Statement {F13010}
107154 **
107155 ** To execute an SQL query, it must first be compiled into a byte-code
107156 ** program using one of these routines. 
107157 **
107158 ** {F13011} The first argument "db" is an [sqlite3 | SQLite database handle] 
107159 ** obtained from a prior call to [sqlite3_open()], [sqlite3_open_v2()]
107160 ** or [sqlite3_open16()]. {F13012}
107161 ** The second argument "zSql" is the statement to be compiled, encoded
107162 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
107163 ** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2()
107164 ** use UTF-16. {END}
107165 **
107166 ** {F13013} If the nByte argument is less
107167 ** than zero, then zSql is read up to the first zero terminator.
107168 ** {F13014} If nByte is non-negative, then it is the maximum number of 
107169 ** bytes read from zSql.  When nByte is non-negative, the
107170 ** zSql string ends at either the first '\000' or '\u0000' character or 
107171 ** until the nByte-th byte, whichever comes first. {END}
107172 **
107173 ** {F13015} *pzTail is made to point to the first byte past the end of the
107174 ** first SQL statement in zSql.  These routines only compiles the first
107175 ** statement in zSql, so *pzTail is left pointing to what remains
107176 ** uncompiled. {END}
107177 **
107178 ** {F13016} *ppStmt is left pointing to a compiled 
107179 ** [sqlite3_stmt | SQL statement structure] that can be
107180 ** executed using [sqlite3_step()].  Or if there is an error, *ppStmt may be
107181 ** set to NULL.  {F13017} If the input text contains no SQL (if the input
107182 ** is and empty string or a comment) then *ppStmt is set to NULL.
107183 ** {U13018} The calling procedure is responsible for deleting the
107184 ** compiled SQL statement
107185 ** using [sqlite3_finalize()] after it has finished with it.
107186 **
107187 ** {F13019} On success, [SQLITE_OK] is returned.  Otherwise an 
107188 ** [SQLITE_ERROR | error code] is returned. {END}
107189 **
107190 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
107191 ** recommended for all new programs. The two older interfaces are retained
107192 ** for backwards compatibility, but their use is discouraged.
107193 ** {F13020} In the "v2" interfaces, the prepared statement
107194 ** that is returned (the [sqlite3_stmt] object) contains a copy of the 
107195 ** original SQL text. {END} This causes the [sqlite3_step()] interface to
107196 ** behave a differently in two ways:
107197 **
107198 ** <ol>
107199 ** <li>{F13022}
107200 ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
107201 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
107202 ** statement and try to run it again. {F12023} If the schema has changed in
107203 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
107204 ** return [SQLITE_SCHEMA].  {END} But unlike the legacy behavior, 
107205 ** [SQLITE_SCHEMA] is now a fatal error.  {F12024} Calling
107206 ** [sqlite3_prepare_v2()] again will not make the
107207 ** error go away.  {F12025} Note: use [sqlite3_errmsg()] to find the text
107208 ** of the parsing error that results in an [SQLITE_SCHEMA] return. {END}
107209 ** </li>
107210 **
107211 ** <li>
107212 ** {F13030} When an error occurs, 
107213 ** [sqlite3_step()] will return one of the detailed 
107214 ** [SQLITE_ERROR | result codes] or
107215 ** [SQLITE_IOERR_READ | extended result codes].  {F13031}
107216 ** The legacy behavior was that [sqlite3_step()] would only return a generic
107217 ** [SQLITE_ERROR] result code and you would have to make a second call to
107218 ** [sqlite3_reset()] in order to find the underlying cause of the problem.
107219 ** {F13032}
107220 ** With the "v2" prepare interfaces, the underlying reason for the error is
107221 ** returned immediately. {END}
107222 ** </li>
107223 ** </ol>
107224 */
107225 int sqlite3_prepare(
107226   sqlite3 *db,            /* Database handle */
107227   const char *zSql,       /* SQL statement, UTF-8 encoded */
107228   int nByte,              /* Maximum length of zSql in bytes. */
107229   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
107230   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
107231 );
107232 int sqlite3_prepare_v2(
107233   sqlite3 *db,            /* Database handle */
107234   const char *zSql,       /* SQL statement, UTF-8 encoded */
107235   int nByte,              /* Maximum length of zSql in bytes. */
107236   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
107237   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
107238 );
107239 int sqlite3_prepare16(
107240   sqlite3 *db,            /* Database handle */
107241   const void *zSql,       /* SQL statement, UTF-16 encoded */
107242   int nByte,              /* Maximum length of zSql in bytes. */
107243   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
107244   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
107245 );
107246 int sqlite3_prepare16_v2(
107247   sqlite3 *db,            /* Database handle */
107248   const void *zSql,       /* SQL statement, UTF-16 encoded */
107249   int nByte,              /* Maximum length of zSql in bytes. */
107250   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
107251   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
107252 );
107253
107254 /*
107255 ** CAPIREF: Retrieving Statement SQL {F13100}
107256 **
107257 ** {F13101} If the compiled SQL statement passed as an argument was
107258 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()],
107259 ** then this function returns a pointer to a zero-terminated string
107260 ** containing a copy of the original SQL statement. {F13102} The
107261 ** pointer is valid until the statement
107262 ** is deleted using sqlite3_finalize().
107263 ** {F13103} The string returned by sqlite3_sql() is always UTF8 even
107264 ** if a UTF16 string was originally entered using [sqlite3_prepare16_v2()]
107265 ** or the equivalent.
107266 **
107267 ** {F13104} If the statement was compiled using either of the legacy
107268 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this
107269 ** function returns NULL.
107270 */
107271 const char *sqlite3_sql(sqlite3_stmt *pStmt);
107272
107273 /*
107274 ** CAPI3REF:  Dynamically Typed Value Object  {F15000}
107275 **
107276 ** {F15001} SQLite uses the sqlite3_value object to represent all values
107277 ** that are or can be stored in a database table. {END}
107278 ** SQLite uses dynamic typing for the values it stores.  
107279 ** {F15002} Values stored in sqlite3_value objects can be
107280 ** be integers, floating point values, strings, BLOBs, or NULL.
107281 */
107282 typedef struct Mem sqlite3_value;
107283
107284 /*
107285 ** CAPI3REF:  SQL Function Context Object {F16001}
107286 **
107287 ** The context in which an SQL function executes is stored in an
107288 ** sqlite3_context object.  {F16002} A pointer to an sqlite3_context
107289 ** object is always first parameter to application-defined SQL functions.
107290 */
107291 typedef struct sqlite3_context sqlite3_context;
107292
107293 /*
107294 ** CAPI3REF:  Binding Values To Prepared Statements {F13500}
107295 **
107296 ** {F13501} In the SQL strings input to [sqlite3_prepare_v2()] and its
107297 ** variants, literals may be replace by a parameter in one
107298 ** of these forms:
107299 **
107300 ** <ul>
107301 ** <li>  ?
107302 ** <li>  ?NNN
107303 ** <li>  :AAA
107304 ** <li>  @AAA
107305 ** <li>  $VVV
107306 ** </ul>
107307 **
107308 ** In the parameter forms shown above NNN is an integer literal,
107309 ** AAA is an alphanumeric identifier and VVV is a variable name according
107310 ** to the syntax rules of the TCL programming language. {END}
107311 ** The values of these parameters (also called "host parameter names")
107312 ** can be set using the sqlite3_bind_*() routines defined here.
107313 **
107314 ** {F13502} The first argument to the sqlite3_bind_*() routines always
107315 ** is a pointer to the [sqlite3_stmt] object returned from
107316 ** [sqlite3_prepare_v2()] or its variants.  {F13503} The second
107317 ** argument is the index of the parameter to be set.  {F13504} The
107318 ** first parameter has an index of 1.  {F13505} When the same named
107319 ** parameter is used more than once, second and subsequent
107320 ** occurrences have the same index as the first occurrence. 
107321 ** {F13506} The index for named parameters can be looked up using the
107322 ** [sqlite3_bind_parameter_name()] API if desired.  {F13507} The index
107323 ** for "?NNN" parameters is the value of NNN.
107324 ** {F13508} The NNN value must be between 1 and the compile-time
107325 ** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). {END}
107326 ** See <a href="limits.html">limits.html</a> for additional information.
107327 **
107328 ** {F13509} The third argument is the value to bind to the parameter. {END}
107329 **
107330 ** {F13510} In those
107331 ** routines that have a fourth argument, its value is the number of bytes
107332 ** in the parameter.  To be clear: the value is the number of bytes in the
107333 ** string, not the number of characters. {F13511}  The number
107334 ** of bytes does not include the zero-terminator at the end of strings.
107335 ** {F13512}
107336 ** If the fourth parameter is negative, the length of the string is
107337 ** number of bytes up to the first zero terminator. {END}
107338 **
107339 ** {F13513}
107340 ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
107341 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
107342 ** text after SQLite has finished with it. {F13514} If the fifth argument is
107343 ** the special value [SQLITE_STATIC], then the library assumes that the
107344 ** information is in static, unmanaged space and does not need to be freed.
107345 ** {F13515} If the fifth argument has the value [SQLITE_TRANSIENT], then
107346 ** SQLite makes its own private copy of the data immediately, before
107347 ** the sqlite3_bind_*() routine returns. {END}
107348 **
107349 ** {F13520} The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
107350 ** is filled with zeros.  {F13521} A zeroblob uses a fixed amount of memory
107351 ** (just an integer to hold it size) while it is being processed. {END}
107352 ** Zeroblobs are intended to serve as place-holders for BLOBs whose
107353 ** content is later written using 
107354 ** [sqlite3_blob_open | increment BLOB I/O] routines. {F13522} A negative
107355 ** value for the zeroblob results in a zero-length BLOB. {END}
107356 **
107357 ** {F13530} The sqlite3_bind_*() routines must be called after
107358 ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and
107359 ** before [sqlite3_step()]. {F13531}
107360 ** Bindings are not cleared by the [sqlite3_reset()] routine.
107361 ** {F13532} Unbound parameters are interpreted as NULL. {END}
107362 **
107363 ** {F13540} These routines return [SQLITE_OK] on success or an error code if
107364 ** anything goes wrong.  {F13541} [SQLITE_RANGE] is returned if the parameter
107365 ** index is out of range.  {F13542} [SQLITE_NOMEM] is returned if malloc fails.
107366 ** {F13543} [SQLITE_MISUSE] is returned if these routines are called on a
107367 ** virtual machine that is the wrong state or which has already been finalized.
107368 */
107369 int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
107370 int sqlite3_bind_double(sqlite3_stmt*, int, double);
107371 int sqlite3_bind_int(sqlite3_stmt*, int, int);
107372 int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
107373 int sqlite3_bind_null(sqlite3_stmt*, int);
107374 int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
107375 int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
107376 int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
107377 int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
107378
107379 /*
107380 ** CAPI3REF: Number Of Host Parameters {F13600}
107381 **
107382 ** {F13601} Return the largest host parameter index in the precompiled
107383 ** statement given as the argument. {F13602} When the host parameters
107384 ** are of the forms like ":AAA", "$VVV", "@AAA", or "?",
107385 ** then they are assigned sequential increasing numbers beginning
107386 ** with one, so the value returned is the number of parameters.
107387 ** {F13603} However
107388 ** if the same host parameter name is used multiple times, each occurrance
107389 ** is given the same number, so the value returned in that case is the number
107390 ** of unique host parameter names. {F13604} If host parameters of the
107391 ** form "?NNN" are used (where NNN is an integer) then there might be
107392 ** gaps in the numbering and the value returned by this interface is
107393 ** the index of the host parameter with the largest index value. {END}
107394 **
107395 ** {U13605} The prepared statement must not be [sqlite3_finalize | finalized]
107396 ** prior to this routine returning.  Otherwise the results are undefined
107397 ** and probably undesirable.
107398 */
107399 int sqlite3_bind_parameter_count(sqlite3_stmt*);
107400
107401 /*
107402 ** CAPI3REF: Name Of A Host Parameter {F13620}
107403 **
107404 ** {F13621} This routine returns a pointer to the name of the n-th
107405 ** parameter in a [sqlite3_stmt | prepared statement]. {F13622}
107406 ** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name
107407 ** which is the string ":AAA" or "@AAA" or "$VVV". 
107408 ** In other words, the initial ":" or "$" or "@"
107409 ** is included as part of the name.  {F13626}
107410 ** Parameters of the form "?" or "?NNN" have no name.
107411 **
107412 ** {F13623} The first host parameter has an index of 1, not 0.
107413 **
107414 ** {F13624} If the value n is out of range or if the n-th parameter is
107415 ** nameless, then NULL is returned.  {F13625} The returned string is
107416 ** always in the UTF-8 encoding even if the named parameter was
107417 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
107418 ** [sqlite3_prepare16_v2()].
107419 */
107420 const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
107421
107422 /*
107423 ** CAPI3REF: Index Of A Parameter With A Given Name {F13640}
107424 **
107425 ** {F13641} This routine returns the index of a host parameter with the
107426 ** given name.  {F13642} The name must match exactly.  {F13643}
107427 ** If no parameter with the given name is found, return 0.
107428 ** {F13644} Parameter names must be UTF8.
107429 */
107430 int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
107431
107432 /*
107433 ** CAPI3REF: Reset All Bindings On A Prepared Statement {F13660}
107434 **
107435 ** {F13661} Contrary to the intuition of many, [sqlite3_reset()] does not
107436 ** reset the [sqlite3_bind_blob | bindings] on a 
107437 ** [sqlite3_stmt | prepared statement]. {F13662} Use this routine to
107438 ** reset all host parameters to NULL.
107439 */
107440 int sqlite3_clear_bindings(sqlite3_stmt*);
107441
107442 /*
107443 ** CAPI3REF: Number Of Columns In A Result Set {F13710}
107444 **
107445 ** {F13711} Return the number of columns in the result set returned by the 
107446 ** [sqlite3_stmt | compiled SQL statement]. {F13712} This routine returns 0
107447 ** if pStmt is an SQL statement that does not return data (for 
107448 ** example an UPDATE).
107449 */
107450 int sqlite3_column_count(sqlite3_stmt *pStmt);
107451
107452 /*
107453 ** CAPI3REF: Column Names In A Result Set {F13720}
107454 **
107455 ** {F13721} These routines return the name assigned to a particular column
107456 ** in the result set of a SELECT statement.  {F13722} The sqlite3_column_name()
107457 ** interface returns a pointer to a zero-terminated UTF8 string
107458 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
107459 ** UTF16 string. {F13723}  The first parameter is the
107460 ** [sqlite3_stmt | prepared statement] that implements the SELECT statement.
107461 ** The second parameter is the column number.  The left-most column is
107462 ** number 0.
107463 **
107464 ** {F13724} The returned string pointer is valid until either the 
107465 ** [sqlite3_stmt | prepared statement] is destroyed by [sqlite3_finalize()]
107466 ** or until the next call sqlite3_column_name() or sqlite3_column_name16()
107467 ** on the same column.
107468 **
107469 ** {F13725} If sqlite3_malloc() fails during the processing of either routine
107470 ** (for example during a conversion from UTF-8 to UTF-16) then a
107471 ** NULL pointer is returned.
107472 */
107473 const char *sqlite3_column_name(sqlite3_stmt*, int N);
107474 const void *sqlite3_column_name16(sqlite3_stmt*, int N);
107475
107476 /*
107477 ** CAPI3REF: Source Of Data In A Query Result {F13740}
107478 **
107479 ** {F13741} These routines provide a means to determine what column of what
107480 ** table in which database a result of a SELECT statement comes from.
107481 ** {F13742} The name of the database or table or column can be returned as
107482 ** either a UTF8 or UTF16 string.  {F13743} The _database_ routines return
107483 ** the database name, the _table_ routines return the table name, and
107484 ** the origin_ routines return the column name. {F13744}
107485 ** The returned string is valid until
107486 ** the [sqlite3_stmt | prepared statement] is destroyed using
107487 ** [sqlite3_finalize()] or until the same information is requested
107488 ** again in a different encoding.
107489 **
107490 ** {F13745} The names returned are the original un-aliased names of the
107491 ** database, table, and column.
107492 **
107493 ** {F13746} The first argument to the following calls is a 
107494 ** [sqlite3_stmt | compiled SQL statement].
107495 ** {F13747} These functions return information about the Nth column returned by 
107496 ** the statement, where N is the second function argument.
107497 **
107498 ** {F13748} If the Nth column returned by the statement is an expression
107499 ** or subquery and is not a column value, then all of these functions
107500 ** return NULL.  {F13749} Otherwise, they return the 
107501 ** name of the attached database, table and column that query result
107502 ** column was extracted from.
107503 **
107504 ** {F13750} As with all other SQLite APIs, those postfixed with "16" return
107505 ** UTF-16 encoded strings, the other functions return UTF-8. {END}
107506 **
107507 ** These APIs are only available if the library was compiled with the 
107508 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
107509 **
107510 ** {U13751}
107511 ** If two or more threads call one or more of these routines against the same
107512 ** prepared statement and column at the same time then the results are
107513 ** undefined.
107514 */
107515 const char *sqlite3_column_database_name(sqlite3_stmt*,int);
107516 const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
107517 const char *sqlite3_column_table_name(sqlite3_stmt*,int);
107518 const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
107519 const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
107520 const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
107521
107522 /*
107523 ** CAPI3REF: Declared Datatype Of A Query Result {F13760}
107524 **
107525 ** The first parameter is a [sqlite3_stmt | compiled SQL statement]. 
107526 ** {F13761} If this statement is a SELECT statement and the Nth column of the 
107527 ** returned result set of that SELECT is a table column (not an
107528 ** expression or subquery) then the declared type of the table
107529 ** column is returned.  {F13762} If the Nth column of the result set is an
107530 ** expression or subquery, then a NULL pointer is returned.
107531 ** {F13763} The returned string is always UTF-8 encoded.  {END} 
107532 ** For example, in the database schema:
107533 **
107534 ** CREATE TABLE t1(c1 VARIANT);
107535 **
107536 ** And the following statement compiled:
107537 **
107538 ** SELECT c1 + 1, c1 FROM t1;
107539 **
107540 ** Then this routine would return the string "VARIANT" for the second
107541 ** result column (i==1), and a NULL pointer for the first result column
107542 ** (i==0).
107543 **
107544 ** SQLite uses dynamic run-time typing.  So just because a column
107545 ** is declared to contain a particular type does not mean that the
107546 ** data stored in that column is of the declared type.  SQLite is
107547 ** strongly typed, but the typing is dynamic not static.  Type
107548 ** is associated with individual values, not with the containers
107549 ** used to hold those values.
107550 */
107551 const char *sqlite3_column_decltype(sqlite3_stmt *, int i);
107552 const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
107553
107554 /* 
107555 ** CAPI3REF:  Evaluate An SQL Statement {F13200}
107556 **
107557 ** After an [sqlite3_stmt | SQL statement] has been prepared with a call
107558 ** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of
107559 ** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()],
107560 ** then this function must be called one or more times to evaluate the 
107561 ** statement.
107562 **
107563 ** The details of the behavior of this sqlite3_step() interface depend
107564 ** on whether the statement was prepared using the newer "v2" interface
107565 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
107566 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
107567 ** new "v2" interface is recommended for new applications but the legacy
107568 ** interface will continue to be supported.
107569 **
107570 ** In the lagacy interface, the return value will be either [SQLITE_BUSY], 
107571 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
107572 ** With the "v2" interface, any of the other [SQLITE_OK | result code]
107573 ** or [SQLITE_IOERR_READ | extended result code] might be returned as
107574 ** well.
107575 **
107576 ** [SQLITE_BUSY] means that the database engine was unable to acquire the
107577 ** database locks it needs to do its job.  If the statement is a COMMIT
107578 ** or occurs outside of an explicit transaction, then you can retry the
107579 ** statement.  If the statement is not a COMMIT and occurs within a
107580 ** explicit transaction then you should rollback the transaction before
107581 ** continuing.
107582 **
107583 ** [SQLITE_DONE] means that the statement has finished executing
107584 ** successfully.  sqlite3_step() should not be called again on this virtual
107585 ** machine without first calling [sqlite3_reset()] to reset the virtual
107586 ** machine back to its initial state.
107587 **
107588 ** If the SQL statement being executed returns any data, then 
107589 ** [SQLITE_ROW] is returned each time a new row of data is ready
107590 ** for processing by the caller. The values may be accessed using
107591 ** the [sqlite3_column_int | column access functions].
107592 ** sqlite3_step() is called again to retrieve the next row of data.
107593 ** 
107594 ** [SQLITE_ERROR] means that a run-time error (such as a constraint
107595 ** violation) has occurred.  sqlite3_step() should not be called again on
107596 ** the VM. More information may be found by calling [sqlite3_errmsg()].
107597 ** With the legacy interface, a more specific error code (example:
107598 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
107599 ** can be obtained by calling [sqlite3_reset()] on the
107600 ** [sqlite3_stmt | prepared statement].  In the "v2" interface,
107601 ** the more specific error code is returned directly by sqlite3_step().
107602 **
107603 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
107604 ** Perhaps it was called on a [sqlite3_stmt | prepared statement] that has
107605 ** already been [sqlite3_finalize | finalized] or on one that had 
107606 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
107607 ** be the case that the same database connection is being used by two or
107608 ** more threads at the same moment in time.
107609 **
107610 ** <b>Goofy Interface Alert:</b>
107611 ** In the legacy interface, 
107612 ** the sqlite3_step() API always returns a generic error code,
107613 ** [SQLITE_ERROR], following any error other than [SQLITE_BUSY]
107614 ** and [SQLITE_MISUSE].  You must call [sqlite3_reset()] or
107615 ** [sqlite3_finalize()] in order to find one of the specific
107616 ** [SQLITE_ERROR | result codes] that better describes the error.
107617 ** We admit that this is a goofy design.  The problem has been fixed
107618 ** with the "v2" interface.  If you prepare all of your SQL statements
107619 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
107620 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the 
107621 ** more specific [SQLITE_ERROR | result codes] are returned directly
107622 ** by sqlite3_step().  The use of the "v2" interface is recommended.
107623 */
107624 int sqlite3_step(sqlite3_stmt*);
107625
107626 /*
107627 ** CAPI3REF: Number of columns in a result set {F13770}
107628 **
107629 ** Return the number of values in the current row of the result set.
107630 **
107631 ** {F13771} After a call to [sqlite3_step()] that returns [SQLITE_ROW],
107632 ** this routine
107633 ** will return the same value as the [sqlite3_column_count()] function.
107634 ** {F13772}
107635 ** After [sqlite3_step()] has returned an [SQLITE_DONE], [SQLITE_BUSY], or
107636 ** a [SQLITE_ERROR | error code], or before [sqlite3_step()] has been 
107637 ** called on the [sqlite3_stmt | prepared statement] for the first time,
107638 ** this routine returns zero.
107639 */
107640 int sqlite3_data_count(sqlite3_stmt *pStmt);
107641
107642 /*
107643 ** CAPI3REF: Fundamental Datatypes {F10265}
107644 **
107645 ** {F10266}Every value in SQLite has one of five fundamental datatypes:
107646 **
107647 ** <ul>
107648 ** <li> 64-bit signed integer
107649 ** <li> 64-bit IEEE floating point number
107650 ** <li> string
107651 ** <li> BLOB
107652 ** <li> NULL
107653 ** </ul> {END}
107654 **
107655 ** These constants are codes for each of those types.
107656 **
107657 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
107658 ** for a completely different meaning.  Software that links against both
107659 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not
107660 ** SQLITE_TEXT.
107661 */
107662 #define SQLITE_INTEGER  1
107663 #define SQLITE_FLOAT    2
107664 #define SQLITE_BLOB     4
107665 #define SQLITE_NULL     5
107666 #ifdef SQLITE_TEXT
107667 # undef SQLITE_TEXT
107668 #else
107669 # define SQLITE_TEXT     3
107670 #endif
107671 #define SQLITE3_TEXT     3
107672
107673 /*
107674 ** CAPI3REF: Results Values From A Query {F13800}
107675 **
107676 ** These routines return information about
107677 ** a single column of the current result row of a query.  In every
107678 ** case the first argument is a pointer to the 
107679 ** [sqlite3_stmt | SQL statement] that is being
107680 ** evaluated (the [sqlite3_stmt*] that was returned from 
107681 ** [sqlite3_prepare_v2()] or one of its variants) and
107682 ** the second argument is the index of the column for which information 
107683 ** should be returned.  The left-most column of the result set
107684 ** has an index of 0.
107685 **
107686 ** If the SQL statement is not currently point to a valid row, or if the
107687 ** the column index is out of range, the result is undefined. 
107688 ** These routines may only be called when the most recent call to
107689 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
107690 ** [sqlite3_reset()] nor [sqlite3_finalize()] has been call subsequently.
107691 ** If any of these routines are called after [sqlite3_reset()] or
107692 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
107693 ** something other than [SQLITE_ROW], the results are undefined.
107694 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
107695 ** are called from a different thread while any of these routines
107696 ** are pending, then the results are undefined.  
107697 **
107698 ** The sqlite3_column_type() routine returns 
107699 ** [SQLITE_INTEGER | datatype code] for the initial data type
107700 ** of the result column.  The returned value is one of [SQLITE_INTEGER],
107701 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
107702 ** returned by sqlite3_column_type() is only meaningful if no type
107703 ** conversions have occurred as described below.  After a type conversion,
107704 ** the value returned by sqlite3_column_type() is undefined.  Future
107705 ** versions of SQLite may change the behavior of sqlite3_column_type()
107706 ** following a type conversion.
107707 **
107708 ** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() 
107709 ** routine returns the number of bytes in that BLOB or string.
107710 ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
107711 ** the string to UTF-8 and then returns the number of bytes.
107712 ** If the result is a numeric value then sqlite3_column_bytes() uses
107713 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
107714 ** the number of bytes in that string.
107715 ** The value returned does not include the zero terminator at the end
107716 ** of the string.  For clarity: the value returned is the number of
107717 ** bytes in the string, not the number of characters.
107718 **
107719 ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
107720 ** even zero-length strings, are always zero terminated.  The return
107721 ** value from sqlite3_column_blob() for a zero-length blob is an arbitrary
107722 ** pointer, possibly even a NULL pointer.
107723 **
107724 ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
107725 ** but leaves the result in UTF-16 instead of UTF-8.  
107726 ** The zero terminator is not included in this count.
107727 **
107728 ** These routines attempt to convert the value where appropriate.  For
107729 ** example, if the internal representation is FLOAT and a text result
107730 ** is requested, [sqlite3_snprintf()] is used internally to do the conversion
107731 ** automatically.  The following table details the conversions that
107732 ** are applied:
107733 **
107734 ** <blockquote>
107735 ** <table border="1">
107736 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
107737 **
107738 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
107739 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
107740 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
107741 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
107742 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
107743 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
107744 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as for INTEGER->TEXT
107745 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
107746 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
107747 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
107748 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
107749 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
107750 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
107751 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
107752 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
107753 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
107754 ** </table>
107755 ** </blockquote>
107756 **
107757 ** The table above makes reference to standard C library functions atoi()
107758 ** and atof().  SQLite does not really use these functions.  It has its
107759 ** on equavalent internal routines.  The atoi() and atof() names are
107760 ** used in the table for brevity and because they are familiar to most
107761 ** C programmers.
107762 **
107763 ** Note that when type conversions occur, pointers returned by prior
107764 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
107765 ** sqlite3_column_text16() may be invalidated. 
107766 ** Type conversions and pointer invalidations might occur
107767 ** in the following cases:
107768 **
107769 ** <ul>
107770 ** <li><p>  The initial content is a BLOB and sqlite3_column_text() 
107771 **          or sqlite3_column_text16() is called.  A zero-terminator might
107772 **          need to be added to the string.</p></li>
107773 **
107774 ** <li><p>  The initial content is UTF-8 text and sqlite3_column_bytes16() or
107775 **          sqlite3_column_text16() is called.  The content must be converted
107776 **          to UTF-16.</p></li>
107777 **
107778 ** <li><p>  The initial content is UTF-16 text and sqlite3_column_bytes() or
107779 **          sqlite3_column_text() is called.  The content must be converted
107780 **          to UTF-8.</p></li>
107781 ** </ul>
107782 **
107783 ** Conversions between UTF-16be and UTF-16le are always done in place and do
107784 ** not invalidate a prior pointer, though of course the content of the buffer
107785 ** that the prior pointer points to will have been modified.  Other kinds
107786 ** of conversion are done in place when it is possible, but sometime it is
107787 ** not possible and in those cases prior pointers are invalidated.  
107788 **
107789 ** The safest and easiest to remember policy is to invoke these routines
107790 ** in one of the following ways:
107791 **
107792 **  <ul>
107793 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
107794 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
107795 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
107796 **  </ul>
107797 **
107798 ** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(),
107799 ** or sqlite3_column_text16() first to force the result into the desired
107800 ** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to
107801 ** find the size of the result.  Do not mix call to sqlite3_column_text() or
107802 ** sqlite3_column_blob() with calls to sqlite3_column_bytes16().  And do not
107803 ** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes().
107804 **
107805 ** The pointers returned are valid until a type conversion occurs as
107806 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
107807 ** [sqlite3_finalize()] is called.  The memory space used to hold strings
107808 ** and blobs is freed automatically.  Do <b>not</b> pass the pointers returned
107809 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into 
107810 ** [sqlite3_free()].
107811 **
107812 ** If a memory allocation error occurs during the evaluation of any
107813 ** of these routines, a default value is returned.  The default value
107814 ** is either the integer 0, the floating point number 0.0, or a NULL
107815 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
107816 ** [SQLITE_NOMEM].
107817 */
107818 const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
107819 int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
107820 int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
107821 double sqlite3_column_double(sqlite3_stmt*, int iCol);
107822 int sqlite3_column_int(sqlite3_stmt*, int iCol);
107823 sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
107824 const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
107825 const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
107826 int sqlite3_column_type(sqlite3_stmt*, int iCol);
107827 sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
107828
107829 /*
107830 ** CAPI3REF: Destroy A Prepared Statement Object {F13300}
107831 **
107832 ** The sqlite3_finalize() function is called to delete a 
107833 ** [sqlite3_stmt | compiled SQL statement]. If the statement was
107834 ** executed successfully, or not executed at all, then SQLITE_OK is returned.
107835 ** If execution of the statement failed then an 
107836 ** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code]
107837 ** is returned. 
107838 **
107839 ** This routine can be called at any point during the execution of the
107840 ** [sqlite3_stmt | virtual machine].  If the virtual machine has not 
107841 ** completed execution when this routine is called, that is like
107842 ** encountering an error or an interrupt.  (See [sqlite3_interrupt()].) 
107843 ** Incomplete updates may be rolled back and transactions cancelled,  
107844 ** depending on the circumstances, and the 
107845 ** [SQLITE_ERROR | result code] returned will be [SQLITE_ABORT].
107846 */
107847 int sqlite3_finalize(sqlite3_stmt *pStmt);
107848
107849 /*
107850 ** CAPI3REF: Reset A Prepared Statement Object {F13330}
107851 **
107852 ** The sqlite3_reset() function is called to reset a 
107853 ** [sqlite3_stmt | compiled SQL statement] object.
107854 ** back to its initial state, ready to be re-executed.
107855 ** Any SQL statement variables that had values bound to them using
107856 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
107857 ** Use [sqlite3_clear_bindings()] to reset the bindings.
107858 */
107859 int sqlite3_reset(sqlite3_stmt *pStmt);
107860
107861 /*
107862 ** CAPI3REF: Create Or Redefine SQL Functions {F16100}
107863 **
107864 ** The following two functions are used to add SQL functions or aggregates
107865 ** or to redefine the behavior of existing SQL functions or aggregates.  The
107866 ** difference only between the two is that the second parameter, the
107867 ** name of the (scalar) function or aggregate, is encoded in UTF-8 for
107868 ** sqlite3_create_function() and UTF-16 for sqlite3_create_function16().
107869 **
107870 ** The first argument is the [sqlite3 | database handle] that holds the
107871 ** SQL function or aggregate is to be added or redefined. If a single
107872 ** program uses more than one database handle internally, then SQL
107873 ** functions or aggregates must be added individually to each database
107874 ** handle with which they will be used.
107875 **
107876 ** The second parameter is the name of the SQL function to be created
107877 ** or redefined.
107878 ** The length of the name is limited to 255 bytes, exclusive of the 
107879 ** zero-terminator.  Note that the name length limit is in bytes, not
107880 ** characters.  Any attempt to create a function with a longer name
107881 ** will result in an SQLITE_ERROR error.
107882 **
107883 ** The third parameter is the number of arguments that the SQL function or
107884 ** aggregate takes. If this parameter is negative, then the SQL function or
107885 ** aggregate may take any number of arguments.
107886 **
107887 ** The fourth parameter, eTextRep, specifies what 
107888 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
107889 ** its parameters.  Any SQL function implementation should be able to work
107890 ** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
107891 ** more efficient with one encoding than another.  It is allowed to
107892 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
107893 ** times with the same function but with different values of eTextRep.
107894 ** When multiple implementations of the same function are available, SQLite
107895 ** will pick the one that involves the least amount of data conversion.
107896 ** If there is only a single implementation which does not care what
107897 ** text encoding is used, then the fourth argument should be
107898 ** [SQLITE_ANY].
107899 **
107900 ** The fifth parameter is an arbitrary pointer.  The implementation
107901 ** of the function can gain access to this pointer using
107902 ** [sqlite3_user_data()].
107903 **
107904 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
107905 ** pointers to C-language functions that implement the SQL
107906 ** function or aggregate. A scalar SQL function requires an implementation of
107907 ** the xFunc callback only, NULL pointers should be passed as the xStep
107908 ** and xFinal parameters. An aggregate SQL function requires an implementation
107909 ** of xStep and xFinal and NULL should be passed for xFunc. To delete an
107910 ** existing SQL function or aggregate, pass NULL for all three function
107911 ** callback.
107912 **
107913 ** It is permitted to register multiple implementations of the same
107914 ** functions with the same name but with either differing numbers of
107915 ** arguments or differing perferred text encodings.  SQLite will use
107916 ** the implementation most closely matches the way in which the
107917 ** SQL function is used.
107918 */
107919 int sqlite3_create_function(
107920   sqlite3 *,
107921   const char *zFunctionName,
107922   int nArg,
107923   int eTextRep,
107924   void*,
107925   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
107926   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
107927   void (*xFinal)(sqlite3_context*)
107928 );
107929 int sqlite3_create_function16(
107930   sqlite3*,
107931   const void *zFunctionName,
107932   int nArg,
107933   int eTextRep,
107934   void*,
107935   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
107936   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
107937   void (*xFinal)(sqlite3_context*)
107938 );
107939
107940 /*
107941 ** CAPI3REF: Text Encodings {F10267}
107942 **
107943 ** These constant define integer codes that represent the various
107944 ** text encodings supported by SQLite.
107945 */
107946 #define SQLITE_UTF8           1
107947 #define SQLITE_UTF16LE        2
107948 #define SQLITE_UTF16BE        3
107949 #define SQLITE_UTF16          4    /* Use native byte order */
107950 #define SQLITE_ANY            5    /* sqlite3_create_function only */
107951 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
107952
107953 /*
107954 ** CAPI3REF: Obsolete Functions
107955 **
107956 ** These functions are all now obsolete.  In order to maintain
107957 ** backwards compatibility with older code, we continue to support
107958 ** these functions.  However, new development projects should avoid
107959 ** the use of these functions.  To help encourage people to avoid
107960 ** using these functions, we are not going to tell you want they do.
107961 */
107962 int sqlite3_aggregate_count(sqlite3_context*);
107963 int sqlite3_expired(sqlite3_stmt*);
107964 int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
107965 int sqlite3_global_recover(void);
107966 void sqlite3_thread_cleanup(void);
107967 int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
107968
107969 /*
107970 ** CAPI3REF: Obtaining SQL Function Parameter Values {F15100}
107971 **
107972 ** The C-language implementation of SQL functions and aggregates uses
107973 ** this set of interface routines to access the parameter values on
107974 ** the function or aggregate.
107975 **
107976 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
107977 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
107978 ** define callbacks that implement the SQL functions and aggregates.
107979 ** The 4th parameter to these callbacks is an array of pointers to
107980 ** [sqlite3_value] objects.  There is one [sqlite3_value] object for
107981 ** each parameter to the SQL function.  These routines are used to
107982 ** extract values from the [sqlite3_value] objects.
107983 **
107984 ** These routines work just like the corresponding 
107985 ** [sqlite3_column_blob | sqlite3_column_* routines] except that 
107986 ** these routines take a single [sqlite3_value*] pointer instead
107987 ** of an [sqlite3_stmt*] pointer and an integer column number.
107988 **
107989 ** The sqlite3_value_text16() interface extracts a UTF16 string
107990 ** in the native byte-order of the host machine.  The
107991 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
107992 ** extract UTF16 strings as big-endian and little-endian respectively.
107993 **
107994 ** The sqlite3_value_numeric_type() interface attempts to apply
107995 ** numeric affinity to the value.  This means that an attempt is
107996 ** made to convert the value to an integer or floating point.  If
107997 ** such a conversion is possible without loss of information (in other
107998 ** words if the value is a string that looks like a number)
107999 ** then the conversion is done.  Otherwise no conversion occurs.  The 
108000 ** [SQLITE_INTEGER | datatype] after conversion is returned.
108001 **
108002 ** Please pay particular attention to the fact that the pointer that
108003 ** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or
108004 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
108005 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
108006 ** or [sqlite3_value_text16()].  
108007 **
108008 ** These routines must be called from the same thread as
108009 ** the SQL function that supplied the sqlite3_value* parameters.
108010 ** Or, if the sqlite3_value* argument comes from the [sqlite3_column_value()]
108011 ** interface, then these routines should be called from the same thread
108012 ** that ran [sqlite3_column_value()].
108013 **
108014 */
108015 const void *sqlite3_value_blob(sqlite3_value*);
108016 int sqlite3_value_bytes(sqlite3_value*);
108017 int sqlite3_value_bytes16(sqlite3_value*);
108018 double sqlite3_value_double(sqlite3_value*);
108019 int sqlite3_value_int(sqlite3_value*);
108020 sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
108021 const unsigned char *sqlite3_value_text(sqlite3_value*);
108022 const void *sqlite3_value_text16(sqlite3_value*);
108023 const void *sqlite3_value_text16le(sqlite3_value*);
108024 const void *sqlite3_value_text16be(sqlite3_value*);
108025 int sqlite3_value_type(sqlite3_value*);
108026 int sqlite3_value_numeric_type(sqlite3_value*);
108027
108028 /*
108029 ** CAPI3REF: Obtain Aggregate Function Context {F16210}
108030 **
108031 ** The implementation of aggregate SQL functions use this routine to allocate
108032 ** a structure for storing their state.  
108033 ** {F16211} The first time the sqlite3_aggregate_context() routine is
108034 ** is called for a particular aggregate, SQLite allocates nBytes of memory
108035 ** zeros that memory, and returns a pointer to it.
108036 ** {F16212} On second and subsequent calls to sqlite3_aggregate_context()
108037 ** for the same aggregate function index, the same buffer is returned. {END}
108038 ** The implementation
108039 ** of the aggregate can use the returned buffer to accumulate data.
108040 **
108041 ** {F16213} SQLite automatically frees the allocated buffer when the aggregate
108042 ** query concludes. {END}
108043 **
108044 ** The first parameter should be a copy of the 
108045 ** [sqlite3_context | SQL function context] that is the first
108046 ** parameter to the callback routine that implements the aggregate
108047 ** function.
108048 **
108049 ** This routine must be called from the same thread in which
108050 ** the aggregate SQL function is running.
108051 */
108052 void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
108053
108054 /*
108055 ** CAPI3REF: User Data For Functions {F16240}
108056 **
108057 ** {F16241} The sqlite3_user_data() interface returns a copy of
108058 ** the pointer that was the pUserData parameter (the 5th parameter)
108059 ** of the the [sqlite3_create_function()]
108060 ** and [sqlite3_create_function16()] routines that originally
108061 ** registered the application defined function. {END}
108062 **
108063 ** {U16243} This routine must be called from the same thread in which
108064 ** the application-defined function is running.
108065 */
108066 void *sqlite3_user_data(sqlite3_context*);
108067
108068 /*
108069 ** CAPI3REF: Function Auxiliary Data {F16270}
108070 **
108071 ** The following two functions may be used by scalar SQL functions to
108072 ** associate meta-data with argument values. If the same value is passed to
108073 ** multiple invocations of the same SQL function during query execution, under
108074 ** some circumstances the associated meta-data may be preserved. This may
108075 ** be used, for example, to add a regular-expression matching scalar
108076 ** function. The compiled version of the regular expression is stored as
108077 ** meta-data associated with the SQL value passed as the regular expression
108078 ** pattern.  The compiled regular expression can be reused on multiple
108079 ** invocations of the same function so that the original pattern string
108080 ** does not need to be recompiled on each invocation.
108081 **
108082 ** {F16271}
108083 ** The sqlite3_get_auxdata() interface returns a pointer to the meta-data
108084 ** associated by the sqlite3_set_auxdata() function with the Nth argument
108085 ** value to the application-defined function.
108086 ** {F16272} If no meta-data has been ever been set for the Nth
108087 ** argument of the function, or if the cooresponding function parameter
108088 ** has changed since the meta-data was set, then sqlite3_get_auxdata()
108089 ** returns a NULL pointer.
108090 **
108091 ** {F16275} The sqlite3_set_auxdata() interface saves the meta-data
108092 ** pointed to by its 3rd parameter as the meta-data for the N-th
108093 ** argument of the application-defined function. {END} Subsequent
108094 ** calls to sqlite3_get_auxdata() might return this data, if it has
108095 ** not been destroyed. 
108096 ** {F16277} If it is not NULL, SQLite will invoke the destructor 
108097 ** function given by the 4th parameter to sqlite3_set_auxdata() on
108098 ** the meta-data when the corresponding function parameter changes
108099 ** or when the SQL statement completes, whichever comes first. {END}
108100 **
108101 ** In practice, meta-data is preserved between function calls for
108102 ** expressions that are constant at compile time. This includes literal
108103 ** values and SQL variables.
108104 **
108105 ** These routines must be called from the same thread in which
108106 ** the SQL function is running.
108107 */
108108 void *sqlite3_get_auxdata(sqlite3_context*, int N);
108109 void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
108110
108111
108112 /*
108113 ** CAPI3REF: Constants Defining Special Destructor Behavior {F10280}
108114 **
108115 ** These are special value for the destructor that is passed in as the
108116 ** final argument to routines like [sqlite3_result_blob()].  If the destructor
108117 ** argument is SQLITE_STATIC, it means that the content pointer is constant
108118 ** and will never change.  It does not need to be destroyed.  The 
108119 ** SQLITE_TRANSIENT value means that the content will likely change in
108120 ** the near future and that SQLite should make its own private copy of
108121 ** the content before returning.
108122 **
108123 ** The typedef is necessary to work around problems in certain
108124 ** C++ compilers.  See ticket #2191.
108125 */
108126 typedef void (*sqlite3_destructor_type)(void*);
108127 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
108128 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
108129
108130 /*
108131 ** CAPI3REF: Setting The Result Of An SQL Function {F16400}
108132 **
108133 ** These routines are used by the xFunc or xFinal callbacks that
108134 ** implement SQL functions and aggregates.  See
108135 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
108136 ** for additional information.
108137 **
108138 ** These functions work very much like the 
108139 ** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used
108140 ** to bind values to host parameters in prepared statements.
108141 ** Refer to the
108142 ** [sqlite3_bind_blob | sqlite3_bind_* documentation] for
108143 ** additional information.
108144 **
108145 ** {F16402} The sqlite3_result_blob() interface sets the result from
108146 ** an application defined function to be the BLOB whose content is pointed
108147 ** to by the second parameter and which is N bytes long where N is the
108148 ** third parameter. 
108149 ** {F16403} The sqlite3_result_zeroblob() inerfaces set the result of
108150 ** the application defined function to be a BLOB containing all zero
108151 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
108152 **
108153 ** {F16407} The sqlite3_result_double() interface sets the result from
108154 ** an application defined function to be a floating point value specified
108155 ** by its 2nd argument.
108156 **
108157 ** {F16409} The sqlite3_result_error() and sqlite3_result_error16() functions
108158 ** cause the implemented SQL function to throw an exception.
108159 ** {F16411} SQLite uses the string pointed to by the
108160 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
108161 ** as the text of an error message. {F16412} SQLite interprets the error
108162 ** message string from sqlite3_result_error() as UTF8.  {F16413} SQLite
108163 ** interprets the string from sqlite3_result_error16() as UTF16 in native
108164 ** byte order.  {F16414} If the third parameter to sqlite3_result_error()
108165 ** or sqlite3_result_error16() is negative then SQLite takes as the error
108166 ** message all text up through the first zero character.
108167 ** {F16415} If the third parameter to sqlite3_result_error() or
108168 ** sqlite3_result_error16() is non-negative then SQLite takes that many
108169 ** bytes (not characters) from the 2nd parameter as the error message.
108170 ** {F16417} The sqlite3_result_error() and sqlite3_result_error16()
108171 ** routines make a copy private copy of the error message text before
108172 ** they return.  {END} Hence, the calling function can deallocate or
108173 ** modify the text after they return without harm.
108174 **
108175 ** {F16421} The sqlite3_result_toobig() interface causes SQLite
108176 ** to throw an error indicating that a string or BLOB is to long
108177 ** to represent.  {F16422} The sqlite3_result_nomem() interface
108178 ** causes SQLite to throw an exception indicating that the a
108179 ** memory allocation failed.
108180 **
108181 ** {F16431} The sqlite3_result_int() interface sets the return value
108182 ** of the application-defined function to be the 32-bit signed integer
108183 ** value given in the 2nd argument.
108184 ** {F16432} The sqlite3_result_int64() interface sets the return value
108185 ** of the application-defined function to be the 64-bit signed integer
108186 ** value given in the 2nd argument.
108187 **
108188 ** {F16437} The sqlite3_result_null() interface sets the return value
108189 ** of the application-defined function to be NULL.
108190 **
108191 ** {F16441} The sqlite3_result_text(), sqlite3_result_text16(), 
108192 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
108193 ** set the return value of the application-defined function to be
108194 ** a text string which is represented as UTF-8, UTF-16 native byte order,
108195 ** UTF-16 little endian, or UTF-16 big endian, respectively.
108196 ** {F16442} SQLite takes the text result from the application from
108197 ** the 2nd parameter of the sqlite3_result_text* interfaces.
108198 ** {F16444} If the 3rd parameter to the sqlite3_result_text* interfaces
108199 ** is negative, then SQLite takes result text from the 2nd parameter 
108200 ** through the first zero character.
108201 ** {F16447} If the 3rd parameter to the sqlite3_result_text* interfaces
108202 ** is non-negative, then as many bytes (not characters) of the text
108203 ** pointed to by the 2nd parameter are taken as the application-defined
108204 ** function result.
108205 ** {F16451} If the 4th parameter to the sqlite3_result_text* interfaces
108206 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
108207 ** function as the destructor on the text or blob result when it has
108208 ** finished using that result.
108209 ** {F16453} If the 4th parameter to the sqlite3_result_text* interfaces
108210 ** or sqlite3_result_blob is the special constant SQLITE_STATIC, then
108211 ** SQLite assumes that the text or blob result is constant space and
108212 ** does not copy the space or call a destructor when it has
108213 ** finished using that result.
108214 ** {F16454} If the 4th parameter to the sqlite3_result_text* interfaces
108215 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
108216 ** then SQLite makes a copy of the result into space obtained from
108217 ** from [sqlite3_malloc()] before it returns.
108218 **
108219 ** {F16461} The sqlite3_result_value() interface sets the result of
108220 ** the application-defined function to be a copy the [sqlite3_value]
108221 ** object specified by the 2nd parameter.  {F16463} The
108222 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
108223 ** so that [sqlite3_value] specified in the parameter may change or
108224 ** be deallocated after sqlite3_result_value() returns without harm.
108225 **
108226 ** {U16491} These routines are called from within the different thread 
108227 ** than the one containing the application-defined function that recieved
108228 ** the [sqlite3_context] pointer, the results are undefined.
108229 */
108230 void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
108231 void sqlite3_result_double(sqlite3_context*, double);
108232 void sqlite3_result_error(sqlite3_context*, const char*, int);
108233 void sqlite3_result_error16(sqlite3_context*, const void*, int);
108234 void sqlite3_result_error_toobig(sqlite3_context*);
108235 void sqlite3_result_error_nomem(sqlite3_context*);
108236 void sqlite3_result_int(sqlite3_context*, int);
108237 void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
108238 void sqlite3_result_null(sqlite3_context*);
108239 void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
108240 void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
108241 void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
108242 void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
108243 void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
108244 void sqlite3_result_zeroblob(sqlite3_context*, int n);
108245
108246 /*
108247 ** CAPI3REF: Define New Collating Sequences {F16600}
108248 **
108249 ** {F16601}
108250 ** These functions are used to add new collation sequences to the
108251 ** [sqlite3*] handle specified as the first argument. 
108252 **
108253 ** {F16602}
108254 ** The name of the new collation sequence is specified as a UTF-8 string
108255 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
108256 ** and a UTF-16 string for sqlite3_create_collation16(). {F16603} In all cases
108257 ** the name is passed as the second function argument.
108258 **
108259 ** {F16604}
108260 ** The third argument may be one of the constants [SQLITE_UTF8],
108261 ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
108262 ** routine expects to be passed pointers to strings encoded using UTF-8,
108263 ** UTF-16 little-endian or UTF-16 big-endian respectively. {F16605} The
108264 ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that
108265 ** the routine expects pointers to 16-bit word aligned strings
108266 ** of UTF16 in the native byte order of the host computer.
108267 **
108268 ** {F16607}
108269 ** A pointer to the user supplied routine must be passed as the fifth
108270 ** argument. {F16609} If it is NULL, this is the same as deleting the collation
108271 ** sequence (so that SQLite cannot call it anymore).
108272 ** {F16611} Each time the application
108273 ** supplied function is invoked, it is passed a copy of the void* passed as
108274 ** the fourth argument to sqlite3_create_collation() or
108275 ** sqlite3_create_collation16() as its first parameter.
108276 **
108277 ** {F16612}
108278 ** The remaining arguments to the application-supplied routine are two strings,
108279 ** each represented by a [length, data] pair and encoded in the encoding
108280 ** that was passed as the third argument when the collation sequence was
108281 ** registered. {END} The application defined collation routine should
108282 ** return negative, zero or positive if
108283 ** the first string is less than, equal to, or greater than the second
108284 ** string. i.e. (STRING1 - STRING2).
108285 **
108286 ** {F16615}
108287 ** The sqlite3_create_collation_v2() works like sqlite3_create_collation()
108288 ** excapt that it takes an extra argument which is a destructor for
108289 ** the collation.  {F16617} The destructor is called when the collation is
108290 ** destroyed and is passed a copy of the fourth parameter void* pointer
108291 ** of the sqlite3_create_collation_v2().
108292 ** {F16618}  Collations are destroyed when
108293 ** they are overridden by later calls to the collation creation functions
108294 ** or when the [sqlite3*] database handle is closed using [sqlite3_close()].
108295 */
108296 int sqlite3_create_collation(
108297   sqlite3*, 
108298   const char *zName, 
108299   int eTextRep, 
108300   void*,
108301   int(*xCompare)(void*,int,const void*,int,const void*)
108302 );
108303 int sqlite3_create_collation_v2(
108304   sqlite3*, 
108305   const char *zName, 
108306   int eTextRep, 
108307   void*,
108308   int(*xCompare)(void*,int,const void*,int,const void*),
108309   void(*xDestroy)(void*)
108310 );
108311 int sqlite3_create_collation16(
108312   sqlite3*, 
108313   const char *zName, 
108314   int eTextRep, 
108315   void*,
108316   int(*xCompare)(void*,int,const void*,int,const void*)
108317 );
108318
108319 /*
108320 ** CAPI3REF: Collation Needed Callbacks {F16700}
108321 **
108322 ** {F16701}
108323 ** To avoid having to register all collation sequences before a database
108324 ** can be used, a single callback function may be registered with the
108325 ** database handle to be called whenever an undefined collation sequence is
108326 ** required.
108327 **
108328 ** {F16702}
108329 ** If the function is registered using the sqlite3_collation_needed() API,
108330 ** then it is passed the names of undefined collation sequences as strings
108331 ** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, the names
108332 ** are passed as UTF-16 in machine native byte order. {F16704} A call to either
108333 ** function replaces any existing callback.
108334 **
108335 ** {F16705} When the callback is invoked, the first argument passed is a copy
108336 ** of the second argument to sqlite3_collation_needed() or
108337 ** sqlite3_collation_needed16(). {F16706} The second argument is the database
108338 ** handle.  {F16707} The third argument is one of [SQLITE_UTF8],
108339 ** [SQLITE_UTF16BE], or [SQLITE_UTF16LE], indicating the most
108340 ** desirable form of the collation sequence function required.
108341 ** {F16708} The fourth parameter is the name of the
108342 ** required collation sequence. {END}
108343 **
108344 ** The callback function should register the desired collation using
108345 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
108346 ** [sqlite3_create_collation_v2()].
108347 */
108348 int sqlite3_collation_needed(
108349   sqlite3*, 
108350   void*, 
108351   void(*)(void*,sqlite3*,int eTextRep,const char*)
108352 );
108353 int sqlite3_collation_needed16(
108354   sqlite3*, 
108355   void*,
108356   void(*)(void*,sqlite3*,int eTextRep,const void*)
108357 );
108358
108359 /*
108360 ** Specify the key for an encrypted database.  This routine should be
108361 ** called right after sqlite3_open().
108362 **
108363 ** The code to implement this API is not available in the public release
108364 ** of SQLite.
108365 */
108366 int sqlite3_key(
108367   sqlite3 *db,                   /* Database to be rekeyed */
108368   const void *pKey, int nKey     /* The key */
108369 );
108370
108371 /*
108372 ** Change the key on an open database.  If the current database is not
108373 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
108374 ** database is decrypted.
108375 **
108376 ** The code to implement this API is not available in the public release
108377 ** of SQLite.
108378 */
108379 int sqlite3_rekey(
108380   sqlite3 *db,                   /* Database to be rekeyed */
108381   const void *pKey, int nKey     /* The new key */
108382 );
108383
108384 /*
108385 ** CAPI3REF:  Suspend Execution For A Short Time {F10530}
108386 **
108387 ** {F10531} The sqlite3_sleep() function
108388 ** causes the current thread to suspend execution
108389 ** for at least a number of milliseconds specified in its parameter.
108390 **
108391 ** {F10532} If the operating system does not support sleep requests with 
108392 ** millisecond time resolution, then the time will be rounded up to 
108393 ** the nearest second. {F10533} The number of milliseconds of sleep actually 
108394 ** requested from the operating system is returned.
108395 **
108396 ** {F10534} SQLite implements this interface by calling the xSleep()
108397 ** method of the default [sqlite3_vfs] object. {END}
108398 */
108399 int sqlite3_sleep(int);
108400
108401 /*
108402 ** CAPI3REF:  Name Of The Folder Holding Temporary Files {F10310}
108403 **
108404 ** If this global variable is made to point to a string which is
108405 ** the name of a folder (a.ka. directory), then all temporary files
108406 ** created by SQLite will be placed in that directory.  If this variable
108407 ** is NULL pointer, then SQLite does a search for an appropriate temporary
108408 ** file directory.
108409 **
108410 ** It is not safe to modify this variable once a database connection
108411 ** has been opened.  It is intended that this variable be set once
108412 ** as part of process initialization and before any SQLite interface
108413 ** routines have been call and remain unchanged thereafter.
108414 */
108415 SQLITE_EXTERN char *sqlite3_temp_directory;
108416
108417 /*
108418 ** CAPI3REF:  Test To See If The Database Is In Auto-Commit Mode {F12930}
108419 **
108420 ** {F12931} The sqlite3_get_autocommit() interfaces returns non-zero or
108421 ** zero if the given database connection is or is not in autocommit mode,
108422 ** respectively. {F12932}  Autocommit mode is on
108423 ** by default.  {F12933} Autocommit mode is disabled by a BEGIN statement.
108424 ** {F12934} Autocommit mode is reenabled by a COMMIT or ROLLBACK. {END}
108425 **
108426 ** If certain kinds of errors occur on a statement within a multi-statement
108427 ** transactions (errors including [SQLITE_FULL], [SQLITE_IOERR], 
108428 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
108429 ** transaction might be rolled back automatically.  {F12935} The only way to
108430 ** find out if SQLite automatically rolled back the transaction after
108431 ** an error is to use this function. {END}
108432 **
108433 ** {U12936} If another thread changes the autocommit status of the database
108434 ** connection while this routine is running, then the return value
108435 ** is undefined. {END}
108436 */
108437 int sqlite3_get_autocommit(sqlite3*);
108438
108439 /*
108440 ** CAPI3REF:  Find The Database Handle Of A Prepared Statement {F13120}
108441 **
108442 ** {F13121} The sqlite3_db_handle interface
108443 ** returns the [sqlite3*] database handle to which a
108444 ** [sqlite3_stmt | prepared statement] belongs.
108445 ** {F13122} the database handle returned by sqlite3_db_handle
108446 ** is the same database handle that was
108447 ** the first argument to the [sqlite3_prepare_v2()] or its variants
108448 ** that was used to create the statement in the first place.
108449 */
108450 sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
108451
108452
108453 /*
108454 ** CAPI3REF: Commit And Rollback Notification Callbacks {F12950}
108455 **
108456 ** {F12951} The sqlite3_commit_hook() interface registers a callback
108457 ** function to be invoked whenever a transaction is committed.
108458 ** {F12952} Any callback set by a previous call to sqlite3_commit_hook()
108459 ** for the same database connection is overridden.
108460 ** {F12953} The sqlite3_rollback_hook() interface registers a callback
108461 ** function to be invoked whenever a transaction is committed.
108462 ** {F12954} Any callback set by a previous call to sqlite3_commit_hook()
108463 ** for the same database connection is overridden.
108464 ** {F12956} The pArg argument is passed through
108465 ** to the callback.  {F12957} If the callback on a commit hook function 
108466 ** returns non-zero, then the commit is converted into a rollback.
108467 **
108468 ** {F12958} If another function was previously registered, its
108469 ** pArg value is returned.  Otherwise NULL is returned.
108470 **
108471 ** {F12959} Registering a NULL function disables the callback.
108472 **
108473 ** {F12961} For the purposes of this API, a transaction is said to have been 
108474 ** rolled back if an explicit "ROLLBACK" statement is executed, or
108475 ** an error or constraint causes an implicit rollback to occur.
108476 ** {F12962} The rollback callback is not invoked if a transaction is
108477 ** automatically rolled back because the database connection is closed.
108478 ** {F12964} The rollback callback is not invoked if a transaction is
108479 ** rolled back because a commit callback returned non-zero.
108480 ** <todo> Check on this </todo> {END}
108481 **
108482 ** These are experimental interfaces and are subject to change.
108483 */
108484 void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
108485 void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
108486
108487 /*
108488 ** CAPI3REF: Data Change Notification Callbacks {F12970}
108489 **
108490 ** {F12971} The sqlite3_update_hook() interface
108491 ** registers a callback function with the database connection identified by the 
108492 ** first argument to be invoked whenever a row is updated, inserted or deleted.
108493 ** {F12972} Any callback set by a previous call to this function for the same 
108494 ** database connection is overridden.
108495 **
108496 ** {F12974} The second argument is a pointer to the function to invoke when a 
108497 ** row is updated, inserted or deleted. 
108498 ** {F12976} The first argument to the callback is
108499 ** a copy of the third argument to sqlite3_update_hook().
108500 ** {F12977} The second callback 
108501 ** argument is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
108502 ** depending on the operation that caused the callback to be invoked.
108503 ** {F12978} The third and 
108504 ** fourth arguments to the callback contain pointers to the database and 
108505 ** table name containing the affected row.
108506 ** {F12979} The final callback parameter is 
108507 ** the rowid of the row.
108508 ** {F12981} In the case of an update, this is the rowid after 
108509 ** the update takes place.
108510 **
108511 ** {F12983} The update hook is not invoked when internal system tables are
108512 ** modified (i.e. sqlite_master and sqlite_sequence).
108513 **
108514 ** {F12984} If another function was previously registered, its pArg value
108515 ** is returned.  {F12985} Otherwise NULL is returned.
108516 */
108517 void *sqlite3_update_hook(
108518   sqlite3*, 
108519   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
108520   void*
108521 );
108522
108523 /*
108524 ** CAPI3REF:  Enable Or Disable Shared Pager Cache {F10330}
108525 **
108526 ** {F10331}
108527 ** This routine enables or disables the sharing of the database cache
108528 ** and schema data structures between connections to the same database.
108529 ** {F10332}
108530 ** Sharing is enabled if the argument is true and disabled if the argument
108531 ** is false.
108532 **
108533 ** {F10333} Cache sharing is enabled and disabled
108534 ** for an entire process. {END} This is a change as of SQLite version 3.5.0.
108535 ** In prior versions of SQLite, sharing was
108536 ** enabled or disabled for each thread separately.
108537 **
108538 ** {F10334}
108539 ** The cache sharing mode set by this interface effects all subsequent
108540 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
108541 ** {F10335} Existing database connections continue use the sharing mode
108542 ** that was in effect at the time they were opened. {END}
108543 **
108544 ** Virtual tables cannot be used with a shared cache.  {F10336} When shared
108545 ** cache is enabled, the [sqlite3_create_module()] API used to register
108546 ** virtual tables will always return an error. {END}
108547 **
108548 ** {F10337} This routine returns [SQLITE_OK] if shared cache was
108549 ** enabled or disabled successfully.  {F10338} An [SQLITE_ERROR | error code]
108550 ** is returned otherwise. {END}
108551 **
108552 ** {F10339} Shared cache is disabled by default. {END} But this might change in
108553 ** future releases of SQLite.  Applications that care about shared
108554 ** cache setting should set it explicitly.
108555 */
108556 int sqlite3_enable_shared_cache(int);
108557
108558 /*
108559 ** CAPI3REF:  Attempt To Free Heap Memory {F17340}
108560 **
108561 ** {F17341} The sqlite3_release_memory() interface attempts to
108562 ** free N bytes of heap memory by deallocating non-essential memory
108563 ** allocations held by the database labrary. {END}  Memory used
108564 ** to cache database pages to improve performance is an example of
108565 ** non-essential memory.  {F16342} sqlite3_release_memory() returns
108566 ** the number of bytes actually freed, which might be more or less
108567 ** than the amount requested.
108568 */
108569 int sqlite3_release_memory(int);
108570
108571 /*
108572 ** CAPI3REF:  Impose A Limit On Heap Size {F17350}
108573 **
108574 ** {F16351} The sqlite3_soft_heap_limit() interface
108575 ** places a "soft" limit on the amount of heap memory that may be allocated
108576 ** by SQLite. {F16352} If an internal allocation is requested 
108577 ** that would exceed the soft heap limit, [sqlite3_release_memory()] is
108578 ** invoked one or more times to free up some space before the allocation
108579 ** is made. {END}
108580 **
108581 ** {F16353} The limit is called "soft", because if
108582 ** [sqlite3_release_memory()] cannot
108583 ** free sufficient memory to prevent the limit from being exceeded,
108584 ** the memory is allocated anyway and the current operation proceeds.
108585 **
108586 ** {F16354}
108587 ** A negative or zero value for N means that there is no soft heap limit and
108588 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
108589 ** {F16355} The default value for the soft heap limit is zero.
108590 **
108591 ** SQLite makes a best effort to honor the soft heap limit.  
108592 ** {F16356} But if the soft heap limit cannot honored, execution will
108593 ** continue without error or notification. {END}  This is why the limit is 
108594 ** called a "soft" limit.  It is advisory only.
108595 **
108596 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
108597 ** allocated by a single thread - the same thread in which this routine
108598 ** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
108599 ** applied to all threads. {F16357} The value specified for the soft heap limit
108600 ** is an upper bound on the total memory allocation for all threads. {END}  In
108601 ** version 3.5.0 there is no mechanism for limiting the heap usage for
108602 ** individual threads.
108603 */
108604 void sqlite3_soft_heap_limit(int);
108605
108606 /*
108607 ** CAPI3REF:  Extract Metadata About A Column Of A Table {F12850}
108608 **
108609 ** This routine
108610 ** returns meta-data about a specific column of a specific database
108611 ** table accessible using the connection handle passed as the first function 
108612 ** argument.
108613 **
108614 ** The column is identified by the second, third and fourth parameters to 
108615 ** this function. The second parameter is either the name of the database
108616 ** (i.e. "main", "temp" or an attached database) containing the specified
108617 ** table or NULL. If it is NULL, then all attached databases are searched
108618 ** for the table using the same algorithm as the database engine uses to 
108619 ** resolve unqualified table references.
108620 **
108621 ** The third and fourth parameters to this function are the table and column 
108622 ** name of the desired column, respectively. Neither of these parameters 
108623 ** may be NULL.
108624 **
108625 ** Meta information is returned by writing to the memory locations passed as
108626 ** the 5th and subsequent parameters to this function. Any of these 
108627 ** arguments may be NULL, in which case the corresponding element of meta 
108628 ** information is ommitted.
108629 **
108630 ** <pre>
108631 ** Parameter     Output Type      Description
108632 ** -----------------------------------
108633 **
108634 **   5th         const char*      Data type
108635 **   6th         const char*      Name of the default collation sequence 
108636 **   7th         int              True if the column has a NOT NULL constraint
108637 **   8th         int              True if the column is part of the PRIMARY KEY
108638 **   9th         int              True if the column is AUTOINCREMENT
108639 ** </pre>
108640 **
108641 **
108642 ** The memory pointed to by the character pointers returned for the 
108643 ** declaration type and collation sequence is valid only until the next 
108644 ** call to any sqlite API function.
108645 **
108646 ** If the specified table is actually a view, then an error is returned.
108647 **
108648 ** If the specified column is "rowid", "oid" or "_rowid_" and an 
108649 ** INTEGER PRIMARY KEY column has been explicitly declared, then the output 
108650 ** parameters are set for the explicitly declared column. If there is no
108651 ** explicitly declared IPK column, then the output parameters are set as 
108652 ** follows:
108653 **
108654 ** <pre>
108655 **     data type: "INTEGER"
108656 **     collation sequence: "BINARY"
108657 **     not null: 0
108658 **     primary key: 1
108659 **     auto increment: 0
108660 ** </pre>
108661 **
108662 ** This function may load one or more schemas from database files. If an
108663 ** error occurs during this process, or if the requested table or column
108664 ** cannot be found, an SQLITE error code is returned and an error message
108665 ** left in the database handle (to be retrieved using sqlite3_errmsg()).
108666 **
108667 ** This API is only available if the library was compiled with the
108668 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
108669 */
108670 int sqlite3_table_column_metadata(
108671   sqlite3 *db,                /* Connection handle */
108672   const char *zDbName,        /* Database name or NULL */
108673   const char *zTableName,     /* Table name */
108674   const char *zColumnName,    /* Column name */
108675   char const **pzDataType,    /* OUTPUT: Declared data type */
108676   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
108677   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
108678   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
108679   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
108680 );
108681
108682 /*
108683 ** CAPI3REF: Load An Extension {F12600}
108684 **
108685 ** {F12601} The sqlite3_load_extension() interface
108686 ** attempts to load an SQLite extension library contained in the file
108687 ** zFile. {F12602} The entry point is zProc. {F12603} zProc may be 0
108688 ** in which case the name of the entry point defaults
108689 ** to "sqlite3_extension_init".
108690 **
108691 ** {F12604} The sqlite3_load_extension() interface shall
108692 ** return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
108693 **
108694 ** {F12605}
108695 ** If an error occurs and pzErrMsg is not 0, then the
108696 ** sqlite3_load_extension() interface shall attempt to fill *pzErrMsg with 
108697 ** error message text stored in memory obtained from [sqlite3_malloc()].
108698 ** {END}  The calling function should free this memory
108699 ** by calling [sqlite3_free()].
108700 **
108701 ** {F12606}
108702 ** Extension loading must be enabled using [sqlite3_enable_load_extension()]
108703 ** prior to calling this API or an error will be returned.
108704 */
108705 int sqlite3_load_extension(
108706   sqlite3 *db,          /* Load the extension into this database connection */
108707   const char *zFile,    /* Name of the shared library containing extension */
108708   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
108709   char **pzErrMsg       /* Put error message here if not 0 */
108710 );
108711
108712 /*
108713 ** CAPI3REF:  Enable Or Disable Extension Loading {F12620}
108714 **
108715 ** So as not to open security holes in older applications that are
108716 ** unprepared to deal with extension loading, and as a means of disabling
108717 ** extension loading while evaluating user-entered SQL, the following
108718 ** API is provided to turn the [sqlite3_load_extension()] mechanism on and
108719 ** off.  {F12622} It is off by default. {END} See ticket #1863.
108720 **
108721 ** {F12621} Call the sqlite3_enable_load_extension() routine
108722 ** with onoff==1 to turn extension loading on
108723 ** and call it with onoff==0 to turn it back off again. {END}
108724 */
108725 int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
108726
108727 /*
108728 ** CAPI3REF: Make Arrangements To Automatically Load An Extension {F12640}
108729 **
108730 ** {F12641} This function
108731 ** registers an extension entry point that is automatically invoked
108732 ** whenever a new database connection is opened using
108733 ** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. {END}
108734 **
108735 ** This API can be invoked at program startup in order to register
108736 ** one or more statically linked extensions that will be available
108737 ** to all new database connections.
108738 **
108739 ** {F12642} Duplicate extensions are detected so calling this routine multiple
108740 ** times with the same extension is harmless.
108741 **
108742 ** {F12643} This routine stores a pointer to the extension in an array
108743 ** that is obtained from sqlite_malloc(). {END} If you run a memory leak
108744 ** checker on your program and it reports a leak because of this
108745 ** array, then invoke [sqlite3_reset_auto_extension()] prior
108746 ** to shutdown to free the memory.
108747 **
108748 ** {F12644} Automatic extensions apply across all threads. {END}
108749 **
108750 ** This interface is experimental and is subject to change or
108751 ** removal in future releases of SQLite.
108752 */
108753 int sqlite3_auto_extension(void *xEntryPoint);
108754
108755
108756 /*
108757 ** CAPI3REF: Reset Automatic Extension Loading {F12660}
108758 **
108759 ** {F12661} This function disables all previously registered
108760 ** automatic extensions. {END}  This
108761 ** routine undoes the effect of all prior [sqlite3_automatic_extension()]
108762 ** calls.
108763 **
108764 ** {F12662} This call disabled automatic extensions in all threads. {END}
108765 **
108766 ** This interface is experimental and is subject to change or
108767 ** removal in future releases of SQLite.
108768 */
108769 void sqlite3_reset_auto_extension(void);
108770
108771
108772 /*
108773 ****** EXPERIMENTAL - subject to change without notice **************
108774 **
108775 ** The interface to the virtual-table mechanism is currently considered
108776 ** to be experimental.  The interface might change in incompatible ways.
108777 ** If this is a problem for you, do not use the interface at this time.
108778 **
108779 ** When the virtual-table mechanism stablizes, we will declare the
108780 ** interface fixed, support it indefinitely, and remove this comment.
108781 */
108782
108783 /*
108784 ** Structures used by the virtual table interface
108785 */
108786 typedef struct sqlite3_vtab sqlite3_vtab;
108787 typedef struct sqlite3_index_info sqlite3_index_info;
108788 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
108789 typedef struct sqlite3_module sqlite3_module;
108790
108791 /*
108792 ** A module is a class of virtual tables.  Each module is defined
108793 ** by an instance of the following structure.  This structure consists
108794 ** mostly of methods for the module.
108795 */
108796 struct sqlite3_module {
108797   int iVersion;
108798   int (*xCreate)(sqlite3*, void *pAux,
108799                int argc, const char *const*argv,
108800                sqlite3_vtab **ppVTab, char**);
108801   int (*xConnect)(sqlite3*, void *pAux,
108802                int argc, const char *const*argv,
108803                sqlite3_vtab **ppVTab, char**);
108804   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
108805   int (*xDisconnect)(sqlite3_vtab *pVTab);
108806   int (*xDestroy)(sqlite3_vtab *pVTab);
108807   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
108808   int (*xClose)(sqlite3_vtab_cursor*);
108809   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
108810                 int argc, sqlite3_value **argv);
108811   int (*xNext)(sqlite3_vtab_cursor*);
108812   int (*xEof)(sqlite3_vtab_cursor*);
108813   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
108814   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
108815   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
108816   int (*xBegin)(sqlite3_vtab *pVTab);
108817   int (*xSync)(sqlite3_vtab *pVTab);
108818   int (*xCommit)(sqlite3_vtab *pVTab);
108819   int (*xRollback)(sqlite3_vtab *pVTab);
108820   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
108821                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
108822                        void **ppArg);
108823
108824   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
108825 };
108826
108827 /*
108828 ** The sqlite3_index_info structure and its substructures is used to
108829 ** pass information into and receive the reply from the xBestIndex
108830 ** method of an sqlite3_module.  The fields under **Inputs** are the
108831 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
108832 ** results into the **Outputs** fields.
108833 **
108834 ** The aConstraint[] array records WHERE clause constraints of the
108835 ** form:
108836 **
108837 **         column OP expr
108838 **
108839 ** Where OP is =, &lt;, &lt;=, &gt;, or &gt;=.  
108840 ** The particular operator is stored
108841 ** in aConstraint[].op.  The index of the column is stored in 
108842 ** aConstraint[].iColumn.  aConstraint[].usable is TRUE if the
108843 ** expr on the right-hand side can be evaluated (and thus the constraint
108844 ** is usable) and false if it cannot.
108845 **
108846 ** The optimizer automatically inverts terms of the form "expr OP column"
108847 ** and makes other simplifications to the WHERE clause in an attempt to
108848 ** get as many WHERE clause terms into the form shown above as possible.
108849 ** The aConstraint[] array only reports WHERE clause terms in the correct
108850 ** form that refer to the particular virtual table being queried.
108851 **
108852 ** Information about the ORDER BY clause is stored in aOrderBy[].
108853 ** Each term of aOrderBy records a column of the ORDER BY clause.
108854 **
108855 ** The xBestIndex method must fill aConstraintUsage[] with information
108856 ** about what parameters to pass to xFilter.  If argvIndex>0 then
108857 ** the right-hand side of the corresponding aConstraint[] is evaluated
108858 ** and becomes the argvIndex-th entry in argv.  If aConstraintUsage[].omit
108859 ** is true, then the constraint is assumed to be fully handled by the
108860 ** virtual table and is not checked again by SQLite.
108861 **
108862 ** The idxNum and idxPtr values are recorded and passed into xFilter.
108863 ** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
108864 **
108865 ** The orderByConsumed means that output from xFilter will occur in
108866 ** the correct order to satisfy the ORDER BY clause so that no separate
108867 ** sorting step is required.
108868 **
108869 ** The estimatedCost value is an estimate of the cost of doing the
108870 ** particular lookup.  A full scan of a table with N entries should have
108871 ** a cost of N.  A binary search of a table of N entries should have a
108872 ** cost of approximately log(N).
108873 */
108874 struct sqlite3_index_info {
108875   /* Inputs */
108876   int nConstraint;           /* Number of entries in aConstraint */
108877   struct sqlite3_index_constraint {
108878      int iColumn;              /* Column on left-hand side of constraint */
108879      unsigned char op;         /* Constraint operator */
108880      unsigned char usable;     /* True if this constraint is usable */
108881      int iTermOffset;          /* Used internally - xBestIndex should ignore */
108882   } *aConstraint;            /* Table of WHERE clause constraints */
108883   int nOrderBy;              /* Number of terms in the ORDER BY clause */
108884   struct sqlite3_index_orderby {
108885      int iColumn;              /* Column number */
108886      unsigned char desc;       /* True for DESC.  False for ASC. */
108887   } *aOrderBy;               /* The ORDER BY clause */
108888
108889   /* Outputs */
108890   struct sqlite3_index_constraint_usage {
108891     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
108892     unsigned char omit;      /* Do not code a test for this constraint */
108893   } *aConstraintUsage;
108894   int idxNum;                /* Number used to identify the index */
108895   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
108896   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
108897   int orderByConsumed;       /* True if output is already ordered */
108898   double estimatedCost;      /* Estimated cost of using this index */
108899 };
108900 #define SQLITE_INDEX_CONSTRAINT_EQ    2
108901 #define SQLITE_INDEX_CONSTRAINT_GT    4
108902 #define SQLITE_INDEX_CONSTRAINT_LE    8
108903 #define SQLITE_INDEX_CONSTRAINT_LT    16
108904 #define SQLITE_INDEX_CONSTRAINT_GE    32
108905 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
108906
108907 /*
108908 ** This routine is used to register a new module name with an SQLite
108909 ** connection.  Module names must be registered before creating new
108910 ** virtual tables on the module, or before using preexisting virtual
108911 ** tables of the module.
108912 */
108913 int sqlite3_create_module(
108914   sqlite3 *db,               /* SQLite connection to register module with */
108915   const char *zName,         /* Name of the module */
108916   const sqlite3_module *,    /* Methods for the module */
108917   void *                     /* Client data for xCreate/xConnect */
108918 );
108919
108920 /*
108921 ** This routine is identical to the sqlite3_create_module() method above,
108922 ** except that it allows a destructor function to be specified. It is
108923 ** even more experimental than the rest of the virtual tables API.
108924 */
108925 int sqlite3_create_module_v2(
108926   sqlite3 *db,               /* SQLite connection to register module with */
108927   const char *zName,         /* Name of the module */
108928   const sqlite3_module *,    /* Methods for the module */
108929   void *,                    /* Client data for xCreate/xConnect */
108930   void(*xDestroy)(void*)     /* Module destructor function */
108931 );
108932
108933 /*
108934 ** Every module implementation uses a subclass of the following structure
108935 ** to describe a particular instance of the module.  Each subclass will
108936 ** be tailored to the specific needs of the module implementation.   The
108937 ** purpose of this superclass is to define certain fields that are common
108938 ** to all module implementations.
108939 **
108940 ** Virtual tables methods can set an error message by assigning a
108941 ** string obtained from sqlite3_mprintf() to zErrMsg.  The method should
108942 ** take care that any prior string is freed by a call to sqlite3_free()
108943 ** prior to assigning a new string to zErrMsg.  After the error message
108944 ** is delivered up to the client application, the string will be automatically
108945 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.  Note
108946 ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
108947 ** since virtual tables are commonly implemented in loadable extensions which
108948 ** do not have access to sqlite3MPrintf() or sqlite3Free().
108949 */
108950 struct sqlite3_vtab {
108951   const sqlite3_module *pModule;  /* The module for this virtual table */
108952   int nRef;                       /* Used internally */
108953   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
108954   /* Virtual table implementations will typically add additional fields */
108955 };
108956
108957 /* Every module implementation uses a subclass of the following structure
108958 ** to describe cursors that point into the virtual table and are used
108959 ** to loop through the virtual table.  Cursors are created using the
108960 ** xOpen method of the module.  Each module implementation will define
108961 ** the content of a cursor structure to suit its own needs.
108962 **
108963 ** This superclass exists in order to define fields of the cursor that
108964 ** are common to all implementations.
108965 */
108966 struct sqlite3_vtab_cursor {
108967   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
108968   /* Virtual table implementations will typically add additional fields */
108969 };
108970
108971 /*
108972 ** The xCreate and xConnect methods of a module use the following API
108973 ** to declare the format (the names and datatypes of the columns) of
108974 ** the virtual tables they implement.
108975 */
108976 int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
108977
108978 /*
108979 ** Virtual tables can provide alternative implementations of functions
108980 ** using the xFindFunction method.  But global versions of those functions
108981 ** must exist in order to be overloaded.
108982 **
108983 ** This API makes sure a global version of a function with a particular
108984 ** name and number of parameters exists.  If no such function exists
108985 ** before this API is called, a new function is created.  The implementation
108986 ** of the new function always causes an exception to be thrown.  So
108987 ** the new function is not good for anything by itself.  Its only
108988 ** purpose is to be a place-holder function that can be overloaded
108989 ** by virtual tables.
108990 **
108991 ** This API should be considered part of the virtual table interface,
108992 ** which is experimental and subject to change.
108993 */
108994 int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
108995
108996 /*
108997 ** The interface to the virtual-table mechanism defined above (back up
108998 ** to a comment remarkably similar to this one) is currently considered
108999 ** to be experimental.  The interface might change in incompatible ways.
109000 ** If this is a problem for you, do not use the interface at this time.
109001 **
109002 ** When the virtual-table mechanism stabilizes, we will declare the
109003 ** interface fixed, support it indefinitely, and remove this comment.
109004 **
109005 ****** EXPERIMENTAL - subject to change without notice **************
109006 */
109007
109008 /*
109009 ** CAPI3REF: A Handle To An Open BLOB {F17800}
109010 **
109011 ** An instance of the following opaque structure is used to 
109012 ** represent an blob-handle.  A blob-handle is created by
109013 ** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()].
109014 ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
109015 ** can be used to read or write small subsections of the blob.
109016 ** The [sqlite3_blob_bytes()] interface returns the size of the
109017 ** blob in bytes.
109018 */
109019 typedef struct sqlite3_blob sqlite3_blob;
109020
109021 /*
109022 ** CAPI3REF: Open A BLOB For Incremental I/O {F17810}
109023 **
109024 ** {F17811} This interfaces opens a handle to the blob located
109025 ** in row iRow,, column zColumn, table zTable in database zDb;
109026 ** in other words,  the same blob that would be selected by:
109027 **
109028 ** <pre>
109029 **     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
109030 ** </pre> {END}
109031 **
109032 ** {F17812} If the flags parameter is non-zero, the blob is opened for 
109033 ** read and write access. If it is zero, the blob is opened for read 
109034 ** access. {END}
109035 **
109036 ** {F17813} On success, [SQLITE_OK] is returned and the new 
109037 ** [sqlite3_blob | blob handle] is written to *ppBlob. 
109038 ** {F17814} Otherwise an error code is returned and 
109039 ** any value written to *ppBlob should not be used by the caller.
109040 ** {F17815} This function sets the database-handle error code and message
109041 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()].
109042 ** <todo>We should go through and mark all interfaces that behave this
109043 ** way with a similar statement</todo>
109044 */
109045 int sqlite3_blob_open(
109046   sqlite3*,
109047   const char *zDb,
109048   const char *zTable,
109049   const char *zColumn,
109050   sqlite3_int64 iRow,
109051   int flags,
109052   sqlite3_blob **ppBlob
109053 );
109054
109055 /*
109056 ** CAPI3REF:  Close A BLOB Handle {F17830}
109057 **
109058 ** Close an open [sqlite3_blob | blob handle].
109059 **
109060 ** {F17831} Closing a BLOB shall cause the current transaction to commit
109061 ** if there are no other BLOBs, no pending prepared statements, and the
109062 ** database connection is in autocommit mode.
109063 ** {F17832} If any writes were made to the BLOB, they might be held in cache
109064 ** until the close operation if they will fit. {END}
109065 ** Closing the BLOB often forces the changes
109066 ** out to disk and so if any I/O errors occur, they will likely occur
109067 ** at the time when the BLOB is closed.  {F17833} Any errors that occur during
109068 ** closing are reported as a non-zero return value.
109069 **
109070 ** {F17839} The BLOB is closed unconditionally.  Even if this routine returns
109071 ** an error code, the BLOB is still closed.
109072 */
109073 int sqlite3_blob_close(sqlite3_blob *);
109074
109075 /*
109076 ** CAPI3REF:  Return The Size Of An Open BLOB {F17805}
109077 **
109078 ** {F16806} Return the size in bytes of the blob accessible via the open 
109079 ** [sqlite3_blob | blob-handle] passed as an argument.
109080 */
109081 int sqlite3_blob_bytes(sqlite3_blob *);
109082
109083 /*
109084 ** CAPI3REF:  Read Data From A BLOB Incrementally {F17850}
109085 **
109086 ** This function is used to read data from an open 
109087 ** [sqlite3_blob | blob-handle] into a caller supplied buffer.
109088 ** {F17851} n bytes of data are copied into buffer
109089 ** z from the open blob, starting at offset iOffset.
109090 **
109091 ** {F17852} If offset iOffset is less than n bytes from the end of the blob, 
109092 ** [SQLITE_ERROR] is returned and no data is read.  {F17853} If n is
109093 ** less than zero [SQLITE_ERROR] is returned and no data is read.
109094 **
109095 ** {F17854} On success, SQLITE_OK is returned. Otherwise, an 
109096 ** [SQLITE_ERROR | SQLite error code] or an
109097 ** [SQLITE_IOERR_READ | extended error code] is returned.
109098 */
109099 int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset);
109100
109101 /*
109102 ** CAPI3REF:  Write Data Into A BLOB Incrementally {F17870}
109103 **
109104 ** This function is used to write data into an open 
109105 ** [sqlite3_blob | blob-handle] from a user supplied buffer.
109106 ** {F17871} n bytes of data are copied from the buffer
109107 ** pointed to by z into the open blob, starting at offset iOffset.
109108 **
109109 ** {F17872} If the [sqlite3_blob | blob-handle] passed as the first argument
109110 ** was not opened for writing (the flags parameter to [sqlite3_blob_open()]
109111 *** was zero), this function returns [SQLITE_READONLY].
109112 **
109113 ** {F17873} This function may only modify the contents of the blob; it is
109114 ** not possible to increase the size of a blob using this API.
109115 ** {F17874} If offset iOffset is less than n bytes from the end of the blob, 
109116 ** [SQLITE_ERROR] is returned and no data is written.  {F17875} If n is
109117 ** less than zero [SQLITE_ERROR] is returned and no data is written.
109118 **
109119 ** {F17876} On success, SQLITE_OK is returned. Otherwise, an 
109120 ** [SQLITE_ERROR | SQLite error code] or an
109121 ** [SQLITE_IOERR_READ | extended error code] is returned.
109122 */
109123 int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
109124
109125 /*
109126 ** CAPI3REF:  Virtual File System Objects {F11200}
109127 **
109128 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
109129 ** that SQLite uses to interact
109130 ** with the underlying operating system.  Most builds come with a
109131 ** single default VFS that is appropriate for the host computer.
109132 ** New VFSes can be registered and existing VFSes can be unregistered.
109133 ** The following interfaces are provided.
109134 **
109135 ** {F11201} The sqlite3_vfs_find() interface returns a pointer to 
109136 ** a VFS given its name.  {F11202} Names are case sensitive.
109137 ** {F11203} Names are zero-terminated UTF-8 strings.
109138 ** {F11204} If there is no match, a NULL
109139 ** pointer is returned. {F11205} If zVfsName is NULL then the default 
109140 ** VFS is returned. {END}
109141 **
109142 ** {F11210} New VFSes are registered with sqlite3_vfs_register().
109143 ** {F11211} Each new VFS becomes the default VFS if the makeDflt flag is set.
109144 ** {F11212} The same VFS can be registered multiple times without injury.
109145 ** {F11213} To make an existing VFS into the default VFS, register it again
109146 ** with the makeDflt flag set. {U11214} If two different VFSes with the
109147 ** same name are registered, the behavior is undefined.  {U11215} If a
109148 ** VFS is registered with a name that is NULL or an empty string,
109149 ** then the behavior is undefined.
109150 ** 
109151 ** {F11220} Unregister a VFS with the sqlite3_vfs_unregister() interface.
109152 ** {F11221} If the default VFS is unregistered, another VFS is chosen as
109153 ** the default.  The choice for the new VFS is arbitrary.
109154 */
109155 sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
109156 int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
109157 int sqlite3_vfs_unregister(sqlite3_vfs*);
109158
109159 /*
109160 ** CAPI3REF: Mutexes {F17000}
109161 **
109162 ** The SQLite core uses these routines for thread
109163 ** synchronization.  Though they are intended for internal
109164 ** use by SQLite, code that links against SQLite is
109165 ** permitted to use any of these routines.
109166 **
109167 ** The SQLite source code contains multiple implementations 
109168 ** of these mutex routines.  An appropriate implementation
109169 ** is selected automatically at compile-time.  The following
109170 ** implementations are available in the SQLite core:
109171 **
109172 ** <ul>
109173 ** <li>   SQLITE_MUTEX_OS2
109174 ** <li>   SQLITE_MUTEX_PTHREAD
109175 ** <li>   SQLITE_MUTEX_W32
109176 ** <li>   SQLITE_MUTEX_NOOP
109177 ** </ul>
109178 **
109179 ** The SQLITE_MUTEX_NOOP implementation is a set of routines 
109180 ** that does no real locking and is appropriate for use in 
109181 ** a single-threaded application.  The SQLITE_MUTEX_OS2,
109182 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
109183 ** are appropriate for use on os/2, unix, and windows.
109184 ** 
109185 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
109186 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
109187 ** implementation is included with the library.  The
109188 ** mutex interface routines defined here become external
109189 ** references in the SQLite library for which implementations
109190 ** must be provided by the application.  This facility allows an
109191 ** application that links against SQLite to provide its own mutex
109192 ** implementation without having to modify the SQLite core.
109193 **
109194 ** {F17011} The sqlite3_mutex_alloc() routine allocates a new
109195 ** mutex and returns a pointer to it. {F17012} If it returns NULL
109196 ** that means that a mutex could not be allocated. {F17013} SQLite
109197 ** will unwind its stack and return an error. {F17014} The argument
109198 ** to sqlite3_mutex_alloc() is one of these integer constants:
109199 **
109200 ** <ul>
109201 ** <li>  SQLITE_MUTEX_FAST
109202 ** <li>  SQLITE_MUTEX_RECURSIVE
109203 ** <li>  SQLITE_MUTEX_STATIC_MASTER
109204 ** <li>  SQLITE_MUTEX_STATIC_MEM
109205 ** <li>  SQLITE_MUTEX_STATIC_MEM2
109206 ** <li>  SQLITE_MUTEX_STATIC_PRNG
109207 ** <li>  SQLITE_MUTEX_STATIC_LRU
109208 ** </ul> {END}
109209 **
109210 ** {F17015} The first two constants cause sqlite3_mutex_alloc() to create
109211 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
109212 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END}
109213 ** The mutex implementation does not need to make a distinction
109214 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
109215 ** not want to.  {F17016} But SQLite will only request a recursive mutex in
109216 ** cases where it really needs one.  {END} If a faster non-recursive mutex
109217 ** implementation is available on the host platform, the mutex subsystem
109218 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
109219 **
109220 ** {F17017} The other allowed parameters to sqlite3_mutex_alloc() each return
109221 ** a pointer to a static preexisting mutex. {END}  Four static mutexes are
109222 ** used by the current version of SQLite.  Future versions of SQLite
109223 ** may add additional static mutexes.  Static mutexes are for internal
109224 ** use by SQLite only.  Applications that use SQLite mutexes should
109225 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
109226 ** SQLITE_MUTEX_RECURSIVE.
109227 **
109228 ** {F17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
109229 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
109230 ** returns a different mutex on every call.  {F17034} But for the static 
109231 ** mutex types, the same mutex is returned on every call that has
109232 ** the same type number. {END}
109233 **
109234 ** {F17019} The sqlite3_mutex_free() routine deallocates a previously
109235 ** allocated dynamic mutex. {F17020} SQLite is careful to deallocate every
109236 ** dynamic mutex that it allocates. {U17021} The dynamic mutexes must not be in 
109237 ** use when they are deallocated. {U17022} Attempting to deallocate a static
109238 ** mutex results in undefined behavior. {F17023} SQLite never deallocates
109239 ** a static mutex. {END}
109240 **
109241 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
109242 ** to enter a mutex. {F17024} If another thread is already within the mutex,
109243 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
109244 ** SQLITE_BUSY. {F17025}  The sqlite3_mutex_try() interface returns SQLITE_OK
109245 ** upon successful entry.  {F17026} Mutexes created using
109246 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
109247 ** {F17027} In such cases the,
109248 ** mutex must be exited an equal number of times before another thread
109249 ** can enter.  {U17028} If the same thread tries to enter any other
109250 ** kind of mutex more than once, the behavior is undefined.
109251 ** {F17029} SQLite will never exhibit
109252 ** such behavior in its own use of mutexes. {END}
109253 **
109254 ** Some systems (ex: windows95) do not the operation implemented by
109255 ** sqlite3_mutex_try().  On those systems, sqlite3_mutex_try() will
109256 ** always return SQLITE_BUSY.  {F17030} The SQLite core only ever uses
109257 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior. {END}
109258 **
109259 ** {F17031} The sqlite3_mutex_leave() routine exits a mutex that was
109260 ** previously entered by the same thread.  {U17032} The behavior
109261 ** is undefined if the mutex is not currently entered by the
109262 ** calling thread or is not currently allocated.  {F17033} SQLite will
109263 ** never do either. {END}
109264 **
109265 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
109266 */
109267 sqlite3_mutex *sqlite3_mutex_alloc(int);
109268 void sqlite3_mutex_free(sqlite3_mutex*);
109269 void sqlite3_mutex_enter(sqlite3_mutex*);
109270 int sqlite3_mutex_try(sqlite3_mutex*);
109271 void sqlite3_mutex_leave(sqlite3_mutex*);
109272
109273 /*
109274 ** CAPI3REF: Mutex Verifcation Routines {F17080}
109275 **
109276 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
109277 ** are intended for use inside assert() statements. {F17081} The SQLite core
109278 ** never uses these routines except inside an assert() and applications
109279 ** are advised to follow the lead of the core.  {F17082} The core only
109280 ** provides implementations for these routines when it is compiled
109281 ** with the SQLITE_DEBUG flag.  {U17087} External mutex implementations
109282 ** are only required to provide these routines if SQLITE_DEBUG is
109283 ** defined and if NDEBUG is not defined.
109284 **
109285 ** {F17083} These routines should return true if the mutex in their argument
109286 ** is held or not held, respectively, by the calling thread. {END}
109287 **
109288 ** {X17084} The implementation is not required to provided versions of these
109289 ** routines that actually work.
109290 ** If the implementation does not provide working
109291 ** versions of these routines, it should at least provide stubs
109292 ** that always return true so that one does not get spurious
109293 ** assertion failures. {END}
109294 **
109295 ** {F17085} If the argument to sqlite3_mutex_held() is a NULL pointer then
109296 ** the routine should return 1.  {END} This seems counter-intuitive since
109297 ** clearly the mutex cannot be held if it does not exist.  But the
109298 ** the reason the mutex does not exist is because the build is not
109299 ** using mutexes.  And we do not want the assert() containing the
109300 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
109301 ** the appropriate thing to do.  {F17086} The sqlite3_mutex_notheld() 
109302 ** interface should also return 1 when given a NULL pointer.
109303 */
109304 int sqlite3_mutex_held(sqlite3_mutex*);
109305 int sqlite3_mutex_notheld(sqlite3_mutex*);
109306
109307 /*
109308 ** CAPI3REF: Mutex Types {F17001}
109309 **
109310 ** {F17002} The [sqlite3_mutex_alloc()] interface takes a single argument
109311 ** which is one of these integer constants. {END}
109312 */
109313 #define SQLITE_MUTEX_FAST             0
109314 #define SQLITE_MUTEX_RECURSIVE        1
109315 #define SQLITE_MUTEX_STATIC_MASTER    2
109316 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
109317 #define SQLITE_MUTEX_STATIC_MEM2      4  /* sqlite3_release_memory() */
109318 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
109319 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
109320
109321 /*
109322 ** CAPI3REF: Low-Level Control Of Database Files {F11300}
109323 **
109324 ** {F11301} The [sqlite3_file_control()] interface makes a direct call to the
109325 ** xFileControl method for the [sqlite3_io_methods] object associated
109326 ** with a particular database identified by the second argument. {F11302} The
109327 ** name of the database is the name assigned to the database by the
109328 ** <a href="lang_attach.html">ATTACH</a> SQL command that opened the
109329 ** database. {F11303} To control the main database file, use the name "main"
109330 ** or a NULL pointer. {F11304} The third and fourth parameters to this routine
109331 ** are passed directly through to the second and third parameters of
109332 ** the xFileControl method.  {F11305} The return value of the xFileControl
109333 ** method becomes the return value of this routine.
109334 **
109335 ** {F11306} If the second parameter (zDbName) does not match the name of any
109336 ** open database file, then SQLITE_ERROR is returned. {F11307} This error
109337 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
109338 ** or [sqlite3_errmsg()]. {U11308} The underlying xFileControl method might
109339 ** also return SQLITE_ERROR.  {U11309} There is no way to distinguish between
109340 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
109341 ** xFileControl method. {END}
109342 **
109343 ** See also: [SQLITE_FCNTL_LOCKSTATE]
109344 */
109345 int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
109346
109347 /*
109348 ** Undo the hack that converts floating point types to integer for
109349 ** builds on processors without floating point support.
109350 */
109351 #ifdef SQLITE_OMIT_FLOATING_POINT
109352 # undef double
109353 #endif
109354
109355 #if 0
109356 }  /* End of the 'extern "C"' block */
109357 #endif
109358 #endif
109359
109360 /************** End of sqlite3.h *********************************************/
109361 /************** Continuing where we left off in fts3_tokenizer.h *************/
109362
109363 /*
109364 ** Structures used by the tokenizer interface. When a new tokenizer
109365 ** implementation is registered, the caller provides a pointer to
109366 ** an sqlite3_tokenizer_module containing pointers to the callback
109367 ** functions that make up an implementation.
109368 **
109369 ** When an fts3 table is created, it passes any arguments passed to
109370 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
109371 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
109372 ** implementation. The xCreate() function in turn returns an 
109373 ** sqlite3_tokenizer structure representing the specific tokenizer to
109374 ** be used for the fts3 table (customized by the tokenizer clause arguments).
109375 **
109376 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
109377 ** method is called. It returns an sqlite3_tokenizer_cursor object
109378 ** that may be used to tokenize a specific input buffer based on
109379 ** the tokenization rules supplied by a specific sqlite3_tokenizer
109380 ** object.
109381 */
109382 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
109383 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
109384 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
109385
109386 struct sqlite3_tokenizer_module {
109387
109388   /*
109389   ** Structure version. Should always be set to 0.
109390   */
109391   int iVersion;
109392
109393   /*
109394   ** Create a new tokenizer. The values in the argv[] array are the
109395   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
109396   ** TABLE statement that created the fts3 table. For example, if
109397   ** the following SQL is executed:
109398   **
109399   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
109400   **
109401   ** then argc is set to 2, and the argv[] array contains pointers
109402   ** to the strings "arg1" and "arg2".
109403   **
109404   ** This method should return either SQLITE_OK (0), or an SQLite error 
109405   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
109406   ** to point at the newly created tokenizer structure. The generic
109407   ** sqlite3_tokenizer.pModule variable should not be initialised by
109408   ** this callback. The caller will do so.
109409   */
109410   int (*xCreate)(
109411     int argc,                           /* Size of argv array */
109412     const char *const*argv,             /* Tokenizer argument strings */
109413     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
109414   );
109415
109416   /*
109417   ** Destroy an existing tokenizer. The fts3 module calls this method
109418   ** exactly once for each successful call to xCreate().
109419   */
109420   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
109421
109422   /*
109423   ** Create a tokenizer cursor to tokenize an input buffer. The caller
109424   ** is responsible for ensuring that the input buffer remains valid
109425   ** until the cursor is closed (using the xClose() method). 
109426   */
109427   int (*xOpen)(
109428     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
109429     const char *pInput, int nBytes,      /* Input buffer */
109430     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
109431   );
109432
109433   /*
109434   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
109435   ** method exactly once for each successful call to xOpen().
109436   */
109437   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
109438
109439   /*
109440   ** Retrieve the next token from the tokenizer cursor pCursor. This
109441   ** method should either return SQLITE_OK and set the values of the
109442   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
109443   ** the end of the buffer has been reached, or an SQLite error code.
109444   **
109445   ** *ppToken should be set to point at a buffer containing the 
109446   ** normalized version of the token (i.e. after any case-folding and/or
109447   ** stemming has been performed). *pnBytes should be set to the length
109448   ** of this buffer in bytes. The input text that generated the token is
109449   ** identified by the byte offsets returned in *piStartOffset and
109450   ** *piEndOffset.
109451   **
109452   ** The buffer *ppToken is set to point at is managed by the tokenizer
109453   ** implementation. It is only required to be valid until the next call
109454   ** to xNext() or xClose(). 
109455   */
109456   /* TODO(shess) current implementation requires pInput to be
109457   ** nul-terminated.  This should either be fixed, or pInput/nBytes
109458   ** should be converted to zInput.
109459   */
109460   int (*xNext)(
109461     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
109462     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
109463     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
109464     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
109465     int *piPosition      /* OUT: Number of tokens returned before this one */
109466   );
109467 };
109468
109469 struct sqlite3_tokenizer {
109470   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
109471   /* Tokenizer implementations will typically add additional fields */
109472 };
109473
109474 struct sqlite3_tokenizer_cursor {
109475   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
109476   /* Tokenizer implementations will typically add additional fields */
109477 };
109478
109479 #endif /* _FTS3_TOKENIZER_H_ */
109480
109481 /************** End of fts3_tokenizer.h **************************************/
109482 /************** Continuing where we left off in fts3_tokenizer1.c ************/
109483
109484 typedef struct simple_tokenizer {
109485   sqlite3_tokenizer base;
109486   char delim[128];             /* flag ASCII delimiters */
109487 } simple_tokenizer;
109488
109489 typedef struct simple_tokenizer_cursor {
109490   sqlite3_tokenizer_cursor base;
109491   const char *pInput;          /* input we are tokenizing */
109492   int nBytes;                  /* size of the input */
109493   int iOffset;                 /* current position in pInput */
109494   int iToken;                  /* index of next token to be returned */
109495   char *pToken;                /* storage for current token */
109496   int nTokenAllocated;         /* space allocated to zToken buffer */
109497 } simple_tokenizer_cursor;
109498
109499
109500 /* Forward declaration */
109501 static const sqlite3_tokenizer_module simpleTokenizerModule;
109502
109503 static int simpleDelim(simple_tokenizer *t, unsigned char c){
109504   return c<0x80 && t->delim[c];
109505 }
109506
109507 /*
109508 ** Create a new tokenizer instance.
109509 */
109510 static int simpleCreate(
109511   int argc, const char * const *argv,
109512   sqlite3_tokenizer **ppTokenizer
109513 ){
109514   simple_tokenizer *t;
109515
109516   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
109517   if( t==NULL ) return SQLITE_NOMEM;
109518   memset(t, 0, sizeof(*t));
109519
109520   /* TODO(shess) Delimiters need to remain the same from run to run,
109521   ** else we need to reindex.  One solution would be a meta-table to
109522   ** track such information in the database, then we'd only want this
109523   ** information on the initial create.
109524   */
109525   if( argc>1 ){
109526     int i, n = strlen(argv[1]);
109527     for(i=0; i<n; i++){
109528       unsigned char ch = argv[1][i];
109529       /* We explicitly don't support UTF-8 delimiters for now. */
109530       if( ch>=0x80 ){
109531         sqlite3_free(t);
109532         return SQLITE_ERROR;
109533       }
109534       t->delim[ch] = 1;
109535     }
109536   } else {
109537     /* Mark non-alphanumeric ASCII characters as delimiters */
109538     int i;
109539     for(i=1; i<0x80; i++){
109540       t->delim[i] = !isalnum(i);
109541     }
109542   }
109543
109544   *ppTokenizer = &t->base;
109545   return SQLITE_OK;
109546 }
109547
109548 /*
109549 ** Destroy a tokenizer
109550 */
109551 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
109552   sqlite3_free(pTokenizer);
109553   return SQLITE_OK;
109554 }
109555
109556 /*
109557 ** Prepare to begin tokenizing a particular string.  The input
109558 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
109559 ** used to incrementally tokenize this string is returned in 
109560 ** *ppCursor.
109561 */
109562 static int simpleOpen(
109563   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
109564   const char *pInput, int nBytes,        /* String to be tokenized */
109565   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
109566 ){
109567   simple_tokenizer_cursor *c;
109568
109569   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
109570   if( c==NULL ) return SQLITE_NOMEM;
109571
109572   c->pInput = pInput;
109573   if( pInput==0 ){
109574     c->nBytes = 0;
109575   }else if( nBytes<0 ){
109576     c->nBytes = (int)strlen(pInput);
109577   }else{
109578     c->nBytes = nBytes;
109579   }
109580   c->iOffset = 0;                 /* start tokenizing at the beginning */
109581   c->iToken = 0;
109582   c->pToken = NULL;               /* no space allocated, yet. */
109583   c->nTokenAllocated = 0;
109584
109585   *ppCursor = &c->base;
109586   return SQLITE_OK;
109587 }
109588
109589 /*
109590 ** Close a tokenization cursor previously opened by a call to
109591 ** simpleOpen() above.
109592 */
109593 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
109594   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
109595   sqlite3_free(c->pToken);
109596   sqlite3_free(c);
109597   return SQLITE_OK;
109598 }
109599
109600 /*
109601 ** Extract the next token from a tokenization cursor.  The cursor must
109602 ** have been opened by a prior call to simpleOpen().
109603 */
109604 static int simpleNext(
109605   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
109606   const char **ppToken,               /* OUT: *ppToken is the token text */
109607   int *pnBytes,                       /* OUT: Number of bytes in token */
109608   int *piStartOffset,                 /* OUT: Starting offset of token */
109609   int *piEndOffset,                   /* OUT: Ending offset of token */
109610   int *piPosition                     /* OUT: Position integer of token */
109611 ){
109612   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
109613   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
109614   unsigned char *p = (unsigned char *)c->pInput;
109615
109616   while( c->iOffset<c->nBytes ){
109617     int iStartOffset;
109618
109619     /* Scan past delimiter characters */
109620     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
109621       c->iOffset++;
109622     }
109623
109624     /* Count non-delimiter characters. */
109625     iStartOffset = c->iOffset;
109626     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
109627       c->iOffset++;
109628     }
109629
109630     if( c->iOffset>iStartOffset ){
109631       int i, n = c->iOffset-iStartOffset;
109632       if( n>c->nTokenAllocated ){
109633         c->nTokenAllocated = n+20;
109634         c->pToken = sqlite3_realloc(c->pToken, c->nTokenAllocated);
109635         if( c->pToken==NULL ) return SQLITE_NOMEM;
109636       }
109637       for(i=0; i<n; i++){
109638         /* TODO(shess) This needs expansion to handle UTF-8
109639         ** case-insensitivity.
109640         */
109641         unsigned char ch = p[iStartOffset+i];
109642         c->pToken[i] = ch<0x80 ? tolower(ch) : ch;
109643       }
109644       *ppToken = c->pToken;
109645       *pnBytes = n;
109646       *piStartOffset = iStartOffset;
109647       *piEndOffset = c->iOffset;
109648       *piPosition = c->iToken++;
109649
109650       return SQLITE_OK;
109651     }
109652   }
109653   return SQLITE_DONE;
109654 }
109655
109656 /*
109657 ** The set of routines that implement the simple tokenizer
109658 */
109659 static const sqlite3_tokenizer_module simpleTokenizerModule = {
109660   0,
109661   simpleCreate,
109662   simpleDestroy,
109663   simpleOpen,
109664   simpleClose,
109665   simpleNext,
109666 };
109667
109668 /*
109669 ** Allocate a new simple tokenizer.  Return a pointer to the new
109670 ** tokenizer in *ppModule
109671 */
109672 void sqlite3Fts3SimpleTokenizerModule(
109673   sqlite3_tokenizer_module const**ppModule
109674 ){
109675   *ppModule = &simpleTokenizerModule;
109676 }
109677
109678 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
109679
109680 /************** End of fts3_tokenizer1.c *************************************/
109681 /************** Begin file fts3_icu.c ****************************************/
109682 /*
109683 ** 2007 June 22
109684 **
109685 ** The author disclaims copyright to this source code.  In place of
109686 ** a legal notice, here is a blessing:
109687 **
109688 **    May you do good and not evil.
109689 **    May you find forgiveness for yourself and forgive others.
109690 **    May you share freely, never taking more than you give.
109691 **
109692 *************************************************************************
109693 ** This file implements a tokenizer for fts3 based on the ICU library.
109694 ** 
109695 ** $Id: fts3_icu.c,v 1.2 2007/10/24 21:52:37 shess Exp $
109696 */
109697
109698 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
109699 #ifdef SQLITE_ENABLE_ICU
109700
109701 /************** Include fts3_tokenizer.h in the middle of fts3_icu.c *********/
109702 /************** Begin file fts3_tokenizer.h **********************************/
109703 /*
109704 ** 2006 July 10
109705 **
109706 ** The author disclaims copyright to this source code.
109707 **
109708 *************************************************************************
109709 ** Defines the interface to tokenizers used by fulltext-search.  There
109710 ** are three basic components:
109711 **
109712 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
109713 ** interface functions.  This is essentially the class structure for
109714 ** tokenizers.
109715 **
109716 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
109717 ** including customization information defined at creation time.
109718 **
109719 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
109720 ** tokens from a particular input.
109721 */
109722 #ifndef _FTS3_TOKENIZER_H_
109723 #define _FTS3_TOKENIZER_H_
109724
109725 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
109726 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
109727 ** we will need a way to register the API consistently.
109728 */
109729 /************** Include sqlite3.h in the middle of fts3_tokenizer.h **********/
109730 /************** Begin file sqlite3.h *****************************************/
109731 /*
109732 ** 2001 September 15
109733 **
109734 ** The author disclaims copyright to this source code.  In place of
109735 ** a legal notice, here is a blessing:
109736 **
109737 **    May you do good and not evil.
109738 **    May you find forgiveness for yourself and forgive others.
109739 **    May you share freely, never taking more than you give.
109740 **
109741 *************************************************************************
109742 ** This header file defines the interface that the SQLite library
109743 ** presents to client programs.  If a C-function, structure, datatype,
109744 ** or constant definition does not appear in this file, then it is
109745 ** not a published API of SQLite, is subject to change without
109746 ** notice, and should not be referenced by programs that use SQLite.
109747 **
109748 ** Some of the definitions that are in this file are marked as
109749 ** "experimental".  Experimental interfaces are normally new
109750 ** features recently added to SQLite.  We do not anticipate changes 
109751 ** to experimental interfaces but reserve to make minor changes if
109752 ** experience from use "in the wild" suggest such changes are prudent.
109753 **
109754 ** The official C-language API documentation for SQLite is derived
109755 ** from comments in this file.  This file is the authoritative source
109756 ** on how SQLite interfaces are suppose to operate.
109757 **
109758 ** The name of this file under configuration management is "sqlite.h.in".
109759 ** The makefile makes some minor changes to this file (such as inserting
109760 ** the version number) and changes its name to "sqlite3.h" as
109761 ** part of the build process.
109762 **
109763 ** @(#) $Id: sqlite.h.in,v 1.278 2007/12/13 21:54:11 drh Exp $
109764 */
109765 #ifndef _SQLITE3_H_
109766 #define _SQLITE3_H_
109767
109768 /*
109769 ** Make sure we can call this stuff from C++.
109770 */
109771 #if 0
109772 extern "C" {
109773 #endif
109774
109775
109776 /*
109777 ** Add the ability to override 'extern'
109778 */
109779 #ifndef SQLITE_EXTERN
109780 # define SQLITE_EXTERN extern
109781 #endif
109782
109783 /*
109784 ** Make sure these symbols where not defined by some previous header
109785 ** file.
109786 */
109787 #ifdef SQLITE_VERSION
109788 # undef SQLITE_VERSION
109789 #endif
109790 #ifdef SQLITE_VERSION_NUMBER
109791 # undef SQLITE_VERSION_NUMBER
109792 #endif
109793
109794 /*
109795 ** CAPI3REF: Compile-Time Library Version Numbers {F10010}
109796 **
109797 ** {F10011} The #define in the sqlite3.h header file named
109798 ** SQLITE_VERSION resolves to a string literal that identifies
109799 ** the version of the SQLite library in the format "X.Y.Z", where
109800 ** X is the major version number, Y is the minor version number and Z
109801 ** is the release number.  The X.Y.Z might be followed by "alpha" or "beta".
109802 ** {END} For example "3.1.1beta".
109803 **
109804 ** The X value is always 3 in SQLite.  The X value only changes when
109805 ** backwards compatibility is broken and we intend to never break
109806 ** backwards compatibility.  The Y value only changes when
109807 ** there are major feature enhancements that are forwards compatible
109808 ** but not backwards compatible.  The Z value is incremented with
109809 ** each release but resets back to 0 when Y is incremented.
109810 **
109811 ** {F10014} The SQLITE_VERSION_NUMBER #define resolves to an integer
109812 ** with the value  (X*1000000 + Y*1000 + Z) where X, Y, and Z are as
109813 ** with SQLITE_VERSION. {END} For example, for version "3.1.1beta", 
109814 ** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using 
109815 ** version 3.1.1 or greater at compile time, programs may use the test 
109816 ** (SQLITE_VERSION_NUMBER>=3001001).
109817 **
109818 ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
109819 */
109820 #define SQLITE_VERSION         "3.5.4"
109821 #define SQLITE_VERSION_NUMBER 3005004
109822
109823 /*
109824 ** CAPI3REF: Run-Time Library Version Numbers {F10020}
109825 **
109826 ** {F10021} The sqlite3_libversion_number() interface returns an integer
109827 ** equal to [SQLITE_VERSION_NUMBER].  {END} The value returned
109828 ** by this routine should only be different from the header values
109829 ** if the application is compiled using an sqlite3.h header from a
109830 ** different version of SQLite than library.  Cautious programmers might
109831 ** include a check in their application to verify that 
109832 ** sqlite3_libversion_number() always returns the value 
109833 ** [SQLITE_VERSION_NUMBER].
109834 **
109835 ** {F10022} The sqlite3_version[] string constant contains the text of the
109836 ** [SQLITE_VERSION] string. {F10023} The sqlite3_libversion() function returns
109837 ** a pointer to the sqlite3_version[] string constant. {END} The 
109838 ** sqlite3_libversion() function
109839 ** is provided for DLL users who can only access functions and not
109840 ** constants within the DLL.
109841 */
109842 SQLITE_EXTERN const char sqlite3_version[];
109843 const char *sqlite3_libversion(void);
109844 int sqlite3_libversion_number(void);
109845
109846 /*
109847 ** CAPI3REF: Test To See If The Library Is Threadsafe {F10100}
109848 **
109849 ** {F10101} The sqlite3_threadsafe() routine returns nonzero
109850 ** if SQLite was compiled with its mutexes enabled or zero if
109851 ** SQLite was compiled with mutexes disabled. {END}  If this
109852 ** routine returns false, then it is not safe for simultaneously
109853 ** running threads to both invoke SQLite interfaces.
109854 **
109855 ** Really all this routine does is return true if SQLite was
109856 ** compiled with the -DSQLITE_THREADSAFE=1 option and false if
109857 ** compiled with -DSQLITE_THREADSAFE=0.  If SQLite uses an
109858 ** application-defined mutex subsystem, malloc subsystem, collating
109859 ** sequence, VFS, SQL function, progress callback, commit hook,
109860 ** extension, or other accessories and these add-ons are not
109861 ** threadsafe, then clearly the combination will not be threadsafe
109862 ** either.  Hence, this routine never reports that the library
109863 ** is guaranteed to be threadsafe, only when it is guaranteed not
109864 ** to be.
109865 */
109866 int sqlite3_threadsafe(void);
109867
109868 /*
109869 ** CAPI3REF: Database Connection Handle {F12000}
109870 **
109871 ** Each open SQLite database is represented by pointer to an instance of the
109872 ** opaque structure named "sqlite3".  It is useful to think of an sqlite3
109873 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
109874 ** [sqlite3_open_v2()] interfaces are its constructors
109875 ** and [sqlite3_close()] is its destructor.  There are many other interfaces
109876 ** (such as [sqlite3_prepare_v2()], [sqlite3_create_function()], and
109877 ** [sqlite3_busy_timeout()] to name but three) that are methods on this
109878 ** object.
109879 */
109880 typedef struct sqlite3 sqlite3;
109881
109882
109883 /*
109884 ** CAPI3REF: 64-Bit Integer Types {F10200}
109885 **
109886 ** Because there is no cross-platform way to specify such types
109887 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
109888 ** {F10201} The sqlite_int64 and sqlite3_int64 types specify a
109889 ** 64-bit signed integer. {F10202} The sqlite_uint64 and
109890 ** sqlite3_uint64 types specify a 64-bit unsigned integer. {END}
109891 **
109892 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type
109893 ** definitions.  The sqlite_int64 and sqlite_uint64 types are
109894 ** supported for backwards compatibility only.
109895 */
109896 #ifdef SQLITE_INT64_TYPE
109897   typedef SQLITE_INT64_TYPE sqlite_int64;
109898   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
109899 #elif defined(_MSC_VER) || defined(__BORLANDC__)
109900   typedef __int64 sqlite_int64;
109901   typedef unsigned __int64 sqlite_uint64;
109902 #else
109903   typedef long long int sqlite_int64;
109904   typedef unsigned long long int sqlite_uint64;
109905 #endif
109906 typedef sqlite_int64 sqlite3_int64;
109907 typedef sqlite_uint64 sqlite3_uint64;
109908
109909 /*
109910 ** If compiling for a processor that lacks floating point support,
109911 ** substitute integer for floating-point
109912 */
109913 #ifdef SQLITE_OMIT_FLOATING_POINT
109914 # define double sqlite3_int64
109915 #endif
109916
109917 /*
109918 ** CAPI3REF: Closing A Database Connection {F12010}
109919 **
109920 ** {F12011} The sqlite3_close() interfaces destroys an [sqlite3] object
109921 ** allocated by a prior call to [sqlite3_open()], [sqlite3_open16()], or
109922 ** [sqlite3_open_v2()]. {F12012} Sqlite3_close() releases all
109923 ** memory used by the connection and closes all open files. {END}.
109924 **
109925 ** {F12013} If the database connection contains
109926 ** [sqlite3_stmt | prepared statements] that have not been finalized
109927 ** by [sqlite3_finalize()], then sqlite3_close() returns SQLITE_BUSY
109928 ** and leaves the connection open.  {F12014} Giving sqlite3_close()
109929 ** a NULL pointer is a harmless no-op. {END}
109930 **
109931 ** {U12015} Passing this routine a database connection that has already been
109932 ** closed results in undefined behavior. {U12016} If other interfaces that
109933 ** reference the same database connection are pending (either in the
109934 ** same thread or in different threads) when this routine is called,
109935 ** then the behavior is undefined and is almost certainly undesirable.
109936 */
109937 int sqlite3_close(sqlite3 *);
109938
109939 /*
109940 ** The type for a callback function.
109941 ** This is legacy and deprecated.  It is included for historical
109942 ** compatibility and is not documented.
109943 */
109944 typedef int (*sqlite3_callback)(void*,int,char**, char**);
109945
109946 /*
109947 ** CAPI3REF: One-Step Query Execution Interface {F12100}
109948 **
109949 ** {F12101} The sqlite3_exec() interface evaluates zero or more 
109950 ** UTF-8 encoded, semicolon-separated SQL statements in the zero-terminated
109951 ** string of its second argument.  {F12102} The SQL
109952 ** statements are evaluated in the context of the database connection
109953 ** specified by in the first argument.
109954 ** {F12103} SQL statements are prepared one by one using
109955 ** [sqlite3_prepare()] or the equivalent, evaluated
109956 ** using one or more calls to [sqlite3_step()], then destroyed
109957 ** using [sqlite3_finalize()]. {F12104} The return value of
109958 ** sqlite3_exec() is SQLITE_OK if all SQL statement run
109959 ** successfully.
109960 **
109961 ** {F12105} If one or more of the SQL statements handed to
109962 ** sqlite3_exec() are queries, then
109963 ** the callback function specified by the 3rd parameter is
109964 ** invoked once for each row of the query result. {F12106}
109965 ** If the callback returns a non-zero value then the query
109966 ** is aborted, all subsequent SQL statements
109967 ** are skipped and the sqlite3_exec() function returns the [SQLITE_ABORT].
109968 **
109969 ** {F12107} The 4th parameter to sqlite3_exec() is an arbitrary pointer
109970 ** that is passed through to the callback function as its first parameter.
109971 **
109972 ** {F12108} The 2nd parameter to the callback function is the number of
109973 ** columns in the query result.  {F12109} The 3rd parameter to the callback
109974 ** is an array of pointers to strings holding the values for each column
109975 ** as extracted using [sqlite3_column_text()].  NULL values in the result
109976 ** set result in a NULL pointer.  All other value are in their UTF-8
109977 ** string representation. {F12117}
109978 ** The 4th parameter to the callback is an array of strings
109979 ** obtained using [sqlite3_column_name()] and holding
109980 ** the names of each column, also in UTF-8.
109981 **
109982 ** {F12110} The callback function may be NULL, even for queries.  A NULL
109983 ** callback is not an error.  It just means that no callback
109984 ** will be invoked. 
109985 **
109986 ** {F12112} If an error occurs while parsing or evaluating the SQL
109987 ** then an appropriate error message is written into memory obtained
109988 ** from [sqlite3_malloc()] and *errmsg is made to point to that message
109989 ** assuming errmsg is not NULL.  
109990 ** {U12113} The calling function is responsible for freeing the memory
109991 ** using [sqlite3_free()].
109992 ** {F12116} If [sqlite3_malloc()] fails while attempting to generate
109993 ** the error message, *errmsg is set to NULL.
109994 ** {F12114} If errmsg is NULL then no attempt is made to generate an
109995 ** error message. <todo>Is the return code SQLITE_NOMEM or the original
109996 ** error code?</todo> <todo>What happens if there are multiple errors?
109997 ** Do we get code for the first error, or is the choice of reported
109998 ** error arbitrary?</todo>
109999 **
110000 ** {F12115} The return value is is SQLITE_OK if there are no errors and
110001 ** some other [SQLITE_OK | return code] if there is an error.  
110002 ** The particular return value depends on the type of error.  {END}
110003 */
110004 int sqlite3_exec(
110005   sqlite3*,                                  /* An open database */
110006   const char *sql,                           /* SQL to be evaluted */
110007   int (*callback)(void*,int,char**,char**),  /* Callback function */
110008   void *,                                    /* 1st argument to callback */
110009   char **errmsg                              /* Error msg written here */
110010 );
110011
110012 /*
110013 ** CAPI3REF: Result Codes {F10210}
110014 ** KEYWORDS: SQLITE_OK
110015 **
110016 ** Many SQLite functions return an integer result code from the set shown
110017 ** above in order to indicates success or failure.
110018 **
110019 ** {F10211} The result codes shown here are the only ones returned 
110020 ** by SQLite in its default configuration. {F10212} However, the
110021 ** [sqlite3_extended_result_codes()] API can be used to set a database
110022 ** connectoin to return more detailed result codes. {END}
110023 **
110024 ** See also: [SQLITE_IOERR_READ | extended result codes]
110025 **
110026 */
110027 #define SQLITE_OK           0   /* Successful result */
110028 /* beginning-of-error-codes */
110029 #define SQLITE_ERROR        1   /* SQL error or missing database */
110030 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
110031 #define SQLITE_PERM         3   /* Access permission denied */
110032 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
110033 #define SQLITE_BUSY         5   /* The database file is locked */
110034 #define SQLITE_LOCKED       6   /* A table in the database is locked */
110035 #define SQLITE_NOMEM        7   /* A malloc() failed */
110036 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
110037 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
110038 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
110039 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
110040 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
110041 #define SQLITE_FULL        13   /* Insertion failed because database is full */
110042 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
110043 #define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
110044 #define SQLITE_EMPTY       16   /* Database is empty */
110045 #define SQLITE_SCHEMA      17   /* The database schema changed */
110046 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
110047 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
110048 #define SQLITE_MISMATCH    20   /* Data type mismatch */
110049 #define SQLITE_MISUSE      21   /* Library used incorrectly */
110050 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
110051 #define SQLITE_AUTH        23   /* Authorization denied */
110052 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
110053 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
110054 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
110055 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
110056 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
110057 /* end-of-error-codes */
110058
110059 /*
110060 ** CAPI3REF: Extended Result Codes {F10220}
110061 **
110062 ** In its default configuration, SQLite API routines return one of 26 integer
110063 ** [SQLITE_OK | result codes].  However, experience has shown that
110064 ** many of these result codes are too course-grained.  They do not provide as
110065 ** much information about problems as programmers might like.  In an effort to
110066 ** address this, newer versions of SQLite (version 3.3.8 and later) include
110067 ** support for additional result codes that provide more detailed information
110068 ** about errors. {F10221} The extended result codes are enabled or disabled
110069 ** for each database connection using the [sqlite3_extended_result_codes()]
110070 ** API. {END}
110071 ** 
110072 ** Some of the available extended result codes are listed above.
110073 ** We expect the number of extended result codes will be expand
110074 ** over time.  {U10422} Software that uses extended result codes should expect
110075 ** to see new result codes in future releases of SQLite. {END}
110076 ** 
110077 ** {F10223} The symbolic name for an extended result code always contains
110078 ** a related primary result code as a prefix. {F10224} Primary result
110079 ** codes contain a single "_" character.  {F10225} Extended result codes
110080 ** contain two or more "_" characters. {F10226} The numeric value of an
110081 ** extended result code can be converted to its
110082 ** corresponding primary result code by masking off the lower 8 bytes. {END}
110083 **
110084 ** The SQLITE_OK result code will never be extended.  It will always
110085 ** be exactly zero.
110086 */
110087 #define SQLITE_IOERR_READ          (SQLITE_IOERR | (1<<8))
110088 #define SQLITE_IOERR_SHORT_READ    (SQLITE_IOERR | (2<<8))
110089 #define SQLITE_IOERR_WRITE         (SQLITE_IOERR | (3<<8))
110090 #define SQLITE_IOERR_FSYNC         (SQLITE_IOERR | (4<<8))
110091 #define SQLITE_IOERR_DIR_FSYNC     (SQLITE_IOERR | (5<<8))
110092 #define SQLITE_IOERR_TRUNCATE      (SQLITE_IOERR | (6<<8))
110093 #define SQLITE_IOERR_FSTAT         (SQLITE_IOERR | (7<<8))
110094 #define SQLITE_IOERR_UNLOCK        (SQLITE_IOERR | (8<<8))
110095 #define SQLITE_IOERR_RDLOCK        (SQLITE_IOERR | (9<<8))
110096 #define SQLITE_IOERR_DELETE        (SQLITE_IOERR | (10<<8))
110097 #define SQLITE_IOERR_BLOCKED       (SQLITE_IOERR | (11<<8))
110098 #define SQLITE_IOERR_NOMEM         (SQLITE_IOERR | (12<<8))
110099
110100 /*
110101 ** CAPI3REF: Flags For File Open Operations {F10230}
110102 **
110103 ** {F10231} Some combination of the these bit values are used as the
110104 ** third argument to the [sqlite3_open_v2()] interface and
110105 ** as fourth argument to the xOpen method of the
110106 ** [sqlite3_vfs] object.
110107 */
110108 #define SQLITE_OPEN_READONLY         0x00000001
110109 #define SQLITE_OPEN_READWRITE        0x00000002
110110 #define SQLITE_OPEN_CREATE           0x00000004
110111 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008
110112 #define SQLITE_OPEN_EXCLUSIVE        0x00000010
110113 #define SQLITE_OPEN_MAIN_DB          0x00000100
110114 #define SQLITE_OPEN_TEMP_DB          0x00000200
110115 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400
110116 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800
110117 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000
110118 #define SQLITE_OPEN_SUBJOURNAL       0x00002000
110119 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000
110120
110121 /*
110122 ** CAPI3REF: Device Characteristics {F10240}
110123 **
110124 ** {F10241} The xDeviceCapabilities method of the [sqlite3_io_methods]
110125 ** object returns an integer which is a vector of the these
110126 ** bit values expressing I/O characteristics of the mass storage
110127 ** device that holds the file that the [sqlite3_io_methods]
110128 ** refers to. {END}
110129 **
110130 ** {F10242} The SQLITE_IOCAP_ATOMIC property means that all writes of
110131 ** any size are atomic.  {F10243} The SQLITE_IOCAP_ATOMICnnn values
110132 ** mean that writes of blocks that are nnn bytes in size and
110133 ** are aligned to an address which is an integer multiple of
110134 ** nnn are atomic.  {F10244} The SQLITE_IOCAP_SAFE_APPEND value means
110135 ** that when data is appended to a file, the data is appended
110136 ** first then the size of the file is extended, never the other
110137 ** way around.  {F10245} The SQLITE_IOCAP_SEQUENTIAL property means that
110138 ** information is written to disk in the same order as calls
110139 ** to xWrite().
110140 */
110141 #define SQLITE_IOCAP_ATOMIC          0x00000001
110142 #define SQLITE_IOCAP_ATOMIC512       0x00000002
110143 #define SQLITE_IOCAP_ATOMIC1K        0x00000004
110144 #define SQLITE_IOCAP_ATOMIC2K        0x00000008
110145 #define SQLITE_IOCAP_ATOMIC4K        0x00000010
110146 #define SQLITE_IOCAP_ATOMIC8K        0x00000020
110147 #define SQLITE_IOCAP_ATOMIC16K       0x00000040
110148 #define SQLITE_IOCAP_ATOMIC32K       0x00000080
110149 #define SQLITE_IOCAP_ATOMIC64K       0x00000100
110150 #define SQLITE_IOCAP_SAFE_APPEND     0x00000200
110151 #define SQLITE_IOCAP_SEQUENTIAL      0x00000400
110152
110153 /*
110154 ** CAPI3REF: File Locking Levels {F10250}
110155 **
110156 ** {F10251} SQLite uses one of the following integer values as the second
110157 ** argument to calls it makes to the xLock() and xUnlock() methods
110158 ** of an [sqlite3_io_methods] object. {END}
110159 */
110160 #define SQLITE_LOCK_NONE          0
110161 #define SQLITE_LOCK_SHARED        1
110162 #define SQLITE_LOCK_RESERVED      2
110163 #define SQLITE_LOCK_PENDING       3
110164 #define SQLITE_LOCK_EXCLUSIVE     4
110165
110166 /*
110167 ** CAPI3REF: Synchronization Type Flags {F10260}
110168 **
110169 ** {F10261} When SQLite invokes the xSync() method of an
110170 ** [sqlite3_io_methods] object it uses a combination of the
110171 ** these integer values as the second argument.
110172 **
110173 ** {F10262} When the SQLITE_SYNC_DATAONLY flag is used, it means that the
110174 ** sync operation only needs to flush data to mass storage.  Inode
110175 ** information need not be flushed. {F10263} The SQLITE_SYNC_NORMAL means 
110176 ** to use normal fsync() semantics. {F10264} The SQLITE_SYNC_FULL flag means 
110177 ** to use Mac OS-X style fullsync instead of fsync().
110178 */
110179 #define SQLITE_SYNC_NORMAL        0x00002
110180 #define SQLITE_SYNC_FULL          0x00003
110181 #define SQLITE_SYNC_DATAONLY      0x00010
110182
110183
110184 /*
110185 ** CAPI3REF: OS Interface Open File Handle {F11110}
110186 **
110187 ** An [sqlite3_file] object represents an open file in the OS
110188 ** interface layer.  Individual OS interface implementations will
110189 ** want to subclass this object by appending additional fields
110190 ** for their own use.  The pMethods entry is a pointer to an
110191 ** [sqlite3_io_methods] object that defines methods for performing
110192 ** I/O operations on the open file.
110193 */
110194 typedef struct sqlite3_file sqlite3_file;
110195 struct sqlite3_file {
110196   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
110197 };
110198
110199 /*
110200 ** CAPI3REF: OS Interface File Virtual Methods Object {F11120}
110201 **
110202 ** Every file opened by the [sqlite3_vfs] xOpen method contains a pointer to
110203 ** an instance of the this object.  This object defines the
110204 ** methods used to perform various operations against the open file.
110205 **
110206 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
110207 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
110208 *  The second choice is an
110209 ** OS-X style fullsync.  The SQLITE_SYNC_DATA flag may be ORed in to
110210 ** indicate that only the data of the file and not its inode needs to be
110211 ** synced.
110212 ** 
110213 ** The integer values to xLock() and xUnlock() are one of
110214 ** <ul>
110215 ** <li> [SQLITE_LOCK_NONE],
110216 ** <li> [SQLITE_LOCK_SHARED],
110217 ** <li> [SQLITE_LOCK_RESERVED],
110218 ** <li> [SQLITE_LOCK_PENDING], or
110219 ** <li> [SQLITE_LOCK_EXCLUSIVE].
110220 ** </ul>
110221 ** xLock() increases the lock. xUnlock() decreases the lock.  
110222 ** The xCheckReservedLock() method looks
110223 ** to see if any database connection, either in this
110224 ** process or in some other process, is holding an RESERVED,
110225 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
110226 ** if such a lock exists and false if not.
110227 ** 
110228 ** The xFileControl() method is a generic interface that allows custom
110229 ** VFS implementations to directly control an open file using the
110230 ** [sqlite3_file_control()] interface.  The second "op" argument
110231 ** is an integer opcode.   The third
110232 ** argument is a generic pointer which is intended to be a pointer
110233 ** to a structure that may contain arguments or space in which to
110234 ** write return values.  Potential uses for xFileControl() might be
110235 ** functions to enable blocking locks with timeouts, to change the
110236 ** locking strategy (for example to use dot-file locks), to inquire
110237 ** about the status of a lock, or to break stale locks.  The SQLite
110238 ** core reserves opcodes less than 100 for its own use. 
110239 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
110240 ** Applications that define a custom xFileControl method should use opcodes 
110241 ** greater than 100 to avoid conflicts.
110242 **
110243 ** The xSectorSize() method returns the sector size of the
110244 ** device that underlies the file.  The sector size is the
110245 ** minimum write that can be performed without disturbing
110246 ** other bytes in the file.  The xDeviceCharacteristics()
110247 ** method returns a bit vector describing behaviors of the
110248 ** underlying device:
110249 **
110250 ** <ul>
110251 ** <li> [SQLITE_IOCAP_ATOMIC]
110252 ** <li> [SQLITE_IOCAP_ATOMIC512]
110253 ** <li> [SQLITE_IOCAP_ATOMIC1K]
110254 ** <li> [SQLITE_IOCAP_ATOMIC2K]
110255 ** <li> [SQLITE_IOCAP_ATOMIC4K]
110256 ** <li> [SQLITE_IOCAP_ATOMIC8K]
110257 ** <li> [SQLITE_IOCAP_ATOMIC16K]
110258 ** <li> [SQLITE_IOCAP_ATOMIC32K]
110259 ** <li> [SQLITE_IOCAP_ATOMIC64K]
110260 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
110261 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
110262 ** </ul>
110263 **
110264 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
110265 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
110266 ** mean that writes of blocks that are nnn bytes in size and
110267 ** are aligned to an address which is an integer multiple of
110268 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
110269 ** that when data is appended to a file, the data is appended
110270 ** first then the size of the file is extended, never the other
110271 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
110272 ** information is written to disk in the same order as calls
110273 ** to xWrite().
110274 */
110275 typedef struct sqlite3_io_methods sqlite3_io_methods;
110276 struct sqlite3_io_methods {
110277   int iVersion;
110278   int (*xClose)(sqlite3_file*);
110279   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
110280   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
110281   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
110282   int (*xSync)(sqlite3_file*, int flags);
110283   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
110284   int (*xLock)(sqlite3_file*, int);
110285   int (*xUnlock)(sqlite3_file*, int);
110286   int (*xCheckReservedLock)(sqlite3_file*);
110287   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
110288   int (*xSectorSize)(sqlite3_file*);
110289   int (*xDeviceCharacteristics)(sqlite3_file*);
110290   /* Additional methods may be added in future releases */
110291 };
110292
110293 /*
110294 ** CAPI3REF: Standard File Control Opcodes {F11310}
110295 **
110296 ** These integer constants are opcodes for the xFileControl method
110297 ** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()]
110298 ** interface.
110299 **
110300 ** {F11311} The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
110301 ** opcode cases the xFileControl method to write the current state of
110302 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
110303 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
110304 ** into an integer that the pArg argument points to. {F11312} This capability
110305 ** is used during testing and only needs to be supported when SQLITE_TEST
110306 ** is defined.
110307 */
110308 #define SQLITE_FCNTL_LOCKSTATE        1
110309
110310 /*
110311 ** CAPI3REF: Mutex Handle {F17110}
110312 **
110313 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
110314 ** abstract type for a mutex object.  {F17111} The SQLite core never looks
110315 ** at the internal representation of an [sqlite3_mutex]. {END} It only
110316 ** deals with pointers to the [sqlite3_mutex] object.
110317 **
110318 ** Mutexes are created using [sqlite3_mutex_alloc()].
110319 */
110320 typedef struct sqlite3_mutex sqlite3_mutex;
110321
110322 /*
110323 ** CAPI3REF: OS Interface Object {F11140}
110324 **
110325 ** An instance of this object defines the interface between the
110326 ** SQLite core and the underlying operating system.  The "vfs"
110327 ** in the name of the object stands for "virtual file system".
110328 **
110329 ** The iVersion field is initially 1 but may be larger for future
110330 ** versions of SQLite.  Additional fields may be appended to this
110331 ** object when the iVersion value is increased.
110332 **
110333 ** The szOsFile field is the size of the subclassed [sqlite3_file]
110334 ** structure used by this VFS.  mxPathname is the maximum length of
110335 ** a pathname in this VFS.
110336 **
110337 ** Registered vfs modules are kept on a linked list formed by
110338 ** the pNext pointer.  The [sqlite3_vfs_register()]
110339 ** and [sqlite3_vfs_unregister()] interfaces manage this list
110340 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
110341 ** searches the list.
110342 **
110343 ** The pNext field is the only fields in the sqlite3_vfs 
110344 ** structure that SQLite will ever modify.  SQLite will only access
110345 ** or modify this field while holding a particular static mutex.
110346 ** The application should never modify anything within the sqlite3_vfs
110347 ** object once the object has been registered.
110348 **
110349 ** The zName field holds the name of the VFS module.  The name must
110350 ** be unique across all VFS modules.
110351 **
110352 ** {F11141} SQLite will guarantee that the zFilename string passed to
110353 ** xOpen() is a full pathname as generated by xFullPathname() and
110354 ** that the string will be valid and unchanged until xClose() is
110355 ** called.  {END} So the [sqlite3_file] can store a pointer to the
110356 ** filename if it needs to remember the filename for some reason.
110357 **
110358 ** {F11142} The flags argument to xOpen() includes all bits set in
110359 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
110360 ** or [sqlite3_open16()] is used, then flags includes at least
110361 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END}
110362 ** If xOpen() opens a file read-only then it sets *pOutFlags to
110363 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be
110364 ** set.
110365 ** 
110366 ** {F11143} SQLite will also add one of the following flags to the xOpen()
110367 ** call, depending on the object being opened:
110368 ** 
110369 ** <ul>
110370 ** <li>  [SQLITE_OPEN_MAIN_DB]
110371 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
110372 ** <li>  [SQLITE_OPEN_TEMP_DB]
110373 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
110374 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
110375 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
110376 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
110377 ** </ul> {END}
110378 **
110379 ** The file I/O implementation can use the object type flags to
110380 ** changes the way it deals with files.  For example, an application
110381 ** that does not care about crash recovery or rollback, might make
110382 ** the open of a journal file a no-op.  Writes to this journal are
110383 ** also a no-op.  Any attempt to read the journal return SQLITE_IOERR.
110384 ** Or the implementation might recognize the a database file will
110385 ** be doing page-aligned sector reads and writes in a random order
110386 ** and set up its I/O subsystem accordingly.
110387 ** 
110388 ** {F11144} SQLite might also add one of the following flags to the xOpen
110389 ** method:
110390 ** 
110391 ** <ul>
110392 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
110393 ** <li> [SQLITE_OPEN_EXCLUSIVE]
110394 ** </ul>
110395 ** 
110396 ** {F11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
110397 ** deleted when it is closed.  {F11146} The [SQLITE_OPEN_DELETEONCLOSE]
110398 ** will be set for TEMP  databases, journals and for subjournals. 
110399 ** {F11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened
110400 ** for exclusive access.  This flag is set for all files except
110401 ** for the main database file. {END}
110402 ** 
110403 ** {F11148} At least szOsFile bytes of memory is allocated by SQLite 
110404 ** to hold the  [sqlite3_file] structure passed as the third 
110405 ** argument to xOpen.  {END}  The xOpen method does not have to
110406 ** allocate the structure; it should just fill it in.
110407 ** 
110408 ** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] 
110409 ** to test for the existance of a file,
110410 ** or [SQLITE_ACCESS_READWRITE] to test to see
110411 ** if a file is readable and writable, or [SQLITE_ACCESS_READ]
110412 ** to test to see if a file is at least readable.  {END} The file can be a 
110413 ** directory.
110414 ** 
110415 ** {F11150} SQLite will always allocate at least mxPathname+1 byte for
110416 ** the output buffers for xGetTempname and xFullPathname. {F11151} The exact
110417 ** size of the output buffer is also passed as a parameter to both 
110418 ** methods. {END} If the output buffer is not large enough, SQLITE_CANTOPEN
110419 ** should be returned. As this is handled as a fatal error by SQLite,
110420 ** vfs implementations should endeavor to prevent this by setting 
110421 ** mxPathname to a sufficiently large value.
110422 ** 
110423 ** The xRandomness(), xSleep(), and xCurrentTime() interfaces
110424 ** are not strictly a part of the filesystem, but they are
110425 ** included in the VFS structure for completeness.
110426 ** The xRandomness() function attempts to return nBytes bytes
110427 ** of good-quality randomness into zOut.  The return value is
110428 ** the actual number of bytes of randomness obtained.  The
110429 ** xSleep() method cause the calling thread to sleep for at
110430 ** least the number of microseconds given.  The xCurrentTime()
110431 ** method returns a Julian Day Number for the current date and
110432 ** time.
110433 */
110434 typedef struct sqlite3_vfs sqlite3_vfs;
110435 struct sqlite3_vfs {
110436   int iVersion;            /* Structure version number */
110437   int szOsFile;            /* Size of subclassed sqlite3_file */
110438   int mxPathname;          /* Maximum file pathname length */
110439   sqlite3_vfs *pNext;      /* Next registered VFS */
110440   const char *zName;       /* Name of this virtual file system */
110441   void *pAppData;          /* Pointer to application-specific data */
110442   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
110443                int flags, int *pOutFlags);
110444   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
110445   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags);
110446   int (*xGetTempname)(sqlite3_vfs*, int nOut, char *zOut);
110447   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
110448   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
110449   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
110450   void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol);
110451   void (*xDlClose)(sqlite3_vfs*, void*);
110452   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
110453   int (*xSleep)(sqlite3_vfs*, int microseconds);
110454   int (*xCurrentTime)(sqlite3_vfs*, double*);
110455   /* New fields may be appended in figure versions.  The iVersion
110456   ** value will increment whenever this happens. */
110457 };
110458
110459 /*
110460 ** CAPI3REF: Flags for the xAccess VFS method {F11190}
110461 **
110462 ** {F11191} These integer constants can be used as the third parameter to
110463 ** the xAccess method of an [sqlite3_vfs] object. {END}  They determine
110464 ** the kind of what kind of permissions the xAccess method is
110465 ** looking for.  {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method
110466 ** simply checks to see if the file exists. {F11193} With
110467 ** SQLITE_ACCESS_READWRITE, the xAccess method checks to see
110468 ** if the file is both readable and writable.  {F11194} With
110469 ** SQLITE_ACCESS_READ the xAccess method
110470 ** checks to see if the file is readable.
110471 */
110472 #define SQLITE_ACCESS_EXISTS    0
110473 #define SQLITE_ACCESS_READWRITE 1
110474 #define SQLITE_ACCESS_READ      2
110475
110476 /*
110477 ** CAPI3REF: Enable Or Disable Extended Result Codes {F12200}
110478 **
110479 ** {F12201} The sqlite3_extended_result_codes() routine enables or disables the
110480 ** [SQLITE_IOERR_READ | extended result codes] feature on a database
110481 ** connection if its 2nd parameter is
110482 ** non-zero or zero, respectively. {F12202}
110483 ** By default, SQLite API routines return one of only 26 integer
110484 ** [SQLITE_OK | result codes].  {F12203} When extended result codes
110485 ** are enabled by this routine, the repetoire of result codes can be
110486 ** much larger and can (hopefully) provide more detailed information
110487 ** about the cause of an error.
110488 **
110489 ** {F12204} The second argument is a boolean value that turns extended result
110490 ** codes on and off. {F12205} Extended result codes are off by default for
110491 ** backwards compatibility with older versions of SQLite.
110492 */
110493 int sqlite3_extended_result_codes(sqlite3*, int onoff);
110494
110495 /*
110496 ** CAPI3REF: Last Insert Rowid {F12220}
110497 **
110498 ** {F12221} Each entry in an SQLite table has a unique 64-bit signed
110499 ** integer key called the "rowid".  {F12222} The rowid is always available
110500 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
110501 ** names are not also used by explicitly declared columns. {F12223} If
110502 ** the table has a column of type INTEGER PRIMARY KEY then that column
110503 ** is another an alias for the rowid.
110504 **
110505 ** {F12224} This routine returns the rowid of the most recent
110506 ** successful INSERT into the database from the database connection
110507 ** shown in the first argument.  {F12225} If no successful inserts
110508 ** have ever occurred on this database connection, zero is returned.
110509 **
110510 ** {F12226} If an INSERT occurs within a trigger, then the rowid of the
110511 ** inserted row is returned by this routine as long as the trigger
110512 ** is running.  {F12227} But once the trigger terminates, the value returned
110513 ** by this routine reverts to the last value inserted before the
110514 ** trigger fired.
110515 **
110516 ** {F12228} An INSERT that fails due to a constraint violation is not a
110517 ** successful insert and does not change the value returned by this
110518 ** routine.  {F12229} Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
110519 ** and INSERT OR ABORT make no changes to the return value of this
110520 ** routine when their insertion fails.  {F12231} When INSERT OR REPLACE 
110521 ** encounters a constraint violation, it does not fail.  The
110522 ** INSERT continues to completion after deleting rows that caused
110523 ** the constraint problem so INSERT OR REPLACE will always change
110524 ** the return value of this interface. 
110525 **
110526 ** {UF12232} If another thread does a new insert on the same database connection
110527 ** while this routine is running and thus changes the last insert rowid,
110528 ** then the return value of this routine is undefined.
110529 */
110530 sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
110531
110532 /*
110533 ** CAPI3REF: Count The Number Of Rows Modified {F12240}
110534 **
110535 ** {F12241} This function returns the number of database rows that were changed
110536 ** or inserted or deleted by the most recently completed SQL statement
110537 ** on the connection specified by the first parameter. {F12242} Only
110538 ** changes that are directly specified by the INSERT, UPDATE, or
110539 ** DELETE statement are counted.  Auxiliary changes caused by
110540 ** triggers are not counted. {F12243} Use the [sqlite3_total_changes()] function
110541 ** to find the total number of changes including changes caused by triggers.
110542 **
110543 ** {F12244} Within the body of a trigger, the sqlite3_changes() interface
110544 ** can be called to find the number of
110545 ** changes in the most recently completed INSERT, UPDATE, or DELETE
110546 ** statement within the body of the same trigger.
110547 **
110548 ** {F12245} All changes are counted, even if they are later undone by a
110549 ** ROLLBACK or ABORT.  {F12246} Except, changes associated with creating and
110550 ** dropping tables are not counted.
110551 **
110552 ** {F12247} If a callback invokes [sqlite3_exec()] or [sqlite3_step()]
110553 ** recursively, then the changes in the inner, recursive call are
110554 ** counted together with the changes in the outer call.
110555 **
110556 ** {F12248} SQLite implements the command "DELETE FROM table" without
110557 ** a WHERE clause by dropping and recreating the table.  (This is much
110558 ** faster than going through and deleting individual elements from the
110559 ** table.)  Because of this optimization, the change count for 
110560 ** "DELETE FROM table" will be zero regardless of the number of elements
110561 ** that were originally in the table. {F12251} To get an accurate count
110562 ** of the number of rows deleted, use
110563 ** "DELETE FROM table WHERE 1" instead.
110564 **
110565 ** {UF12252} If another thread makes changes on the same database connection
110566 ** while this routine is running then the return value of this routine
110567 ** is undefined.
110568 */
110569 int sqlite3_changes(sqlite3*);
110570
110571 /*
110572 ** CAPI3REF: Total Number Of Rows Modified {F12260}
110573 ***
110574 ** {F12261} This function returns the number of database rows that have been
110575 ** modified by INSERT, UPDATE or DELETE statements since the database handle
110576 ** was opened. {F12262} The count includes UPDATE, INSERT and DELETE 
110577 ** statements executed as part of trigger programs.  {F12263} All changes
110578 ** are counted as soon as the statement that makes them is completed 
110579 ** (when the statement handle is passed to [sqlite3_reset()] or 
110580 ** [sqlite3_finalize()]). {END}
110581 **
110582 ** See also the [sqlite3_change()] interface.
110583 **
110584 ** {F12265} SQLite implements the command "DELETE FROM table" without
110585 ** a WHERE clause by dropping and recreating the table.  (This is much
110586 ** faster than going
110587 ** through and deleting individual elements form the table.)  Because of
110588 ** this optimization, the change count for "DELETE FROM table" will be
110589 ** zero regardless of the number of elements that were originally in the
110590 ** table. To get an accurate count of the number of rows deleted, use
110591 ** "DELETE FROM table WHERE 1" instead.
110592 **
110593 ** {U12264} If another thread makes changes on the same database connection
110594 ** while this routine is running then the return value of this routine
110595 ** is undefined. {END}
110596 */
110597 int sqlite3_total_changes(sqlite3*);
110598
110599 /*
110600 ** CAPI3REF: Interrupt A Long-Running Query {F12270}
110601 **
110602 ** {F12271} This function causes any pending database operation to abort and
110603 ** return at its earliest opportunity. {END} This routine is typically
110604 ** called in response to a user action such as pressing "Cancel"
110605 ** or Ctrl-C where the user wants a long query operation to halt
110606 ** immediately.
110607 **
110608 ** {F12272} It is safe to call this routine from a thread different from the
110609 ** thread that is currently running the database operation. {U12273} But it
110610 ** is not safe to call this routine with a database connection that
110611 ** is closed or might close before sqlite3_interrupt() returns.
110612 **
110613 ** If an SQL is very nearly finished at the time when sqlite3_interrupt()
110614 ** is called, then it might not have an opportunity to be interrupted.
110615 ** It might continue to completion.
110616 ** {F12274} The SQL operation that is interrupted will return
110617 ** [SQLITE_INTERRUPT].  {F12275} If the interrupted SQL operation is an
110618 ** INSERT, UPDATE, or DELETE that is inside an explicit transaction, 
110619 ** then the entire transaction will be rolled back automatically.
110620 ** {F12276} A call to sqlite3_interrupt() has no effect on SQL statements
110621 ** that are started after sqlite3_interrupt() returns.
110622 */
110623 void sqlite3_interrupt(sqlite3*);
110624
110625 /*
110626 ** CAPI3REF: Determine If An SQL Statement Is Complete {F10510}
110627 **
110628 ** These routines are useful for command-line input to determine if the
110629 ** currently entered text seems to form complete a SQL statement or
110630 ** if additional input is needed before sending the text into
110631 ** SQLite for parsing.  These routines return true if the input string
110632 ** appears to be a complete SQL statement.  A statement is judged to be
110633 ** complete if it ends with a semicolon and is not a fragment of a
110634 ** CREATE TRIGGER statement.  These routines do not parse the SQL and
110635 ** so will not detect syntactically incorrect SQL.
110636 **
110637 ** {F10511} These functions return true if the given input string 
110638 ** ends with a semicolon optionally followed by whitespace or
110639 ** comments. {F10512} For sqlite3_complete(),
110640 ** the parameter must be a zero-terminated UTF-8 string. {F10513} For
110641 ** sqlite3_complete16(), a zero-terminated machine byte order UTF-16 string
110642 ** is required.  {F10514} These routines return false if the terminal
110643 ** semicolon is within a comment, a string literal or a quoted identifier
110644 ** (in other words if the final semicolon is not really a separate token
110645 ** but part of a larger token) or if the final semicolon is
110646 ** in between the BEGIN and END keywords of a CREATE TRIGGER statement.
110647 ** {END}
110648 */
110649 int sqlite3_complete(const char *sql);
110650 int sqlite3_complete16(const void *sql);
110651
110652 /*
110653 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310}
110654 **
110655 ** {F12311} This routine identifies a callback function that might be
110656 ** invoked whenever an attempt is made to open a database table 
110657 ** that another thread or process has locked.
110658 ** {F12312} If the busy callback is NULL, then [SQLITE_BUSY]
110659 ** or [SQLITE_IOERR_BLOCKED]
110660 ** is returned immediately upon encountering the lock.
110661 ** {F12313} If the busy callback is not NULL, then the
110662 ** callback will be invoked with two arguments.  {F12314} The
110663 ** first argument to the handler is a copy of the void* pointer which
110664 ** is the third argument to this routine.  {F12315} The second argument to
110665 ** the handler is the number of times that the busy handler has
110666 ** been invoked for this locking event.  {F12316} If the
110667 ** busy callback returns 0, then no additional attempts are made to
110668 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
110669 ** {F12317} If the callback returns non-zero, then another attempt
110670 ** is made to open the database for reading and the cycle repeats.
110671 **
110672 ** The presence of a busy handler does not guarantee that
110673 ** it will be invoked when there is lock contention. {F12319}
110674 ** If SQLite determines that invoking the busy handler could result in
110675 ** a deadlock, it will go ahead and return [SQLITE_BUSY] or
110676 ** [SQLITE_IOERR_BLOCKED] instead of invoking the
110677 ** busy handler. {END}
110678 ** Consider a scenario where one process is holding a read lock that
110679 ** it is trying to promote to a reserved lock and
110680 ** a second process is holding a reserved lock that it is trying
110681 ** to promote to an exclusive lock.  The first process cannot proceed
110682 ** because it is blocked by the second and the second process cannot
110683 ** proceed because it is blocked by the first.  If both processes
110684 ** invoke the busy handlers, neither will make any progress.  Therefore,
110685 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
110686 ** will induce the first process to release its read lock and allow
110687 ** the second process to proceed.
110688 **
110689 ** {F12321} The default busy callback is NULL. {END}
110690 **
110691 ** {F12322} The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
110692 ** when SQLite is in the middle of a large transaction where all the
110693 ** changes will not fit into the in-memory cache.  {F12323} SQLite will
110694 ** already hold a RESERVED lock on the database file, but it needs
110695 ** to promote this lock to EXCLUSIVE so that it can spill cache
110696 ** pages into the database file without harm to concurrent
110697 ** readers.  {F12324} If it is unable to promote the lock, then the in-memory
110698 ** cache will be left in an inconsistent state and so the error
110699 ** code is promoted from the relatively benign [SQLITE_BUSY] to
110700 ** the more severe [SQLITE_IOERR_BLOCKED].  {F12325} This error code promotion
110701 ** forces an automatic rollback of the changes. {END} See the
110702 ** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError">
110703 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
110704 ** this is important.
110705 **      
110706 ** {F12326} Sqlite is re-entrant, so the busy handler may start a new
110707 ** query. {END} (It is not clear why anyone would every want to do this,
110708 ** but it is allowed, in theory.) {U12327} But the busy handler may not
110709 ** close the database.  Closing the database from a busy handler will delete 
110710 ** data structures out from under the executing query and will 
110711 ** probably result in a segmentation fault or other runtime error. {END}
110712 **
110713 ** {F12328} There can only be a single busy handler defined for each database
110714 ** connection.  Setting a new busy handler clears any previous one. 
110715 ** {F12329} Note that calling [sqlite3_busy_timeout()] will also set or clear
110716 ** the busy handler.
110717 **
110718 ** {F12331} When operating in [sqlite3_enable_shared_cache | shared cache mode],
110719 ** only a single busy handler can be defined for each database file.
110720 ** So if two database connections share a single cache, then changing
110721 ** the busy handler on one connection will also change the busy
110722 ** handler in the other connection.  {F12332} The busy handler is invoked
110723 ** in the thread that was running when the lock contention occurs.
110724 */
110725 int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
110726
110727 /*
110728 ** CAPI3REF: Set A Busy Timeout {F12340}
110729 **
110730 ** {F12341} This routine sets a [sqlite3_busy_handler | busy handler]
110731 ** that sleeps for a while when a
110732 ** table is locked.  {F12342} The handler will sleep multiple times until 
110733 ** at least "ms" milliseconds of sleeping have been done. {F12343} After
110734 ** "ms" milliseconds of sleeping, the handler returns 0 which
110735 ** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
110736 **
110737 ** {F12344} Calling this routine with an argument less than or equal to zero
110738 ** turns off all busy handlers.
110739 **
110740 ** {F12345} There can only be a single busy handler for a particular database
110741 ** connection.  If another busy handler was defined  
110742 ** (using [sqlite3_busy_handler()]) prior to calling
110743 ** this routine, that other busy handler is cleared.
110744 */
110745 int sqlite3_busy_timeout(sqlite3*, int ms);
110746
110747 /*
110748 ** CAPI3REF: Convenience Routines For Running Queries {F12370}
110749 **
110750 ** This next routine is a convenience wrapper around [sqlite3_exec()].
110751 ** {F12371} Instead of invoking a user-supplied callback for each row of the
110752 ** result, this routine remembers each row of the result in memory
110753 ** obtained from [sqlite3_malloc()], then returns all of the result after the
110754 ** query has finished. {F12372}
110755 **
110756 ** As an example, suppose the query result where this table:
110757 **
110758 ** <blockquote><pre>
110759 **        Name        | Age
110760 **        -----------------------
110761 **        Alice       | 43
110762 **        Bob         | 28
110763 **        Cindy       | 21
110764 ** </pre></blockquote>
110765 **
110766 ** If the 3rd argument were &azResult then after the function returns
110767 ** azResult will contain the following data:
110768 **
110769 ** <blockquote><pre>
110770 **        azResult&#91;0] = "Name";
110771 **        azResult&#91;1] = "Age";
110772 **        azResult&#91;2] = "Alice";
110773 **        azResult&#91;3] = "43";
110774 **        azResult&#91;4] = "Bob";
110775 **        azResult&#91;5] = "28";
110776 **        azResult&#91;6] = "Cindy";
110777 **        azResult&#91;7] = "21";
110778 ** </pre></blockquote>
110779 **
110780 ** Notice that there is an extra row of data containing the column
110781 ** headers.  But the *nrow return value is still 3.  *ncolumn is
110782 ** set to 2.  In general, the number of values inserted into azResult
110783 ** will be ((*nrow) + 1)*(*ncolumn).
110784 **
110785 ** {U12374} After the calling function has finished using the result, it should 
110786 ** pass the result data pointer to sqlite3_free_table() in order to 
110787 ** release the memory that was malloc-ed.  Because of the way the 
110788 ** [sqlite3_malloc()] happens, the calling function must not try to call 
110789 ** [sqlite3_free()] directly.  Only [sqlite3_free_table()] is able to release 
110790 ** the memory properly and safely. {END}
110791 **
110792 ** {F12373} The return value of this routine is the same as
110793 ** from [sqlite3_exec()].
110794 */
110795 int sqlite3_get_table(
110796   sqlite3*,              /* An open database */
110797   const char *sql,       /* SQL to be executed */
110798   char ***resultp,       /* Result written to a char *[]  that this points to */
110799   int *nrow,             /* Number of result rows written here */
110800   int *ncolumn,          /* Number of result columns written here */
110801   char **errmsg          /* Error msg written here */
110802 );
110803 void sqlite3_free_table(char **result);
110804
110805 /*
110806 ** CAPI3REF: Formatted String Printing Functions {F17400}
110807 **
110808 ** These routines are workalikes of the "printf()" family of functions
110809 ** from the standard C library.
110810 **
110811 ** {F17401} The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
110812 ** results into memory obtained from [sqlite3_malloc()].
110813 ** {U17402} The strings returned by these two routines should be
110814 ** released by [sqlite3_free()]. {F17403}  Both routines return a
110815 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
110816 ** memory to hold the resulting string.
110817 **
110818 ** {F17404} In sqlite3_snprintf() routine is similar to "snprintf()" from
110819 ** the standard C library.  The result is written into the
110820 ** buffer supplied as the second parameter whose size is given by
110821 ** the first parameter. {END} Note that the order of the
110822 ** first two parameters is reversed from snprintf().  This is an
110823 ** historical accident that cannot be fixed without breaking
110824 ** backwards compatibility.  {F17405} Note also that sqlite3_snprintf()
110825 ** returns a pointer to its buffer instead of the number of
110826 ** characters actually written into the buffer. {END} We admit that
110827 ** the number of characters written would be a more useful return
110828 ** value but we cannot change the implementation of sqlite3_snprintf()
110829 ** now without breaking compatibility.
110830 **
110831 ** {F17406} As long as the buffer size is greater than zero, sqlite3_snprintf()
110832 ** guarantees that the buffer is always zero-terminated. {F17407} The first
110833 ** parameter "n" is the total size of the buffer, including space for
110834 ** the zero terminator.  {END} So the longest string that can be completely
110835 ** written will be n-1 characters.
110836 **
110837 ** These routines all implement some additional formatting
110838 ** options that are useful for constructing SQL statements.
110839 ** All of the usual printf formatting options apply.  In addition, there
110840 ** is are "%q", "%Q", and "%z" options.
110841 **
110842 ** {F17410} The %q option works like %s in that it substitutes a null-terminated
110843 ** string from the argument list.  But %q also doubles every '\'' character.
110844 ** %q is designed for use inside a string literal. {END} By doubling each '\''
110845 ** character it escapes that character and allows it to be inserted into
110846 ** the string.
110847 **
110848 ** For example, so some string variable contains text as follows:
110849 **
110850 ** <blockquote><pre>
110851 **  char *zText = "It's a happy day!";
110852 ** </pre></blockquote>
110853 **
110854 ** One can use this text in an SQL statement as follows:
110855 **
110856 ** <blockquote><pre>
110857 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
110858 **  sqlite3_exec(db, zSQL, 0, 0, 0);
110859 **  sqlite3_free(zSQL);
110860 ** </pre></blockquote>
110861 **
110862 ** Because the %q format string is used, the '\'' character in zText
110863 ** is escaped and the SQL generated is as follows:
110864 **
110865 ** <blockquote><pre>
110866 **  INSERT INTO table1 VALUES('It''s a happy day!')
110867 ** </pre></blockquote>
110868 **
110869 ** This is correct.  Had we used %s instead of %q, the generated SQL
110870 ** would have looked like this:
110871 **
110872 ** <blockquote><pre>
110873 **  INSERT INTO table1 VALUES('It's a happy day!');
110874 ** </pre></blockquote>
110875 **
110876 ** This second example is an SQL syntax error.  As a general rule you
110877 ** should always use %q instead of %s when inserting text into a string 
110878 ** literal.
110879 **
110880 ** {F17411} The %Q option works like %q except it also adds single quotes around
110881 ** the outside of the total string.  Or if the parameter in the argument
110882 ** list is a NULL pointer, %Q substitutes the text "NULL" (without single
110883 ** quotes) in place of the %Q option. {END}  So, for example, one could say:
110884 **
110885 ** <blockquote><pre>
110886 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
110887 **  sqlite3_exec(db, zSQL, 0, 0, 0);
110888 **  sqlite3_free(zSQL);
110889 ** </pre></blockquote>
110890 **
110891 ** The code above will render a correct SQL statement in the zSQL
110892 ** variable even if the zText variable is a NULL pointer.
110893 **
110894 ** {F17412} The "%z" formatting option works exactly like "%s" with the
110895 ** addition that after the string has been read and copied into
110896 ** the result, [sqlite3_free()] is called on the input string. {END}
110897 */
110898 char *sqlite3_mprintf(const char*,...);
110899 char *sqlite3_vmprintf(const char*, va_list);
110900 char *sqlite3_snprintf(int,char*,const char*, ...);
110901
110902 /*
110903 ** CAPI3REF: Memory Allocation Subsystem {F17300}
110904 **
110905 ** {F17301} The SQLite core  uses these three routines for all of its own
110906 ** internal memory allocation needs. {END}  "Core" in the previous sentence
110907 ** does not include operating-system specific VFS implementation.  The
110908 ** windows VFS uses native malloc and free for some operations.
110909 **
110910 ** {F17302} The sqlite3_malloc() routine returns a pointer to a block
110911 ** of memory at least N bytes in length, where N is the parameter.
110912 ** {F17303} If sqlite3_malloc() is unable to obtain sufficient free
110913 ** memory, it returns a NULL pointer.  {F17304} If the parameter N to
110914 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
110915 ** a NULL pointer.
110916 **
110917 ** {F17305} Calling sqlite3_free() with a pointer previously returned
110918 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
110919 ** that it might be reused.  {F17306} The sqlite3_free() routine is
110920 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
110921 ** to sqlite3_free() is harmless.  {U17307} After being freed, memory
110922 ** should neither be read nor written.  Even reading previously freed
110923 ** memory might result in a segmentation fault or other severe error.
110924 ** {U17309} Memory corruption, a segmentation fault, or other severe error
110925 ** might result if sqlite3_free() is called with a non-NULL pointer that
110926 ** was not obtained from sqlite3_malloc() or sqlite3_free().
110927 **
110928 ** {F17310} The sqlite3_realloc() interface attempts to resize a
110929 ** prior memory allocation to be at least N bytes, where N is the
110930 ** second parameter.  The memory allocation to be resized is the first
110931 ** parameter.  {F17311} If the first parameter to sqlite3_realloc()
110932 ** is a NULL pointer then its behavior is identical to calling
110933 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
110934 ** {F17312} If the second parameter to sqlite3_realloc() is zero or
110935 ** negative then the behavior is exactly the same as calling
110936 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
110937 ** {F17313} Sqlite3_realloc() returns a pointer to a memory allocation
110938 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
110939 ** {F17314} If M is the size of the prior allocation, then min(N,M) bytes
110940 ** of the prior allocation are copied into the beginning of buffer returned
110941 ** by sqlite3_realloc() and the prior allocation is freed.
110942 ** {F17315} If sqlite3_realloc() returns NULL, then the prior allocation
110943 ** is not freed.
110944 **
110945 ** {F17316} The memory returned by sqlite3_malloc() and sqlite3_realloc()
110946 ** is always aligned to at least an 8 byte boundary. {END}
110947 **
110948 ** {F17381} The default implementation
110949 ** of the memory allocation subsystem uses the malloc(), realloc()
110950 ** and free() provided by the standard C library. {F17382} However, if 
110951 ** SQLite is compiled with the following C preprocessor macro
110952 **
110953 ** <blockquote> SQLITE_MEMORY_SIZE=<i>NNN</i> </blockquote>
110954 **
110955 ** where <i>NNN</i> is an integer, then SQLite create a static
110956 ** array of at least <i>NNN</i> bytes in size and use that array
110957 ** for all of its dynamic memory allocation needs. {END}  Additional
110958 ** memory allocator options may be added in future releases.
110959 **
110960 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
110961 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
110962 ** implementation of these routines to be omitted.  That capability
110963 ** is no longer provided.  Only built-in memory allocators can be
110964 ** used.
110965 **
110966 ** The windows OS interface layer calls
110967 ** the system malloc() and free() directly when converting
110968 ** filenames between the UTF-8 encoding used by SQLite
110969 ** and whatever filename encoding is used by the particular windows
110970 ** installation.  Memory allocation errors are detected, but
110971 ** they are reported back as [SQLITE_CANTOPEN] or
110972 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
110973 */
110974 void *sqlite3_malloc(int);
110975 void *sqlite3_realloc(void*, int);
110976 void sqlite3_free(void*);
110977
110978 /*
110979 ** CAPI3REF: Memory Allocator Statistics {F17370}
110980 **
110981 ** In addition to the basic three allocation routines 
110982 ** [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()],
110983 ** the memory allocation subsystem included with the SQLite
110984 ** sources provides the interfaces shown here.
110985 **
110986 ** {F17371} The sqlite3_memory_used() routine returns the
110987 ** number of bytes of memory currently outstanding (malloced but not freed).
110988 ** {F17372} The value returned by sqlite3_memory_used() includes
110989 ** any overhead added by SQLite, but not overhead added by the
110990 ** library malloc() that backs the sqlite3_malloc() implementation.
110991 ** {F17373} The sqlite3_memory_highwater() routines returns the
110992 ** maximum number of bytes that have been outstanding at any time
110993 ** since the highwater mark was last reset.
110994 ** {F17374} The byte count returned by sqlite3_memory_highwater()
110995 ** uses the same byte counting rules as sqlite3_memory_used(). {END}
110996 ** In other words, overhead added internally by SQLite is counted,
110997 ** but overhead from the underlying system malloc is not.
110998 ** {F17375} If the parameter to sqlite3_memory_highwater() is true,
110999 ** then the highwater mark is reset to the current value of
111000 ** sqlite3_memory_used() and the prior highwater mark (before the
111001 ** reset) is returned.  {F17376}  If the parameter to 
111002 ** sqlite3_memory_highwater() is zero, then the highwater mark is
111003 ** unchanged.
111004 */
111005 sqlite3_int64 sqlite3_memory_used(void);
111006 sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
111007
111008 /*
111009 ** CAPI3REF: Compile-Time Authorization Callbacks {F12500}
111010 **
111011 ** {F12501} This routine registers a authorizer callback with a particular
111012 ** database connection, supplied in the first argument. {F12502}
111013 ** The authorizer callback is invoked as SQL statements are being compiled
111014 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
111015 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  {F12503} At various
111016 ** points during the compilation process, as logic is being created
111017 ** to perform various actions, the authorizer callback is invoked to
111018 ** see if those actions are allowed.  The authorizer callback should
111019 ** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the
111020 ** specific action but allow the SQL statement to continue to be
111021 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
111022 ** rejected with an error.  {F12504} If the authorizer callback returns
111023 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
111024 ** then [sqlite3_prepare_v2()] or equivalent call that triggered
111025 ** the authorizer shall
111026 ** fail with an SQLITE_ERROR error code and an appropriate error message. {END}
111027 **
111028 ** When the callback returns [SQLITE_OK], that means the operation
111029 ** requested is ok.  {F12505} When the callback returns [SQLITE_DENY], the
111030 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
111031 ** authorizer shall fail
111032 ** with an SQLITE_ERROR error code and an error message explaining that
111033 ** access is denied. {F12506} If the authorizer code (the 2nd parameter
111034 ** to the authorizer callback is anything other than [SQLITE_READ], then
111035 ** a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. 
111036 ** If the authorizer code is [SQLITE_READ] and the callback returns
111037 ** [SQLITE_IGNORE] then the prepared statement is constructed to
111038 ** insert a NULL value in place of the table column that would have
111039 ** been read if [SQLITE_OK] had been returned. {END}
111040 **
111041 ** {F12510} The first parameter to the authorizer callback is a copy of
111042 ** the third parameter to the sqlite3_set_authorizer() interface.
111043 ** {F12511} The second parameter to the callback is an integer 
111044 ** [SQLITE_COPY | action code] that specifies the particular action
111045 ** to be authorized. {END} The available action codes are
111046 ** [SQLITE_COPY | documented separately].  {F12512} The third through sixth
111047 ** parameters to the callback are zero-terminated strings that contain 
111048 ** additional details about the action to be authorized. {END}
111049 **
111050 ** An authorizer is used when preparing SQL statements from an untrusted
111051 ** source, to ensure that the SQL statements do not try to access data
111052 ** that they are not allowed to see, or that they do not try to
111053 ** execute malicious statements that damage the database.  For
111054 ** example, an application may allow a user to enter arbitrary
111055 ** SQL queries for evaluation by a database.  But the application does
111056 ** not want the user to be able to make arbitrary changes to the
111057 ** database.  An authorizer could then be put in place while the
111058 ** user-entered SQL is being prepared that disallows everything
111059 ** except SELECT statements.  
111060 **
111061 ** {F12520} Only a single authorizer can be in place on a database connection
111062 ** at a time.  Each call to sqlite3_set_authorizer overrides the
111063 ** previous call. {F12521}  A NULL authorizer means that no authorization
111064 ** callback is invoked.  {F12522} The default authorizer is NULL. {END}
111065 **
111066 ** Note that the authorizer callback is invoked only during 
111067 ** [sqlite3_prepare()] or its variants.  {F12523} Authorization is not
111068 ** performed during statement evaluation in [sqlite3_step()]. {END}
111069 */
111070 int sqlite3_set_authorizer(
111071   sqlite3*,
111072   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
111073   void *pUserData
111074 );
111075
111076 /*
111077 ** CAPI3REF: Authorizer Return Codes {F12590}
111078 **
111079 ** The [sqlite3_set_authorizer | authorizer callback function] must
111080 ** return either [SQLITE_OK] or one of these two constants in order
111081 ** to signal SQLite whether or not the action is permitted.  See the
111082 ** [sqlite3_set_authorizer | authorizer documentation] for additional
111083 ** information.
111084 */
111085 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
111086 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
111087
111088 /*
111089 ** CAPI3REF: Authorizer Action Codes {F12550}
111090 **
111091 ** The [sqlite3_set_authorizer()] interface registers a callback function
111092 ** that is invoked to authorizer certain SQL statement actions.  {F12551} The
111093 ** second parameter to the callback is an integer code that specifies
111094 ** what action is being authorized.  These are the integer action codes that
111095 ** the authorizer callback may be passed. {END}
111096 **
111097 ** These action code values signify what kind of operation is to be 
111098 ** authorized.  {F12552} The 3rd and 4th parameters to the authorization
111099 ** callback function will be parameters or NULL depending on which of these
111100 ** codes is used as the second parameter. {F12553} The 5th parameter to the
111101 ** authorizer callback is the name of the database ("main", "temp", 
111102 ** etc.) if applicable. {F12554} The 6th parameter to the authorizer callback
111103 ** is the name of the inner-most trigger or view that is responsible for
111104 ** the access attempt or NULL if this access attempt is directly from 
111105 ** top-level SQL code.
111106 */
111107 /******************************************* 3rd ************ 4th ***********/
111108 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
111109 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
111110 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
111111 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
111112 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
111113 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
111114 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
111115 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
111116 #define SQLITE_DELETE                9   /* Table Name      NULL            */
111117 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
111118 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
111119 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
111120 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
111121 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
111122 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
111123 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
111124 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
111125 #define SQLITE_INSERT               18   /* Table Name      NULL            */
111126 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
111127 #define SQLITE_READ                 20   /* Table Name      Column Name     */
111128 #define SQLITE_SELECT               21   /* NULL            NULL            */
111129 #define SQLITE_TRANSACTION          22   /* NULL            NULL            */
111130 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
111131 #define SQLITE_ATTACH               24   /* Filename        NULL            */
111132 #define SQLITE_DETACH               25   /* Database Name   NULL            */
111133 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
111134 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
111135 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
111136 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
111137 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
111138 #define SQLITE_FUNCTION             31   /* Function Name   NULL            */
111139 #define SQLITE_COPY                  0   /* No longer used */
111140
111141 /*
111142 ** CAPI3REF: Tracing And Profiling Functions {F12280}
111143 **
111144 ** These routines register callback functions that can be used for
111145 ** tracing and profiling the execution of SQL statements.
111146 **
111147 ** {F12281} The callback function registered by sqlite3_trace() is invoked
111148 ** at the first [sqlite3_step()] for the evaluation of an SQL statement.
111149 ** {F12282} Only a single trace callback can be registered at a time.
111150 ** Each call to sqlite3_trace() overrides the previous.  {F12283} A
111151 ** NULL callback for sqlite3_trace() disables tracing.  {F12284} The
111152 ** first argument to the trace callback is a copy of the pointer which
111153 ** was the 3rd argument to sqlite3_trace.  {F12285} The second argument
111154 ** to the trace callback is a zero-terminated UTF8 string containing
111155 ** the original text of the SQL statement as it was passed into
111156 ** [sqlite3_prepare_v2()] or the equivalent. {END}  Note that the
111157 ** host parameter are not expanded in the SQL statement text.
111158 **
111159 ** {F12287} The callback function registered by sqlite3_profile() is invoked
111160 ** as each SQL statement finishes.  {F12288} The first parameter to the
111161 ** profile callback is a copy of the 3rd parameter to sqlite3_profile().
111162 ** {F12289} The second parameter to the profile callback is a
111163 ** zero-terminated UTF-8 string that contains the complete text of
111164 ** the SQL statement as it was processed by [sqlite3_prepare_v2()] or
111165 ** the equivalent.  {F12290} The third parameter to the profile 
111166 ** callback is an estimate of the number of nanoseconds of
111167 ** wall-clock time required to run the SQL statement from start
111168 ** to finish. {END}  
111169 **
111170 ** The sqlite3_profile() API is currently considered experimental and
111171 ** is subject to change.
111172 */
111173 void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
111174 void *sqlite3_profile(sqlite3*,
111175    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
111176
111177 /*
111178 ** CAPI3REF: Query Progress Callbacks {F12910}
111179 **
111180 ** {F12911} This routine configures a callback function - the
111181 ** progress callback - that is invoked periodically during long
111182 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
111183 ** [sqlite3_get_table()]. {END}  An example use for this 
111184 ** interface is to keep a GUI updated during a large query.
111185 **
111186 ** {F12912} The progress callback is invoked once for every N virtual
111187 ** machine opcodes, where N is the second argument to this function.
111188 ** {F12913} The progress callback itself is identified by the third
111189 ** argument to this function. {F12914} The fourth argument to this
111190 ** function is a void pointer passed to the progress callback
111191 ** function each time it is invoked. {END}
111192 **
111193 ** {F12915} If a call to [sqlite3_exec()], [sqlite3_step()], or
111194 ** [sqlite3_get_table()] results in fewer than N opcodes being executed,
111195 ** then the progress callback is never invoked. {END}
111196 ** 
111197 ** {F12916} Only a single progress callback function may be registered for each
111198 ** open database connection.  Every call to sqlite3_progress_handler()
111199 ** overwrites the results of the previous call. {F12917}
111200 ** To remove the progress callback altogether, pass NULL as the third
111201 ** argument to this function. {END}
111202 **
111203 ** {F12918} If the progress callback returns a result other than 0, then
111204 ** the current query is immediately terminated and any database changes
111205 ** rolled back. {F12919}
111206 ** The containing [sqlite3_exec()], [sqlite3_step()], or
111207 ** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. {END}  This feature
111208 ** can be used, for example, to implement the "Cancel" button on a
111209 ** progress dialog box in a GUI.
111210 */
111211 void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
111212
111213 /*
111214 ** CAPI3REF: Opening A New Database Connection {F12700}
111215 **
111216 ** {F12701} These routines open an SQLite database file whose name
111217 ** is given by the filename argument.
111218 ** {F12702} The filename argument is interpreted as UTF-8
111219 ** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16
111220 ** in the native byte order for [sqlite3_open16()].
111221 ** {F12703} An [sqlite3*] handle is returned in *ppDb, even
111222 ** if an error occurs.  {F12723} (Exception: if SQLite is unable
111223 ** to allocate memory to hold the [sqlite3] object, a NULL will
111224 ** be written into *ppDb instead of a pointer to the [sqlite3] object.)
111225 ** {F12704} If the database is opened (and/or created)
111226 ** successfully, then [SQLITE_OK] is returned.  {F12705} Otherwise an
111227 ** error code is returned.  {F12706} The
111228 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()]  routines can be used to obtain
111229 ** an English language description of the error.
111230 **
111231 ** {F12707} The default encoding for the database will be UTF-8 if
111232 ** [sqlite3_open()] or [sqlite3_open_v2()] is called and
111233 ** UTF-16 in the native byte order if [sqlite3_open16()] is used.
111234 **
111235 ** {F12708} Whether or not an error occurs when it is opened, resources
111236 ** associated with the [sqlite3*] handle should be released by passing it
111237 ** to [sqlite3_close()] when it is no longer required.
111238 **
111239 ** {F12709} The [sqlite3_open_v2()] interface works like [sqlite3_open()] 
111240 ** except that it acccepts two additional parameters for additional control
111241 ** over the new database connection.  {F12710} The flags parameter can be
111242 ** one of:
111243 **
111244 ** <ol>
111245 ** <li>  [SQLITE_OPEN_READONLY]
111246 ** <li>  [SQLITE_OPEN_READWRITE]
111247 ** <li>  [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
111248 ** </ol>
111249 **
111250 ** {F12711} The first value opens the database read-only. 
111251 ** {F12712} If the database does not previously exist, an error is returned.
111252 ** {F12713} The second option opens
111253 ** the database for reading and writing if possible, or reading only if
111254 ** if the file is write protected.  {F12714} In either case the database
111255 ** must already exist or an error is returned.  {F12715} The third option
111256 ** opens the database for reading and writing and creates it if it does
111257 ** not already exist. {F12716}
111258 ** The third options is behavior that is always used for [sqlite3_open()]
111259 ** and [sqlite3_open16()].
111260 **
111261 ** {F12717} If the filename is ":memory:", then an private
111262 ** in-memory database is created for the connection. {F12718} This in-memory
111263 ** database will vanish when the database connection is closed. {END}  Future
111264 ** version of SQLite might make use of additional special filenames
111265 ** that begin with the ":" character.  It is recommended that 
111266 ** when a database filename really does begin with
111267 ** ":" that you prefix the filename with a pathname like "./" to
111268 ** avoid ambiguity.
111269 **
111270 ** {F12719} If the filename is an empty string, then a private temporary
111271 ** on-disk database will be created.  {F12720} This private database will be
111272 ** automatically deleted as soon as the database connection is closed.
111273 **
111274 ** {F12721} The fourth parameter to sqlite3_open_v2() is the name of the
111275 ** [sqlite3_vfs] object that defines the operating system 
111276 ** interface that the new database connection should use.  {F12722} If the
111277 ** fourth parameter is a NULL pointer then the default [sqlite3_vfs]
111278 ** object is used. {END}
111279 **
111280 ** <b>Note to windows users:</b>  The encoding used for the filename argument
111281 ** of [sqlite3_open()] and [sqlite3_open_v2()] must be UTF-8, not whatever
111282 ** codepage is currently defined.  Filenames containing international
111283 ** characters must be converted to UTF-8 prior to passing them into
111284 ** [sqlite3_open()] or [sqlite3_open_v2()].
111285 */
111286 int sqlite3_open(
111287   const char *filename,   /* Database filename (UTF-8) */
111288   sqlite3 **ppDb          /* OUT: SQLite db handle */
111289 );
111290 int sqlite3_open16(
111291   const void *filename,   /* Database filename (UTF-16) */
111292   sqlite3 **ppDb          /* OUT: SQLite db handle */
111293 );
111294 int sqlite3_open_v2(
111295   const char *filename,   /* Database filename (UTF-8) */
111296   sqlite3 **ppDb,         /* OUT: SQLite db handle */
111297   int flags,              /* Flags */
111298   const char *zVfs        /* Name of VFS module to use */
111299 );
111300
111301 /*
111302 ** CAPI3REF: Error Codes And Messages {F12800}
111303 **
111304 ** {F12801} The sqlite3_errcode() interface returns the numeric
111305 ** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code]
111306 ** for the most recent failed sqlite3_* API call associated
111307 ** with [sqlite3] handle 'db'. {U12802} If a prior API call failed but the
111308 ** most recent API call succeeded, the return value from sqlite3_errcode()
111309 ** is undefined. {END}
111310 **
111311 ** {F12803} The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
111312 ** text that describes the error, as either UTF8 or UTF16 respectively.
111313 ** {F12804} Memory to hold the error message string is managed internally.
111314 ** {U12805} The 
111315 ** string may be overwritten or deallocated by subsequent calls to SQLite
111316 ** interface functions. {END}
111317 **
111318 ** {F12806} Calls to many sqlite3_* functions set the error code and
111319 ** string returned by [sqlite3_errcode()], [sqlite3_errmsg()], and
111320 ** [sqlite3_errmsg16()] overwriting the previous values.  {F12807}
111321 ** Except, calls to [sqlite3_errcode()],
111322 ** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the
111323 ** results of future invocations.  {F12808} Calls to API routines that
111324 ** do not return an error code (example: [sqlite3_data_count()]) do not
111325 ** change the error code returned by this routine.  {F12809} Interfaces that
111326 ** are not associated with a specific database connection (examples:
111327 ** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change
111328 ** the return code. {END}
111329 **
111330 ** {F12810} Assuming no other intervening sqlite3_* API calls are made,
111331 ** the error code returned by this function is associated with the same
111332 ** error as the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()].
111333 */
111334 int sqlite3_errcode(sqlite3 *db);
111335 const char *sqlite3_errmsg(sqlite3*);
111336 const void *sqlite3_errmsg16(sqlite3*);
111337
111338 /*
111339 ** CAPI3REF: SQL Statement Object {F13000}
111340 **
111341 ** An instance of this object represent single SQL statements.  This
111342 ** object is variously known as a "prepared statement" or a 
111343 ** "compiled SQL statement" or simply as a "statement".
111344 ** 
111345 ** The life of a statement object goes something like this:
111346 **
111347 ** <ol>
111348 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
111349 **      function.
111350 ** <li> Bind values to host parameters using
111351 **      [sqlite3_bind_blob | sqlite3_bind_* interfaces].
111352 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
111353 ** <li> Reset the statement using [sqlite3_reset()] then go back
111354 **      to step 2.  Do this zero or more times.
111355 ** <li> Destroy the object using [sqlite3_finalize()].
111356 ** </ol>
111357 **
111358 ** Refer to documentation on individual methods above for additional
111359 ** information.
111360 */
111361 typedef struct sqlite3_stmt sqlite3_stmt;
111362
111363 /*
111364 ** CAPI3REF: Compiling An SQL Statement {F13010}
111365 **
111366 ** To execute an SQL query, it must first be compiled into a byte-code
111367 ** program using one of these routines. 
111368 **
111369 ** {F13011} The first argument "db" is an [sqlite3 | SQLite database handle] 
111370 ** obtained from a prior call to [sqlite3_open()], [sqlite3_open_v2()]
111371 ** or [sqlite3_open16()]. {F13012}
111372 ** The second argument "zSql" is the statement to be compiled, encoded
111373 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
111374 ** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2()
111375 ** use UTF-16. {END}
111376 **
111377 ** {F13013} If the nByte argument is less
111378 ** than zero, then zSql is read up to the first zero terminator.
111379 ** {F13014} If nByte is non-negative, then it is the maximum number of 
111380 ** bytes read from zSql.  When nByte is non-negative, the
111381 ** zSql string ends at either the first '\000' or '\u0000' character or 
111382 ** until the nByte-th byte, whichever comes first. {END}
111383 **
111384 ** {F13015} *pzTail is made to point to the first byte past the end of the
111385 ** first SQL statement in zSql.  These routines only compiles the first
111386 ** statement in zSql, so *pzTail is left pointing to what remains
111387 ** uncompiled. {END}
111388 **
111389 ** {F13016} *ppStmt is left pointing to a compiled 
111390 ** [sqlite3_stmt | SQL statement structure] that can be
111391 ** executed using [sqlite3_step()].  Or if there is an error, *ppStmt may be
111392 ** set to NULL.  {F13017} If the input text contains no SQL (if the input
111393 ** is and empty string or a comment) then *ppStmt is set to NULL.
111394 ** {U13018} The calling procedure is responsible for deleting the
111395 ** compiled SQL statement
111396 ** using [sqlite3_finalize()] after it has finished with it.
111397 **
111398 ** {F13019} On success, [SQLITE_OK] is returned.  Otherwise an 
111399 ** [SQLITE_ERROR | error code] is returned. {END}
111400 **
111401 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
111402 ** recommended for all new programs. The two older interfaces are retained
111403 ** for backwards compatibility, but their use is discouraged.
111404 ** {F13020} In the "v2" interfaces, the prepared statement
111405 ** that is returned (the [sqlite3_stmt] object) contains a copy of the 
111406 ** original SQL text. {END} This causes the [sqlite3_step()] interface to
111407 ** behave a differently in two ways:
111408 **
111409 ** <ol>
111410 ** <li>{F13022}
111411 ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
111412 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
111413 ** statement and try to run it again. {F12023} If the schema has changed in
111414 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
111415 ** return [SQLITE_SCHEMA].  {END} But unlike the legacy behavior, 
111416 ** [SQLITE_SCHEMA] is now a fatal error.  {F12024} Calling
111417 ** [sqlite3_prepare_v2()] again will not make the
111418 ** error go away.  {F12025} Note: use [sqlite3_errmsg()] to find the text
111419 ** of the parsing error that results in an [SQLITE_SCHEMA] return. {END}
111420 ** </li>
111421 **
111422 ** <li>
111423 ** {F13030} When an error occurs, 
111424 ** [sqlite3_step()] will return one of the detailed 
111425 ** [SQLITE_ERROR | result codes] or
111426 ** [SQLITE_IOERR_READ | extended result codes].  {F13031}
111427 ** The legacy behavior was that [sqlite3_step()] would only return a generic
111428 ** [SQLITE_ERROR] result code and you would have to make a second call to
111429 ** [sqlite3_reset()] in order to find the underlying cause of the problem.
111430 ** {F13032}
111431 ** With the "v2" prepare interfaces, the underlying reason for the error is
111432 ** returned immediately. {END}
111433 ** </li>
111434 ** </ol>
111435 */
111436 int sqlite3_prepare(
111437   sqlite3 *db,            /* Database handle */
111438   const char *zSql,       /* SQL statement, UTF-8 encoded */
111439   int nByte,              /* Maximum length of zSql in bytes. */
111440   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
111441   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
111442 );
111443 int sqlite3_prepare_v2(
111444   sqlite3 *db,            /* Database handle */
111445   const char *zSql,       /* SQL statement, UTF-8 encoded */
111446   int nByte,              /* Maximum length of zSql in bytes. */
111447   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
111448   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
111449 );
111450 int sqlite3_prepare16(
111451   sqlite3 *db,            /* Database handle */
111452   const void *zSql,       /* SQL statement, UTF-16 encoded */
111453   int nByte,              /* Maximum length of zSql in bytes. */
111454   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
111455   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
111456 );
111457 int sqlite3_prepare16_v2(
111458   sqlite3 *db,            /* Database handle */
111459   const void *zSql,       /* SQL statement, UTF-16 encoded */
111460   int nByte,              /* Maximum length of zSql in bytes. */
111461   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
111462   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
111463 );
111464
111465 /*
111466 ** CAPIREF: Retrieving Statement SQL {F13100}
111467 **
111468 ** {F13101} If the compiled SQL statement passed as an argument was
111469 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()],
111470 ** then this function returns a pointer to a zero-terminated string
111471 ** containing a copy of the original SQL statement. {F13102} The
111472 ** pointer is valid until the statement
111473 ** is deleted using sqlite3_finalize().
111474 ** {F13103} The string returned by sqlite3_sql() is always UTF8 even
111475 ** if a UTF16 string was originally entered using [sqlite3_prepare16_v2()]
111476 ** or the equivalent.
111477 **
111478 ** {F13104} If the statement was compiled using either of the legacy
111479 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this
111480 ** function returns NULL.
111481 */
111482 const char *sqlite3_sql(sqlite3_stmt *pStmt);
111483
111484 /*
111485 ** CAPI3REF:  Dynamically Typed Value Object  {F15000}
111486 **
111487 ** {F15001} SQLite uses the sqlite3_value object to represent all values
111488 ** that are or can be stored in a database table. {END}
111489 ** SQLite uses dynamic typing for the values it stores.  
111490 ** {F15002} Values stored in sqlite3_value objects can be
111491 ** be integers, floating point values, strings, BLOBs, or NULL.
111492 */
111493 typedef struct Mem sqlite3_value;
111494
111495 /*
111496 ** CAPI3REF:  SQL Function Context Object {F16001}
111497 **
111498 ** The context in which an SQL function executes is stored in an
111499 ** sqlite3_context object.  {F16002} A pointer to an sqlite3_context
111500 ** object is always first parameter to application-defined SQL functions.
111501 */
111502 typedef struct sqlite3_context sqlite3_context;
111503
111504 /*
111505 ** CAPI3REF:  Binding Values To Prepared Statements {F13500}
111506 **
111507 ** {F13501} In the SQL strings input to [sqlite3_prepare_v2()] and its
111508 ** variants, literals may be replace by a parameter in one
111509 ** of these forms:
111510 **
111511 ** <ul>
111512 ** <li>  ?
111513 ** <li>  ?NNN
111514 ** <li>  :AAA
111515 ** <li>  @AAA
111516 ** <li>  $VVV
111517 ** </ul>
111518 **
111519 ** In the parameter forms shown above NNN is an integer literal,
111520 ** AAA is an alphanumeric identifier and VVV is a variable name according
111521 ** to the syntax rules of the TCL programming language. {END}
111522 ** The values of these parameters (also called "host parameter names")
111523 ** can be set using the sqlite3_bind_*() routines defined here.
111524 **
111525 ** {F13502} The first argument to the sqlite3_bind_*() routines always
111526 ** is a pointer to the [sqlite3_stmt] object returned from
111527 ** [sqlite3_prepare_v2()] or its variants.  {F13503} The second
111528 ** argument is the index of the parameter to be set.  {F13504} The
111529 ** first parameter has an index of 1.  {F13505} When the same named
111530 ** parameter is used more than once, second and subsequent
111531 ** occurrences have the same index as the first occurrence. 
111532 ** {F13506} The index for named parameters can be looked up using the
111533 ** [sqlite3_bind_parameter_name()] API if desired.  {F13507} The index
111534 ** for "?NNN" parameters is the value of NNN.
111535 ** {F13508} The NNN value must be between 1 and the compile-time
111536 ** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). {END}
111537 ** See <a href="limits.html">limits.html</a> for additional information.
111538 **
111539 ** {F13509} The third argument is the value to bind to the parameter. {END}
111540 **
111541 ** {F13510} In those
111542 ** routines that have a fourth argument, its value is the number of bytes
111543 ** in the parameter.  To be clear: the value is the number of bytes in the
111544 ** string, not the number of characters. {F13511}  The number
111545 ** of bytes does not include the zero-terminator at the end of strings.
111546 ** {F13512}
111547 ** If the fourth parameter is negative, the length of the string is
111548 ** number of bytes up to the first zero terminator. {END}
111549 **
111550 ** {F13513}
111551 ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
111552 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
111553 ** text after SQLite has finished with it. {F13514} If the fifth argument is
111554 ** the special value [SQLITE_STATIC], then the library assumes that the
111555 ** information is in static, unmanaged space and does not need to be freed.
111556 ** {F13515} If the fifth argument has the value [SQLITE_TRANSIENT], then
111557 ** SQLite makes its own private copy of the data immediately, before
111558 ** the sqlite3_bind_*() routine returns. {END}
111559 **
111560 ** {F13520} The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
111561 ** is filled with zeros.  {F13521} A zeroblob uses a fixed amount of memory
111562 ** (just an integer to hold it size) while it is being processed. {END}
111563 ** Zeroblobs are intended to serve as place-holders for BLOBs whose
111564 ** content is later written using 
111565 ** [sqlite3_blob_open | increment BLOB I/O] routines. {F13522} A negative
111566 ** value for the zeroblob results in a zero-length BLOB. {END}
111567 **
111568 ** {F13530} The sqlite3_bind_*() routines must be called after
111569 ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and
111570 ** before [sqlite3_step()]. {F13531}
111571 ** Bindings are not cleared by the [sqlite3_reset()] routine.
111572 ** {F13532} Unbound parameters are interpreted as NULL. {END}
111573 **
111574 ** {F13540} These routines return [SQLITE_OK] on success or an error code if
111575 ** anything goes wrong.  {F13541} [SQLITE_RANGE] is returned if the parameter
111576 ** index is out of range.  {F13542} [SQLITE_NOMEM] is returned if malloc fails.
111577 ** {F13543} [SQLITE_MISUSE] is returned if these routines are called on a
111578 ** virtual machine that is the wrong state or which has already been finalized.
111579 */
111580 int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
111581 int sqlite3_bind_double(sqlite3_stmt*, int, double);
111582 int sqlite3_bind_int(sqlite3_stmt*, int, int);
111583 int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
111584 int sqlite3_bind_null(sqlite3_stmt*, int);
111585 int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
111586 int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
111587 int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
111588 int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
111589
111590 /*
111591 ** CAPI3REF: Number Of Host Parameters {F13600}
111592 **
111593 ** {F13601} Return the largest host parameter index in the precompiled
111594 ** statement given as the argument. {F13602} When the host parameters
111595 ** are of the forms like ":AAA", "$VVV", "@AAA", or "?",
111596 ** then they are assigned sequential increasing numbers beginning
111597 ** with one, so the value returned is the number of parameters.
111598 ** {F13603} However
111599 ** if the same host parameter name is used multiple times, each occurrance
111600 ** is given the same number, so the value returned in that case is the number
111601 ** of unique host parameter names. {F13604} If host parameters of the
111602 ** form "?NNN" are used (where NNN is an integer) then there might be
111603 ** gaps in the numbering and the value returned by this interface is
111604 ** the index of the host parameter with the largest index value. {END}
111605 **
111606 ** {U13605} The prepared statement must not be [sqlite3_finalize | finalized]
111607 ** prior to this routine returning.  Otherwise the results are undefined
111608 ** and probably undesirable.
111609 */
111610 int sqlite3_bind_parameter_count(sqlite3_stmt*);
111611
111612 /*
111613 ** CAPI3REF: Name Of A Host Parameter {F13620}
111614 **
111615 ** {F13621} This routine returns a pointer to the name of the n-th
111616 ** parameter in a [sqlite3_stmt | prepared statement]. {F13622}
111617 ** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name
111618 ** which is the string ":AAA" or "@AAA" or "$VVV". 
111619 ** In other words, the initial ":" or "$" or "@"
111620 ** is included as part of the name.  {F13626}
111621 ** Parameters of the form "?" or "?NNN" have no name.
111622 **
111623 ** {F13623} The first host parameter has an index of 1, not 0.
111624 **
111625 ** {F13624} If the value n is out of range or if the n-th parameter is
111626 ** nameless, then NULL is returned.  {F13625} The returned string is
111627 ** always in the UTF-8 encoding even if the named parameter was
111628 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
111629 ** [sqlite3_prepare16_v2()].
111630 */
111631 const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
111632
111633 /*
111634 ** CAPI3REF: Index Of A Parameter With A Given Name {F13640}
111635 **
111636 ** {F13641} This routine returns the index of a host parameter with the
111637 ** given name.  {F13642} The name must match exactly.  {F13643}
111638 ** If no parameter with the given name is found, return 0.
111639 ** {F13644} Parameter names must be UTF8.
111640 */
111641 int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
111642
111643 /*
111644 ** CAPI3REF: Reset All Bindings On A Prepared Statement {F13660}
111645 **
111646 ** {F13661} Contrary to the intuition of many, [sqlite3_reset()] does not
111647 ** reset the [sqlite3_bind_blob | bindings] on a 
111648 ** [sqlite3_stmt | prepared statement]. {F13662} Use this routine to
111649 ** reset all host parameters to NULL.
111650 */
111651 int sqlite3_clear_bindings(sqlite3_stmt*);
111652
111653 /*
111654 ** CAPI3REF: Number Of Columns In A Result Set {F13710}
111655 **
111656 ** {F13711} Return the number of columns in the result set returned by the 
111657 ** [sqlite3_stmt | compiled SQL statement]. {F13712} This routine returns 0
111658 ** if pStmt is an SQL statement that does not return data (for 
111659 ** example an UPDATE).
111660 */
111661 int sqlite3_column_count(sqlite3_stmt *pStmt);
111662
111663 /*
111664 ** CAPI3REF: Column Names In A Result Set {F13720}
111665 **
111666 ** {F13721} These routines return the name assigned to a particular column
111667 ** in the result set of a SELECT statement.  {F13722} The sqlite3_column_name()
111668 ** interface returns a pointer to a zero-terminated UTF8 string
111669 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
111670 ** UTF16 string. {F13723}  The first parameter is the
111671 ** [sqlite3_stmt | prepared statement] that implements the SELECT statement.
111672 ** The second parameter is the column number.  The left-most column is
111673 ** number 0.
111674 **
111675 ** {F13724} The returned string pointer is valid until either the 
111676 ** [sqlite3_stmt | prepared statement] is destroyed by [sqlite3_finalize()]
111677 ** or until the next call sqlite3_column_name() or sqlite3_column_name16()
111678 ** on the same column.
111679 **
111680 ** {F13725} If sqlite3_malloc() fails during the processing of either routine
111681 ** (for example during a conversion from UTF-8 to UTF-16) then a
111682 ** NULL pointer is returned.
111683 */
111684 const char *sqlite3_column_name(sqlite3_stmt*, int N);
111685 const void *sqlite3_column_name16(sqlite3_stmt*, int N);
111686
111687 /*
111688 ** CAPI3REF: Source Of Data In A Query Result {F13740}
111689 **
111690 ** {F13741} These routines provide a means to determine what column of what
111691 ** table in which database a result of a SELECT statement comes from.
111692 ** {F13742} The name of the database or table or column can be returned as
111693 ** either a UTF8 or UTF16 string.  {F13743} The _database_ routines return
111694 ** the database name, the _table_ routines return the table name, and
111695 ** the origin_ routines return the column name. {F13744}
111696 ** The returned string is valid until
111697 ** the [sqlite3_stmt | prepared statement] is destroyed using
111698 ** [sqlite3_finalize()] or until the same information is requested
111699 ** again in a different encoding.
111700 **
111701 ** {F13745} The names returned are the original un-aliased names of the
111702 ** database, table, and column.
111703 **
111704 ** {F13746} The first argument to the following calls is a 
111705 ** [sqlite3_stmt | compiled SQL statement].
111706 ** {F13747} These functions return information about the Nth column returned by 
111707 ** the statement, where N is the second function argument.
111708 **
111709 ** {F13748} If the Nth column returned by the statement is an expression
111710 ** or subquery and is not a column value, then all of these functions
111711 ** return NULL.  {F13749} Otherwise, they return the 
111712 ** name of the attached database, table and column that query result
111713 ** column was extracted from.
111714 **
111715 ** {F13750} As with all other SQLite APIs, those postfixed with "16" return
111716 ** UTF-16 encoded strings, the other functions return UTF-8. {END}
111717 **
111718 ** These APIs are only available if the library was compiled with the 
111719 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
111720 **
111721 ** {U13751}
111722 ** If two or more threads call one or more of these routines against the same
111723 ** prepared statement and column at the same time then the results are
111724 ** undefined.
111725 */
111726 const char *sqlite3_column_database_name(sqlite3_stmt*,int);
111727 const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
111728 const char *sqlite3_column_table_name(sqlite3_stmt*,int);
111729 const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
111730 const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
111731 const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
111732
111733 /*
111734 ** CAPI3REF: Declared Datatype Of A Query Result {F13760}
111735 **
111736 ** The first parameter is a [sqlite3_stmt | compiled SQL statement]. 
111737 ** {F13761} If this statement is a SELECT statement and the Nth column of the 
111738 ** returned result set of that SELECT is a table column (not an
111739 ** expression or subquery) then the declared type of the table
111740 ** column is returned.  {F13762} If the Nth column of the result set is an
111741 ** expression or subquery, then a NULL pointer is returned.
111742 ** {F13763} The returned string is always UTF-8 encoded.  {END} 
111743 ** For example, in the database schema:
111744 **
111745 ** CREATE TABLE t1(c1 VARIANT);
111746 **
111747 ** And the following statement compiled:
111748 **
111749 ** SELECT c1 + 1, c1 FROM t1;
111750 **
111751 ** Then this routine would return the string "VARIANT" for the second
111752 ** result column (i==1), and a NULL pointer for the first result column
111753 ** (i==0).
111754 **
111755 ** SQLite uses dynamic run-time typing.  So just because a column
111756 ** is declared to contain a particular type does not mean that the
111757 ** data stored in that column is of the declared type.  SQLite is
111758 ** strongly typed, but the typing is dynamic not static.  Type
111759 ** is associated with individual values, not with the containers
111760 ** used to hold those values.
111761 */
111762 const char *sqlite3_column_decltype(sqlite3_stmt *, int i);
111763 const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
111764
111765 /* 
111766 ** CAPI3REF:  Evaluate An SQL Statement {F13200}
111767 **
111768 ** After an [sqlite3_stmt | SQL statement] has been prepared with a call
111769 ** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of
111770 ** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()],
111771 ** then this function must be called one or more times to evaluate the 
111772 ** statement.
111773 **
111774 ** The details of the behavior of this sqlite3_step() interface depend
111775 ** on whether the statement was prepared using the newer "v2" interface
111776 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
111777 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
111778 ** new "v2" interface is recommended for new applications but the legacy
111779 ** interface will continue to be supported.
111780 **
111781 ** In the lagacy interface, the return value will be either [SQLITE_BUSY], 
111782 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
111783 ** With the "v2" interface, any of the other [SQLITE_OK | result code]
111784 ** or [SQLITE_IOERR_READ | extended result code] might be returned as
111785 ** well.
111786 **
111787 ** [SQLITE_BUSY] means that the database engine was unable to acquire the
111788 ** database locks it needs to do its job.  If the statement is a COMMIT
111789 ** or occurs outside of an explicit transaction, then you can retry the
111790 ** statement.  If the statement is not a COMMIT and occurs within a
111791 ** explicit transaction then you should rollback the transaction before
111792 ** continuing.
111793 **
111794 ** [SQLITE_DONE] means that the statement has finished executing
111795 ** successfully.  sqlite3_step() should not be called again on this virtual
111796 ** machine without first calling [sqlite3_reset()] to reset the virtual
111797 ** machine back to its initial state.
111798 **
111799 ** If the SQL statement being executed returns any data, then 
111800 ** [SQLITE_ROW] is returned each time a new row of data is ready
111801 ** for processing by the caller. The values may be accessed using
111802 ** the [sqlite3_column_int | column access functions].
111803 ** sqlite3_step() is called again to retrieve the next row of data.
111804 ** 
111805 ** [SQLITE_ERROR] means that a run-time error (such as a constraint
111806 ** violation) has occurred.  sqlite3_step() should not be called again on
111807 ** the VM. More information may be found by calling [sqlite3_errmsg()].
111808 ** With the legacy interface, a more specific error code (example:
111809 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
111810 ** can be obtained by calling [sqlite3_reset()] on the
111811 ** [sqlite3_stmt | prepared statement].  In the "v2" interface,
111812 ** the more specific error code is returned directly by sqlite3_step().
111813 **
111814 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
111815 ** Perhaps it was called on a [sqlite3_stmt | prepared statement] that has
111816 ** already been [sqlite3_finalize | finalized] or on one that had 
111817 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
111818 ** be the case that the same database connection is being used by two or
111819 ** more threads at the same moment in time.
111820 **
111821 ** <b>Goofy Interface Alert:</b>
111822 ** In the legacy interface, 
111823 ** the sqlite3_step() API always returns a generic error code,
111824 ** [SQLITE_ERROR], following any error other than [SQLITE_BUSY]
111825 ** and [SQLITE_MISUSE].  You must call [sqlite3_reset()] or
111826 ** [sqlite3_finalize()] in order to find one of the specific
111827 ** [SQLITE_ERROR | result codes] that better describes the error.
111828 ** We admit that this is a goofy design.  The problem has been fixed
111829 ** with the "v2" interface.  If you prepare all of your SQL statements
111830 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
111831 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the 
111832 ** more specific [SQLITE_ERROR | result codes] are returned directly
111833 ** by sqlite3_step().  The use of the "v2" interface is recommended.
111834 */
111835 int sqlite3_step(sqlite3_stmt*);
111836
111837 /*
111838 ** CAPI3REF: Number of columns in a result set {F13770}
111839 **
111840 ** Return the number of values in the current row of the result set.
111841 **
111842 ** {F13771} After a call to [sqlite3_step()] that returns [SQLITE_ROW],
111843 ** this routine
111844 ** will return the same value as the [sqlite3_column_count()] function.
111845 ** {F13772}
111846 ** After [sqlite3_step()] has returned an [SQLITE_DONE], [SQLITE_BUSY], or
111847 ** a [SQLITE_ERROR | error code], or before [sqlite3_step()] has been 
111848 ** called on the [sqlite3_stmt | prepared statement] for the first time,
111849 ** this routine returns zero.
111850 */
111851 int sqlite3_data_count(sqlite3_stmt *pStmt);
111852
111853 /*
111854 ** CAPI3REF: Fundamental Datatypes {F10265}
111855 **
111856 ** {F10266}Every value in SQLite has one of five fundamental datatypes:
111857 **
111858 ** <ul>
111859 ** <li> 64-bit signed integer
111860 ** <li> 64-bit IEEE floating point number
111861 ** <li> string
111862 ** <li> BLOB
111863 ** <li> NULL
111864 ** </ul> {END}
111865 **
111866 ** These constants are codes for each of those types.
111867 **
111868 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
111869 ** for a completely different meaning.  Software that links against both
111870 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not
111871 ** SQLITE_TEXT.
111872 */
111873 #define SQLITE_INTEGER  1
111874 #define SQLITE_FLOAT    2
111875 #define SQLITE_BLOB     4
111876 #define SQLITE_NULL     5
111877 #ifdef SQLITE_TEXT
111878 # undef SQLITE_TEXT
111879 #else
111880 # define SQLITE_TEXT     3
111881 #endif
111882 #define SQLITE3_TEXT     3
111883
111884 /*
111885 ** CAPI3REF: Results Values From A Query {F13800}
111886 **
111887 ** These routines return information about
111888 ** a single column of the current result row of a query.  In every
111889 ** case the first argument is a pointer to the 
111890 ** [sqlite3_stmt | SQL statement] that is being
111891 ** evaluated (the [sqlite3_stmt*] that was returned from 
111892 ** [sqlite3_prepare_v2()] or one of its variants) and
111893 ** the second argument is the index of the column for which information 
111894 ** should be returned.  The left-most column of the result set
111895 ** has an index of 0.
111896 **
111897 ** If the SQL statement is not currently point to a valid row, or if the
111898 ** the column index is out of range, the result is undefined. 
111899 ** These routines may only be called when the most recent call to
111900 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
111901 ** [sqlite3_reset()] nor [sqlite3_finalize()] has been call subsequently.
111902 ** If any of these routines are called after [sqlite3_reset()] or
111903 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
111904 ** something other than [SQLITE_ROW], the results are undefined.
111905 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
111906 ** are called from a different thread while any of these routines
111907 ** are pending, then the results are undefined.  
111908 **
111909 ** The sqlite3_column_type() routine returns 
111910 ** [SQLITE_INTEGER | datatype code] for the initial data type
111911 ** of the result column.  The returned value is one of [SQLITE_INTEGER],
111912 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
111913 ** returned by sqlite3_column_type() is only meaningful if no type
111914 ** conversions have occurred as described below.  After a type conversion,
111915 ** the value returned by sqlite3_column_type() is undefined.  Future
111916 ** versions of SQLite may change the behavior of sqlite3_column_type()
111917 ** following a type conversion.
111918 **
111919 ** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() 
111920 ** routine returns the number of bytes in that BLOB or string.
111921 ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
111922 ** the string to UTF-8 and then returns the number of bytes.
111923 ** If the result is a numeric value then sqlite3_column_bytes() uses
111924 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
111925 ** the number of bytes in that string.
111926 ** The value returned does not include the zero terminator at the end
111927 ** of the string.  For clarity: the value returned is the number of
111928 ** bytes in the string, not the number of characters.
111929 **
111930 ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
111931 ** even zero-length strings, are always zero terminated.  The return
111932 ** value from sqlite3_column_blob() for a zero-length blob is an arbitrary
111933 ** pointer, possibly even a NULL pointer.
111934 **
111935 ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
111936 ** but leaves the result in UTF-16 instead of UTF-8.  
111937 ** The zero terminator is not included in this count.
111938 **
111939 ** These routines attempt to convert the value where appropriate.  For
111940 ** example, if the internal representation is FLOAT and a text result
111941 ** is requested, [sqlite3_snprintf()] is used internally to do the conversion
111942 ** automatically.  The following table details the conversions that
111943 ** are applied:
111944 **
111945 ** <blockquote>
111946 ** <table border="1">
111947 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
111948 **
111949 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
111950 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
111951 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
111952 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
111953 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
111954 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
111955 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as for INTEGER->TEXT
111956 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
111957 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
111958 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
111959 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
111960 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
111961 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
111962 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
111963 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
111964 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
111965 ** </table>
111966 ** </blockquote>
111967 **
111968 ** The table above makes reference to standard C library functions atoi()
111969 ** and atof().  SQLite does not really use these functions.  It has its
111970 ** on equavalent internal routines.  The atoi() and atof() names are
111971 ** used in the table for brevity and because they are familiar to most
111972 ** C programmers.
111973 **
111974 ** Note that when type conversions occur, pointers returned by prior
111975 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
111976 ** sqlite3_column_text16() may be invalidated. 
111977 ** Type conversions and pointer invalidations might occur
111978 ** in the following cases:
111979 **
111980 ** <ul>
111981 ** <li><p>  The initial content is a BLOB and sqlite3_column_text() 
111982 **          or sqlite3_column_text16() is called.  A zero-terminator might
111983 **          need to be added to the string.</p></li>
111984 **
111985 ** <li><p>  The initial content is UTF-8 text and sqlite3_column_bytes16() or
111986 **          sqlite3_column_text16() is called.  The content must be converted
111987 **          to UTF-16.</p></li>
111988 **
111989 ** <li><p>  The initial content is UTF-16 text and sqlite3_column_bytes() or
111990 **          sqlite3_column_text() is called.  The content must be converted
111991 **          to UTF-8.</p></li>
111992 ** </ul>
111993 **
111994 ** Conversions between UTF-16be and UTF-16le are always done in place and do
111995 ** not invalidate a prior pointer, though of course the content of the buffer
111996 ** that the prior pointer points to will have been modified.  Other kinds
111997 ** of conversion are done in place when it is possible, but sometime it is
111998 ** not possible and in those cases prior pointers are invalidated.  
111999 **
112000 ** The safest and easiest to remember policy is to invoke these routines
112001 ** in one of the following ways:
112002 **
112003 **  <ul>
112004 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
112005 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
112006 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
112007 **  </ul>
112008 **
112009 ** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(),
112010 ** or sqlite3_column_text16() first to force the result into the desired
112011 ** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to
112012 ** find the size of the result.  Do not mix call to sqlite3_column_text() or
112013 ** sqlite3_column_blob() with calls to sqlite3_column_bytes16().  And do not
112014 ** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes().
112015 **
112016 ** The pointers returned are valid until a type conversion occurs as
112017 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
112018 ** [sqlite3_finalize()] is called.  The memory space used to hold strings
112019 ** and blobs is freed automatically.  Do <b>not</b> pass the pointers returned
112020 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into 
112021 ** [sqlite3_free()].
112022 **
112023 ** If a memory allocation error occurs during the evaluation of any
112024 ** of these routines, a default value is returned.  The default value
112025 ** is either the integer 0, the floating point number 0.0, or a NULL
112026 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
112027 ** [SQLITE_NOMEM].
112028 */
112029 const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
112030 int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
112031 int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
112032 double sqlite3_column_double(sqlite3_stmt*, int iCol);
112033 int sqlite3_column_int(sqlite3_stmt*, int iCol);
112034 sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
112035 const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
112036 const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
112037 int sqlite3_column_type(sqlite3_stmt*, int iCol);
112038 sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
112039
112040 /*
112041 ** CAPI3REF: Destroy A Prepared Statement Object {F13300}
112042 **
112043 ** The sqlite3_finalize() function is called to delete a 
112044 ** [sqlite3_stmt | compiled SQL statement]. If the statement was
112045 ** executed successfully, or not executed at all, then SQLITE_OK is returned.
112046 ** If execution of the statement failed then an 
112047 ** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code]
112048 ** is returned. 
112049 **
112050 ** This routine can be called at any point during the execution of the
112051 ** [sqlite3_stmt | virtual machine].  If the virtual machine has not 
112052 ** completed execution when this routine is called, that is like
112053 ** encountering an error or an interrupt.  (See [sqlite3_interrupt()].) 
112054 ** Incomplete updates may be rolled back and transactions cancelled,  
112055 ** depending on the circumstances, and the 
112056 ** [SQLITE_ERROR | result code] returned will be [SQLITE_ABORT].
112057 */
112058 int sqlite3_finalize(sqlite3_stmt *pStmt);
112059
112060 /*
112061 ** CAPI3REF: Reset A Prepared Statement Object {F13330}
112062 **
112063 ** The sqlite3_reset() function is called to reset a 
112064 ** [sqlite3_stmt | compiled SQL statement] object.
112065 ** back to its initial state, ready to be re-executed.
112066 ** Any SQL statement variables that had values bound to them using
112067 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
112068 ** Use [sqlite3_clear_bindings()] to reset the bindings.
112069 */
112070 int sqlite3_reset(sqlite3_stmt *pStmt);
112071
112072 /*
112073 ** CAPI3REF: Create Or Redefine SQL Functions {F16100}
112074 **
112075 ** The following two functions are used to add SQL functions or aggregates
112076 ** or to redefine the behavior of existing SQL functions or aggregates.  The
112077 ** difference only between the two is that the second parameter, the
112078 ** name of the (scalar) function or aggregate, is encoded in UTF-8 for
112079 ** sqlite3_create_function() and UTF-16 for sqlite3_create_function16().
112080 **
112081 ** The first argument is the [sqlite3 | database handle] that holds the
112082 ** SQL function or aggregate is to be added or redefined. If a single
112083 ** program uses more than one database handle internally, then SQL
112084 ** functions or aggregates must be added individually to each database
112085 ** handle with which they will be used.
112086 **
112087 ** The second parameter is the name of the SQL function to be created
112088 ** or redefined.
112089 ** The length of the name is limited to 255 bytes, exclusive of the 
112090 ** zero-terminator.  Note that the name length limit is in bytes, not
112091 ** characters.  Any attempt to create a function with a longer name
112092 ** will result in an SQLITE_ERROR error.
112093 **
112094 ** The third parameter is the number of arguments that the SQL function or
112095 ** aggregate takes. If this parameter is negative, then the SQL function or
112096 ** aggregate may take any number of arguments.
112097 **
112098 ** The fourth parameter, eTextRep, specifies what 
112099 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
112100 ** its parameters.  Any SQL function implementation should be able to work
112101 ** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
112102 ** more efficient with one encoding than another.  It is allowed to
112103 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
112104 ** times with the same function but with different values of eTextRep.
112105 ** When multiple implementations of the same function are available, SQLite
112106 ** will pick the one that involves the least amount of data conversion.
112107 ** If there is only a single implementation which does not care what
112108 ** text encoding is used, then the fourth argument should be
112109 ** [SQLITE_ANY].
112110 **
112111 ** The fifth parameter is an arbitrary pointer.  The implementation
112112 ** of the function can gain access to this pointer using
112113 ** [sqlite3_user_data()].
112114 **
112115 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
112116 ** pointers to C-language functions that implement the SQL
112117 ** function or aggregate. A scalar SQL function requires an implementation of
112118 ** the xFunc callback only, NULL pointers should be passed as the xStep
112119 ** and xFinal parameters. An aggregate SQL function requires an implementation
112120 ** of xStep and xFinal and NULL should be passed for xFunc. To delete an
112121 ** existing SQL function or aggregate, pass NULL for all three function
112122 ** callback.
112123 **
112124 ** It is permitted to register multiple implementations of the same
112125 ** functions with the same name but with either differing numbers of
112126 ** arguments or differing perferred text encodings.  SQLite will use
112127 ** the implementation most closely matches the way in which the
112128 ** SQL function is used.
112129 */
112130 int sqlite3_create_function(
112131   sqlite3 *,
112132   const char *zFunctionName,
112133   int nArg,
112134   int eTextRep,
112135   void*,
112136   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
112137   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
112138   void (*xFinal)(sqlite3_context*)
112139 );
112140 int sqlite3_create_function16(
112141   sqlite3*,
112142   const void *zFunctionName,
112143   int nArg,
112144   int eTextRep,
112145   void*,
112146   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
112147   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
112148   void (*xFinal)(sqlite3_context*)
112149 );
112150
112151 /*
112152 ** CAPI3REF: Text Encodings {F10267}
112153 **
112154 ** These constant define integer codes that represent the various
112155 ** text encodings supported by SQLite.
112156 */
112157 #define SQLITE_UTF8           1
112158 #define SQLITE_UTF16LE        2
112159 #define SQLITE_UTF16BE        3
112160 #define SQLITE_UTF16          4    /* Use native byte order */
112161 #define SQLITE_ANY            5    /* sqlite3_create_function only */
112162 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
112163
112164 /*
112165 ** CAPI3REF: Obsolete Functions
112166 **
112167 ** These functions are all now obsolete.  In order to maintain
112168 ** backwards compatibility with older code, we continue to support
112169 ** these functions.  However, new development projects should avoid
112170 ** the use of these functions.  To help encourage people to avoid
112171 ** using these functions, we are not going to tell you want they do.
112172 */
112173 int sqlite3_aggregate_count(sqlite3_context*);
112174 int sqlite3_expired(sqlite3_stmt*);
112175 int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
112176 int sqlite3_global_recover(void);
112177 void sqlite3_thread_cleanup(void);
112178 int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
112179
112180 /*
112181 ** CAPI3REF: Obtaining SQL Function Parameter Values {F15100}
112182 **
112183 ** The C-language implementation of SQL functions and aggregates uses
112184 ** this set of interface routines to access the parameter values on
112185 ** the function or aggregate.
112186 **
112187 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
112188 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
112189 ** define callbacks that implement the SQL functions and aggregates.
112190 ** The 4th parameter to these callbacks is an array of pointers to
112191 ** [sqlite3_value] objects.  There is one [sqlite3_value] object for
112192 ** each parameter to the SQL function.  These routines are used to
112193 ** extract values from the [sqlite3_value] objects.
112194 **
112195 ** These routines work just like the corresponding 
112196 ** [sqlite3_column_blob | sqlite3_column_* routines] except that 
112197 ** these routines take a single [sqlite3_value*] pointer instead
112198 ** of an [sqlite3_stmt*] pointer and an integer column number.
112199 **
112200 ** The sqlite3_value_text16() interface extracts a UTF16 string
112201 ** in the native byte-order of the host machine.  The
112202 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
112203 ** extract UTF16 strings as big-endian and little-endian respectively.
112204 **
112205 ** The sqlite3_value_numeric_type() interface attempts to apply
112206 ** numeric affinity to the value.  This means that an attempt is
112207 ** made to convert the value to an integer or floating point.  If
112208 ** such a conversion is possible without loss of information (in other
112209 ** words if the value is a string that looks like a number)
112210 ** then the conversion is done.  Otherwise no conversion occurs.  The 
112211 ** [SQLITE_INTEGER | datatype] after conversion is returned.
112212 **
112213 ** Please pay particular attention to the fact that the pointer that
112214 ** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or
112215 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
112216 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
112217 ** or [sqlite3_value_text16()].  
112218 **
112219 ** These routines must be called from the same thread as
112220 ** the SQL function that supplied the sqlite3_value* parameters.
112221 ** Or, if the sqlite3_value* argument comes from the [sqlite3_column_value()]
112222 ** interface, then these routines should be called from the same thread
112223 ** that ran [sqlite3_column_value()].
112224 **
112225 */
112226 const void *sqlite3_value_blob(sqlite3_value*);
112227 int sqlite3_value_bytes(sqlite3_value*);
112228 int sqlite3_value_bytes16(sqlite3_value*);
112229 double sqlite3_value_double(sqlite3_value*);
112230 int sqlite3_value_int(sqlite3_value*);
112231 sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
112232 const unsigned char *sqlite3_value_text(sqlite3_value*);
112233 const void *sqlite3_value_text16(sqlite3_value*);
112234 const void *sqlite3_value_text16le(sqlite3_value*);
112235 const void *sqlite3_value_text16be(sqlite3_value*);
112236 int sqlite3_value_type(sqlite3_value*);
112237 int sqlite3_value_numeric_type(sqlite3_value*);
112238
112239 /*
112240 ** CAPI3REF: Obtain Aggregate Function Context {F16210}
112241 **
112242 ** The implementation of aggregate SQL functions use this routine to allocate
112243 ** a structure for storing their state.  
112244 ** {F16211} The first time the sqlite3_aggregate_context() routine is
112245 ** is called for a particular aggregate, SQLite allocates nBytes of memory
112246 ** zeros that memory, and returns a pointer to it.
112247 ** {F16212} On second and subsequent calls to sqlite3_aggregate_context()
112248 ** for the same aggregate function index, the same buffer is returned. {END}
112249 ** The implementation
112250 ** of the aggregate can use the returned buffer to accumulate data.
112251 **
112252 ** {F16213} SQLite automatically frees the allocated buffer when the aggregate
112253 ** query concludes. {END}
112254 **
112255 ** The first parameter should be a copy of the 
112256 ** [sqlite3_context | SQL function context] that is the first
112257 ** parameter to the callback routine that implements the aggregate
112258 ** function.
112259 **
112260 ** This routine must be called from the same thread in which
112261 ** the aggregate SQL function is running.
112262 */
112263 void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
112264
112265 /*
112266 ** CAPI3REF: User Data For Functions {F16240}
112267 **
112268 ** {F16241} The sqlite3_user_data() interface returns a copy of
112269 ** the pointer that was the pUserData parameter (the 5th parameter)
112270 ** of the the [sqlite3_create_function()]
112271 ** and [sqlite3_create_function16()] routines that originally
112272 ** registered the application defined function. {END}
112273 **
112274 ** {U16243} This routine must be called from the same thread in which
112275 ** the application-defined function is running.
112276 */
112277 void *sqlite3_user_data(sqlite3_context*);
112278
112279 /*
112280 ** CAPI3REF: Function Auxiliary Data {F16270}
112281 **
112282 ** The following two functions may be used by scalar SQL functions to
112283 ** associate meta-data with argument values. If the same value is passed to
112284 ** multiple invocations of the same SQL function during query execution, under
112285 ** some circumstances the associated meta-data may be preserved. This may
112286 ** be used, for example, to add a regular-expression matching scalar
112287 ** function. The compiled version of the regular expression is stored as
112288 ** meta-data associated with the SQL value passed as the regular expression
112289 ** pattern.  The compiled regular expression can be reused on multiple
112290 ** invocations of the same function so that the original pattern string
112291 ** does not need to be recompiled on each invocation.
112292 **
112293 ** {F16271}
112294 ** The sqlite3_get_auxdata() interface returns a pointer to the meta-data
112295 ** associated by the sqlite3_set_auxdata() function with the Nth argument
112296 ** value to the application-defined function.
112297 ** {F16272} If no meta-data has been ever been set for the Nth
112298 ** argument of the function, or if the cooresponding function parameter
112299 ** has changed since the meta-data was set, then sqlite3_get_auxdata()
112300 ** returns a NULL pointer.
112301 **
112302 ** {F16275} The sqlite3_set_auxdata() interface saves the meta-data
112303 ** pointed to by its 3rd parameter as the meta-data for the N-th
112304 ** argument of the application-defined function. {END} Subsequent
112305 ** calls to sqlite3_get_auxdata() might return this data, if it has
112306 ** not been destroyed. 
112307 ** {F16277} If it is not NULL, SQLite will invoke the destructor 
112308 ** function given by the 4th parameter to sqlite3_set_auxdata() on
112309 ** the meta-data when the corresponding function parameter changes
112310 ** or when the SQL statement completes, whichever comes first. {END}
112311 **
112312 ** In practice, meta-data is preserved between function calls for
112313 ** expressions that are constant at compile time. This includes literal
112314 ** values and SQL variables.
112315 **
112316 ** These routines must be called from the same thread in which
112317 ** the SQL function is running.
112318 */
112319 void *sqlite3_get_auxdata(sqlite3_context*, int N);
112320 void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
112321
112322
112323 /*
112324 ** CAPI3REF: Constants Defining Special Destructor Behavior {F10280}
112325 **
112326 ** These are special value for the destructor that is passed in as the
112327 ** final argument to routines like [sqlite3_result_blob()].  If the destructor
112328 ** argument is SQLITE_STATIC, it means that the content pointer is constant
112329 ** and will never change.  It does not need to be destroyed.  The 
112330 ** SQLITE_TRANSIENT value means that the content will likely change in
112331 ** the near future and that SQLite should make its own private copy of
112332 ** the content before returning.
112333 **
112334 ** The typedef is necessary to work around problems in certain
112335 ** C++ compilers.  See ticket #2191.
112336 */
112337 typedef void (*sqlite3_destructor_type)(void*);
112338 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
112339 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
112340
112341 /*
112342 ** CAPI3REF: Setting The Result Of An SQL Function {F16400}
112343 **
112344 ** These routines are used by the xFunc or xFinal callbacks that
112345 ** implement SQL functions and aggregates.  See
112346 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
112347 ** for additional information.
112348 **
112349 ** These functions work very much like the 
112350 ** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used
112351 ** to bind values to host parameters in prepared statements.
112352 ** Refer to the
112353 ** [sqlite3_bind_blob | sqlite3_bind_* documentation] for
112354 ** additional information.
112355 **
112356 ** {F16402} The sqlite3_result_blob() interface sets the result from
112357 ** an application defined function to be the BLOB whose content is pointed
112358 ** to by the second parameter and which is N bytes long where N is the
112359 ** third parameter. 
112360 ** {F16403} The sqlite3_result_zeroblob() inerfaces set the result of
112361 ** the application defined function to be a BLOB containing all zero
112362 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
112363 **
112364 ** {F16407} The sqlite3_result_double() interface sets the result from
112365 ** an application defined function to be a floating point value specified
112366 ** by its 2nd argument.
112367 **
112368 ** {F16409} The sqlite3_result_error() and sqlite3_result_error16() functions
112369 ** cause the implemented SQL function to throw an exception.
112370 ** {F16411} SQLite uses the string pointed to by the
112371 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
112372 ** as the text of an error message. {F16412} SQLite interprets the error
112373 ** message string from sqlite3_result_error() as UTF8.  {F16413} SQLite
112374 ** interprets the string from sqlite3_result_error16() as UTF16 in native
112375 ** byte order.  {F16414} If the third parameter to sqlite3_result_error()
112376 ** or sqlite3_result_error16() is negative then SQLite takes as the error
112377 ** message all text up through the first zero character.
112378 ** {F16415} If the third parameter to sqlite3_result_error() or
112379 ** sqlite3_result_error16() is non-negative then SQLite takes that many
112380 ** bytes (not characters) from the 2nd parameter as the error message.
112381 ** {F16417} The sqlite3_result_error() and sqlite3_result_error16()
112382 ** routines make a copy private copy of the error message text before
112383 ** they return.  {END} Hence, the calling function can deallocate or
112384 ** modify the text after they return without harm.
112385 **
112386 ** {F16421} The sqlite3_result_toobig() interface causes SQLite
112387 ** to throw an error indicating that a string or BLOB is to long
112388 ** to represent.  {F16422} The sqlite3_result_nomem() interface
112389 ** causes SQLite to throw an exception indicating that the a
112390 ** memory allocation failed.
112391 **
112392 ** {F16431} The sqlite3_result_int() interface sets the return value
112393 ** of the application-defined function to be the 32-bit signed integer
112394 ** value given in the 2nd argument.
112395 ** {F16432} The sqlite3_result_int64() interface sets the return value
112396 ** of the application-defined function to be the 64-bit signed integer
112397 ** value given in the 2nd argument.
112398 **
112399 ** {F16437} The sqlite3_result_null() interface sets the return value
112400 ** of the application-defined function to be NULL.
112401 **
112402 ** {F16441} The sqlite3_result_text(), sqlite3_result_text16(), 
112403 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
112404 ** set the return value of the application-defined function to be
112405 ** a text string which is represented as UTF-8, UTF-16 native byte order,
112406 ** UTF-16 little endian, or UTF-16 big endian, respectively.
112407 ** {F16442} SQLite takes the text result from the application from
112408 ** the 2nd parameter of the sqlite3_result_text* interfaces.
112409 ** {F16444} If the 3rd parameter to the sqlite3_result_text* interfaces
112410 ** is negative, then SQLite takes result text from the 2nd parameter 
112411 ** through the first zero character.
112412 ** {F16447} If the 3rd parameter to the sqlite3_result_text* interfaces
112413 ** is non-negative, then as many bytes (not characters) of the text
112414 ** pointed to by the 2nd parameter are taken as the application-defined
112415 ** function result.
112416 ** {F16451} If the 4th parameter to the sqlite3_result_text* interfaces
112417 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
112418 ** function as the destructor on the text or blob result when it has
112419 ** finished using that result.
112420 ** {F16453} If the 4th parameter to the sqlite3_result_text* interfaces
112421 ** or sqlite3_result_blob is the special constant SQLITE_STATIC, then
112422 ** SQLite assumes that the text or blob result is constant space and
112423 ** does not copy the space or call a destructor when it has
112424 ** finished using that result.
112425 ** {F16454} If the 4th parameter to the sqlite3_result_text* interfaces
112426 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
112427 ** then SQLite makes a copy of the result into space obtained from
112428 ** from [sqlite3_malloc()] before it returns.
112429 **
112430 ** {F16461} The sqlite3_result_value() interface sets the result of
112431 ** the application-defined function to be a copy the [sqlite3_value]
112432 ** object specified by the 2nd parameter.  {F16463} The
112433 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
112434 ** so that [sqlite3_value] specified in the parameter may change or
112435 ** be deallocated after sqlite3_result_value() returns without harm.
112436 **
112437 ** {U16491} These routines are called from within the different thread 
112438 ** than the one containing the application-defined function that recieved
112439 ** the [sqlite3_context] pointer, the results are undefined.
112440 */
112441 void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
112442 void sqlite3_result_double(sqlite3_context*, double);
112443 void sqlite3_result_error(sqlite3_context*, const char*, int);
112444 void sqlite3_result_error16(sqlite3_context*, const void*, int);
112445 void sqlite3_result_error_toobig(sqlite3_context*);
112446 void sqlite3_result_error_nomem(sqlite3_context*);
112447 void sqlite3_result_int(sqlite3_context*, int);
112448 void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
112449 void sqlite3_result_null(sqlite3_context*);
112450 void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
112451 void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
112452 void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
112453 void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
112454 void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
112455 void sqlite3_result_zeroblob(sqlite3_context*, int n);
112456
112457 /*
112458 ** CAPI3REF: Define New Collating Sequences {F16600}
112459 **
112460 ** {F16601}
112461 ** These functions are used to add new collation sequences to the
112462 ** [sqlite3*] handle specified as the first argument. 
112463 **
112464 ** {F16602}
112465 ** The name of the new collation sequence is specified as a UTF-8 string
112466 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
112467 ** and a UTF-16 string for sqlite3_create_collation16(). {F16603} In all cases
112468 ** the name is passed as the second function argument.
112469 **
112470 ** {F16604}
112471 ** The third argument may be one of the constants [SQLITE_UTF8],
112472 ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
112473 ** routine expects to be passed pointers to strings encoded using UTF-8,
112474 ** UTF-16 little-endian or UTF-16 big-endian respectively. {F16605} The
112475 ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that
112476 ** the routine expects pointers to 16-bit word aligned strings
112477 ** of UTF16 in the native byte order of the host computer.
112478 **
112479 ** {F16607}
112480 ** A pointer to the user supplied routine must be passed as the fifth
112481 ** argument. {F16609} If it is NULL, this is the same as deleting the collation
112482 ** sequence (so that SQLite cannot call it anymore).
112483 ** {F16611} Each time the application
112484 ** supplied function is invoked, it is passed a copy of the void* passed as
112485 ** the fourth argument to sqlite3_create_collation() or
112486 ** sqlite3_create_collation16() as its first parameter.
112487 **
112488 ** {F16612}
112489 ** The remaining arguments to the application-supplied routine are two strings,
112490 ** each represented by a [length, data] pair and encoded in the encoding
112491 ** that was passed as the third argument when the collation sequence was
112492 ** registered. {END} The application defined collation routine should
112493 ** return negative, zero or positive if
112494 ** the first string is less than, equal to, or greater than the second
112495 ** string. i.e. (STRING1 - STRING2).
112496 **
112497 ** {F16615}
112498 ** The sqlite3_create_collation_v2() works like sqlite3_create_collation()
112499 ** excapt that it takes an extra argument which is a destructor for
112500 ** the collation.  {F16617} The destructor is called when the collation is
112501 ** destroyed and is passed a copy of the fourth parameter void* pointer
112502 ** of the sqlite3_create_collation_v2().
112503 ** {F16618}  Collations are destroyed when
112504 ** they are overridden by later calls to the collation creation functions
112505 ** or when the [sqlite3*] database handle is closed using [sqlite3_close()].
112506 */
112507 int sqlite3_create_collation(
112508   sqlite3*, 
112509   const char *zName, 
112510   int eTextRep, 
112511   void*,
112512   int(*xCompare)(void*,int,const void*,int,const void*)
112513 );
112514 int sqlite3_create_collation_v2(
112515   sqlite3*, 
112516   const char *zName, 
112517   int eTextRep, 
112518   void*,
112519   int(*xCompare)(void*,int,const void*,int,const void*),
112520   void(*xDestroy)(void*)
112521 );
112522 int sqlite3_create_collation16(
112523   sqlite3*, 
112524   const char *zName, 
112525   int eTextRep, 
112526   void*,
112527   int(*xCompare)(void*,int,const void*,int,const void*)
112528 );
112529
112530 /*
112531 ** CAPI3REF: Collation Needed Callbacks {F16700}
112532 **
112533 ** {F16701}
112534 ** To avoid having to register all collation sequences before a database
112535 ** can be used, a single callback function may be registered with the
112536 ** database handle to be called whenever an undefined collation sequence is
112537 ** required.
112538 **
112539 ** {F16702}
112540 ** If the function is registered using the sqlite3_collation_needed() API,
112541 ** then it is passed the names of undefined collation sequences as strings
112542 ** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, the names
112543 ** are passed as UTF-16 in machine native byte order. {F16704} A call to either
112544 ** function replaces any existing callback.
112545 **
112546 ** {F16705} When the callback is invoked, the first argument passed is a copy
112547 ** of the second argument to sqlite3_collation_needed() or
112548 ** sqlite3_collation_needed16(). {F16706} The second argument is the database
112549 ** handle.  {F16707} The third argument is one of [SQLITE_UTF8],
112550 ** [SQLITE_UTF16BE], or [SQLITE_UTF16LE], indicating the most
112551 ** desirable form of the collation sequence function required.
112552 ** {F16708} The fourth parameter is the name of the
112553 ** required collation sequence. {END}
112554 **
112555 ** The callback function should register the desired collation using
112556 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
112557 ** [sqlite3_create_collation_v2()].
112558 */
112559 int sqlite3_collation_needed(
112560   sqlite3*, 
112561   void*, 
112562   void(*)(void*,sqlite3*,int eTextRep,const char*)
112563 );
112564 int sqlite3_collation_needed16(
112565   sqlite3*, 
112566   void*,
112567   void(*)(void*,sqlite3*,int eTextRep,const void*)
112568 );
112569
112570 /*
112571 ** Specify the key for an encrypted database.  This routine should be
112572 ** called right after sqlite3_open().
112573 **
112574 ** The code to implement this API is not available in the public release
112575 ** of SQLite.
112576 */
112577 int sqlite3_key(
112578   sqlite3 *db,                   /* Database to be rekeyed */
112579   const void *pKey, int nKey     /* The key */
112580 );
112581
112582 /*
112583 ** Change the key on an open database.  If the current database is not
112584 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
112585 ** database is decrypted.
112586 **
112587 ** The code to implement this API is not available in the public release
112588 ** of SQLite.
112589 */
112590 int sqlite3_rekey(
112591   sqlite3 *db,                   /* Database to be rekeyed */
112592   const void *pKey, int nKey     /* The new key */
112593 );
112594
112595 /*
112596 ** CAPI3REF:  Suspend Execution For A Short Time {F10530}
112597 **
112598 ** {F10531} The sqlite3_sleep() function
112599 ** causes the current thread to suspend execution
112600 ** for at least a number of milliseconds specified in its parameter.
112601 **
112602 ** {F10532} If the operating system does not support sleep requests with 
112603 ** millisecond time resolution, then the time will be rounded up to 
112604 ** the nearest second. {F10533} The number of milliseconds of sleep actually 
112605 ** requested from the operating system is returned.
112606 **
112607 ** {F10534} SQLite implements this interface by calling the xSleep()
112608 ** method of the default [sqlite3_vfs] object. {END}
112609 */
112610 int sqlite3_sleep(int);
112611
112612 /*
112613 ** CAPI3REF:  Name Of The Folder Holding Temporary Files {F10310}
112614 **
112615 ** If this global variable is made to point to a string which is
112616 ** the name of a folder (a.ka. directory), then all temporary files
112617 ** created by SQLite will be placed in that directory.  If this variable
112618 ** is NULL pointer, then SQLite does a search for an appropriate temporary
112619 ** file directory.
112620 **
112621 ** It is not safe to modify this variable once a database connection
112622 ** has been opened.  It is intended that this variable be set once
112623 ** as part of process initialization and before any SQLite interface
112624 ** routines have been call and remain unchanged thereafter.
112625 */
112626 SQLITE_EXTERN char *sqlite3_temp_directory;
112627
112628 /*
112629 ** CAPI3REF:  Test To See If The Database Is In Auto-Commit Mode {F12930}
112630 **
112631 ** {F12931} The sqlite3_get_autocommit() interfaces returns non-zero or
112632 ** zero if the given database connection is or is not in autocommit mode,
112633 ** respectively. {F12932}  Autocommit mode is on
112634 ** by default.  {F12933} Autocommit mode is disabled by a BEGIN statement.
112635 ** {F12934} Autocommit mode is reenabled by a COMMIT or ROLLBACK. {END}
112636 **
112637 ** If certain kinds of errors occur on a statement within a multi-statement
112638 ** transactions (errors including [SQLITE_FULL], [SQLITE_IOERR], 
112639 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
112640 ** transaction might be rolled back automatically.  {F12935} The only way to
112641 ** find out if SQLite automatically rolled back the transaction after
112642 ** an error is to use this function. {END}
112643 **
112644 ** {U12936} If another thread changes the autocommit status of the database
112645 ** connection while this routine is running, then the return value
112646 ** is undefined. {END}
112647 */
112648 int sqlite3_get_autocommit(sqlite3*);
112649
112650 /*
112651 ** CAPI3REF:  Find The Database Handle Of A Prepared Statement {F13120}
112652 **
112653 ** {F13121} The sqlite3_db_handle interface
112654 ** returns the [sqlite3*] database handle to which a
112655 ** [sqlite3_stmt | prepared statement] belongs.
112656 ** {F13122} the database handle returned by sqlite3_db_handle
112657 ** is the same database handle that was
112658 ** the first argument to the [sqlite3_prepare_v2()] or its variants
112659 ** that was used to create the statement in the first place.
112660 */
112661 sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
112662
112663
112664 /*
112665 ** CAPI3REF: Commit And Rollback Notification Callbacks {F12950}
112666 **
112667 ** {F12951} The sqlite3_commit_hook() interface registers a callback
112668 ** function to be invoked whenever a transaction is committed.
112669 ** {F12952} Any callback set by a previous call to sqlite3_commit_hook()
112670 ** for the same database connection is overridden.
112671 ** {F12953} The sqlite3_rollback_hook() interface registers a callback
112672 ** function to be invoked whenever a transaction is committed.
112673 ** {F12954} Any callback set by a previous call to sqlite3_commit_hook()
112674 ** for the same database connection is overridden.
112675 ** {F12956} The pArg argument is passed through
112676 ** to the callback.  {F12957} If the callback on a commit hook function 
112677 ** returns non-zero, then the commit is converted into a rollback.
112678 **
112679 ** {F12958} If another function was previously registered, its
112680 ** pArg value is returned.  Otherwise NULL is returned.
112681 **
112682 ** {F12959} Registering a NULL function disables the callback.
112683 **
112684 ** {F12961} For the purposes of this API, a transaction is said to have been 
112685 ** rolled back if an explicit "ROLLBACK" statement is executed, or
112686 ** an error or constraint causes an implicit rollback to occur.
112687 ** {F12962} The rollback callback is not invoked if a transaction is
112688 ** automatically rolled back because the database connection is closed.
112689 ** {F12964} The rollback callback is not invoked if a transaction is
112690 ** rolled back because a commit callback returned non-zero.
112691 ** <todo> Check on this </todo> {END}
112692 **
112693 ** These are experimental interfaces and are subject to change.
112694 */
112695 void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
112696 void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
112697
112698 /*
112699 ** CAPI3REF: Data Change Notification Callbacks {F12970}
112700 **
112701 ** {F12971} The sqlite3_update_hook() interface
112702 ** registers a callback function with the database connection identified by the 
112703 ** first argument to be invoked whenever a row is updated, inserted or deleted.
112704 ** {F12972} Any callback set by a previous call to this function for the same 
112705 ** database connection is overridden.
112706 **
112707 ** {F12974} The second argument is a pointer to the function to invoke when a 
112708 ** row is updated, inserted or deleted. 
112709 ** {F12976} The first argument to the callback is
112710 ** a copy of the third argument to sqlite3_update_hook().
112711 ** {F12977} The second callback 
112712 ** argument is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
112713 ** depending on the operation that caused the callback to be invoked.
112714 ** {F12978} The third and 
112715 ** fourth arguments to the callback contain pointers to the database and 
112716 ** table name containing the affected row.
112717 ** {F12979} The final callback parameter is 
112718 ** the rowid of the row.
112719 ** {F12981} In the case of an update, this is the rowid after 
112720 ** the update takes place.
112721 **
112722 ** {F12983} The update hook is not invoked when internal system tables are
112723 ** modified (i.e. sqlite_master and sqlite_sequence).
112724 **
112725 ** {F12984} If another function was previously registered, its pArg value
112726 ** is returned.  {F12985} Otherwise NULL is returned.
112727 */
112728 void *sqlite3_update_hook(
112729   sqlite3*, 
112730   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
112731   void*
112732 );
112733
112734 /*
112735 ** CAPI3REF:  Enable Or Disable Shared Pager Cache {F10330}
112736 **
112737 ** {F10331}
112738 ** This routine enables or disables the sharing of the database cache
112739 ** and schema data structures between connections to the same database.
112740 ** {F10332}
112741 ** Sharing is enabled if the argument is true and disabled if the argument
112742 ** is false.
112743 **
112744 ** {F10333} Cache sharing is enabled and disabled
112745 ** for an entire process. {END} This is a change as of SQLite version 3.5.0.
112746 ** In prior versions of SQLite, sharing was
112747 ** enabled or disabled for each thread separately.
112748 **
112749 ** {F10334}
112750 ** The cache sharing mode set by this interface effects all subsequent
112751 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
112752 ** {F10335} Existing database connections continue use the sharing mode
112753 ** that was in effect at the time they were opened. {END}
112754 **
112755 ** Virtual tables cannot be used with a shared cache.  {F10336} When shared
112756 ** cache is enabled, the [sqlite3_create_module()] API used to register
112757 ** virtual tables will always return an error. {END}
112758 **
112759 ** {F10337} This routine returns [SQLITE_OK] if shared cache was
112760 ** enabled or disabled successfully.  {F10338} An [SQLITE_ERROR | error code]
112761 ** is returned otherwise. {END}
112762 **
112763 ** {F10339} Shared cache is disabled by default. {END} But this might change in
112764 ** future releases of SQLite.  Applications that care about shared
112765 ** cache setting should set it explicitly.
112766 */
112767 int sqlite3_enable_shared_cache(int);
112768
112769 /*
112770 ** CAPI3REF:  Attempt To Free Heap Memory {F17340}
112771 **
112772 ** {F17341} The sqlite3_release_memory() interface attempts to
112773 ** free N bytes of heap memory by deallocating non-essential memory
112774 ** allocations held by the database labrary. {END}  Memory used
112775 ** to cache database pages to improve performance is an example of
112776 ** non-essential memory.  {F16342} sqlite3_release_memory() returns
112777 ** the number of bytes actually freed, which might be more or less
112778 ** than the amount requested.
112779 */
112780 int sqlite3_release_memory(int);
112781
112782 /*
112783 ** CAPI3REF:  Impose A Limit On Heap Size {F17350}
112784 **
112785 ** {F16351} The sqlite3_soft_heap_limit() interface
112786 ** places a "soft" limit on the amount of heap memory that may be allocated
112787 ** by SQLite. {F16352} If an internal allocation is requested 
112788 ** that would exceed the soft heap limit, [sqlite3_release_memory()] is
112789 ** invoked one or more times to free up some space before the allocation
112790 ** is made. {END}
112791 **
112792 ** {F16353} The limit is called "soft", because if
112793 ** [sqlite3_release_memory()] cannot
112794 ** free sufficient memory to prevent the limit from being exceeded,
112795 ** the memory is allocated anyway and the current operation proceeds.
112796 **
112797 ** {F16354}
112798 ** A negative or zero value for N means that there is no soft heap limit and
112799 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
112800 ** {F16355} The default value for the soft heap limit is zero.
112801 **
112802 ** SQLite makes a best effort to honor the soft heap limit.  
112803 ** {F16356} But if the soft heap limit cannot honored, execution will
112804 ** continue without error or notification. {END}  This is why the limit is 
112805 ** called a "soft" limit.  It is advisory only.
112806 **
112807 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
112808 ** allocated by a single thread - the same thread in which this routine
112809 ** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
112810 ** applied to all threads. {F16357} The value specified for the soft heap limit
112811 ** is an upper bound on the total memory allocation for all threads. {END}  In
112812 ** version 3.5.0 there is no mechanism for limiting the heap usage for
112813 ** individual threads.
112814 */
112815 void sqlite3_soft_heap_limit(int);
112816
112817 /*
112818 ** CAPI3REF:  Extract Metadata About A Column Of A Table {F12850}
112819 **
112820 ** This routine
112821 ** returns meta-data about a specific column of a specific database
112822 ** table accessible using the connection handle passed as the first function 
112823 ** argument.
112824 **
112825 ** The column is identified by the second, third and fourth parameters to 
112826 ** this function. The second parameter is either the name of the database
112827 ** (i.e. "main", "temp" or an attached database) containing the specified
112828 ** table or NULL. If it is NULL, then all attached databases are searched
112829 ** for the table using the same algorithm as the database engine uses to 
112830 ** resolve unqualified table references.
112831 **
112832 ** The third and fourth parameters to this function are the table and column 
112833 ** name of the desired column, respectively. Neither of these parameters 
112834 ** may be NULL.
112835 **
112836 ** Meta information is returned by writing to the memory locations passed as
112837 ** the 5th and subsequent parameters to this function. Any of these 
112838 ** arguments may be NULL, in which case the corresponding element of meta 
112839 ** information is ommitted.
112840 **
112841 ** <pre>
112842 ** Parameter     Output Type      Description
112843 ** -----------------------------------
112844 **
112845 **   5th         const char*      Data type
112846 **   6th         const char*      Name of the default collation sequence 
112847 **   7th         int              True if the column has a NOT NULL constraint
112848 **   8th         int              True if the column is part of the PRIMARY KEY
112849 **   9th         int              True if the column is AUTOINCREMENT
112850 ** </pre>
112851 **
112852 **
112853 ** The memory pointed to by the character pointers returned for the 
112854 ** declaration type and collation sequence is valid only until the next 
112855 ** call to any sqlite API function.
112856 **
112857 ** If the specified table is actually a view, then an error is returned.
112858 **
112859 ** If the specified column is "rowid", "oid" or "_rowid_" and an 
112860 ** INTEGER PRIMARY KEY column has been explicitly declared, then the output 
112861 ** parameters are set for the explicitly declared column. If there is no
112862 ** explicitly declared IPK column, then the output parameters are set as 
112863 ** follows:
112864 **
112865 ** <pre>
112866 **     data type: "INTEGER"
112867 **     collation sequence: "BINARY"
112868 **     not null: 0
112869 **     primary key: 1
112870 **     auto increment: 0
112871 ** </pre>
112872 **
112873 ** This function may load one or more schemas from database files. If an
112874 ** error occurs during this process, or if the requested table or column
112875 ** cannot be found, an SQLITE error code is returned and an error message
112876 ** left in the database handle (to be retrieved using sqlite3_errmsg()).
112877 **
112878 ** This API is only available if the library was compiled with the
112879 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
112880 */
112881 int sqlite3_table_column_metadata(
112882   sqlite3 *db,                /* Connection handle */
112883   const char *zDbName,        /* Database name or NULL */
112884   const char *zTableName,     /* Table name */
112885   const char *zColumnName,    /* Column name */
112886   char const **pzDataType,    /* OUTPUT: Declared data type */
112887   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
112888   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
112889   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
112890   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
112891 );
112892
112893 /*
112894 ** CAPI3REF: Load An Extension {F12600}
112895 **
112896 ** {F12601} The sqlite3_load_extension() interface
112897 ** attempts to load an SQLite extension library contained in the file
112898 ** zFile. {F12602} The entry point is zProc. {F12603} zProc may be 0
112899 ** in which case the name of the entry point defaults
112900 ** to "sqlite3_extension_init".
112901 **
112902 ** {F12604} The sqlite3_load_extension() interface shall
112903 ** return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
112904 **
112905 ** {F12605}
112906 ** If an error occurs and pzErrMsg is not 0, then the
112907 ** sqlite3_load_extension() interface shall attempt to fill *pzErrMsg with 
112908 ** error message text stored in memory obtained from [sqlite3_malloc()].
112909 ** {END}  The calling function should free this memory
112910 ** by calling [sqlite3_free()].
112911 **
112912 ** {F12606}
112913 ** Extension loading must be enabled using [sqlite3_enable_load_extension()]
112914 ** prior to calling this API or an error will be returned.
112915 */
112916 int sqlite3_load_extension(
112917   sqlite3 *db,          /* Load the extension into this database connection */
112918   const char *zFile,    /* Name of the shared library containing extension */
112919   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
112920   char **pzErrMsg       /* Put error message here if not 0 */
112921 );
112922
112923 /*
112924 ** CAPI3REF:  Enable Or Disable Extension Loading {F12620}
112925 **
112926 ** So as not to open security holes in older applications that are
112927 ** unprepared to deal with extension loading, and as a means of disabling
112928 ** extension loading while evaluating user-entered SQL, the following
112929 ** API is provided to turn the [sqlite3_load_extension()] mechanism on and
112930 ** off.  {F12622} It is off by default. {END} See ticket #1863.
112931 **
112932 ** {F12621} Call the sqlite3_enable_load_extension() routine
112933 ** with onoff==1 to turn extension loading on
112934 ** and call it with onoff==0 to turn it back off again. {END}
112935 */
112936 int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
112937
112938 /*
112939 ** CAPI3REF: Make Arrangements To Automatically Load An Extension {F12640}
112940 **
112941 ** {F12641} This function
112942 ** registers an extension entry point that is automatically invoked
112943 ** whenever a new database connection is opened using
112944 ** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. {END}
112945 **
112946 ** This API can be invoked at program startup in order to register
112947 ** one or more statically linked extensions that will be available
112948 ** to all new database connections.
112949 **
112950 ** {F12642} Duplicate extensions are detected so calling this routine multiple
112951 ** times with the same extension is harmless.
112952 **
112953 ** {F12643} This routine stores a pointer to the extension in an array
112954 ** that is obtained from sqlite_malloc(). {END} If you run a memory leak
112955 ** checker on your program and it reports a leak because of this
112956 ** array, then invoke [sqlite3_reset_auto_extension()] prior
112957 ** to shutdown to free the memory.
112958 **
112959 ** {F12644} Automatic extensions apply across all threads. {END}
112960 **
112961 ** This interface is experimental and is subject to change or
112962 ** removal in future releases of SQLite.
112963 */
112964 int sqlite3_auto_extension(void *xEntryPoint);
112965
112966
112967 /*
112968 ** CAPI3REF: Reset Automatic Extension Loading {F12660}
112969 **
112970 ** {F12661} This function disables all previously registered
112971 ** automatic extensions. {END}  This
112972 ** routine undoes the effect of all prior [sqlite3_automatic_extension()]
112973 ** calls.
112974 **
112975 ** {F12662} This call disabled automatic extensions in all threads. {END}
112976 **
112977 ** This interface is experimental and is subject to change or
112978 ** removal in future releases of SQLite.
112979 */
112980 void sqlite3_reset_auto_extension(void);
112981
112982
112983 /*
112984 ****** EXPERIMENTAL - subject to change without notice **************
112985 **
112986 ** The interface to the virtual-table mechanism is currently considered
112987 ** to be experimental.  The interface might change in incompatible ways.
112988 ** If this is a problem for you, do not use the interface at this time.
112989 **
112990 ** When the virtual-table mechanism stablizes, we will declare the
112991 ** interface fixed, support it indefinitely, and remove this comment.
112992 */
112993
112994 /*
112995 ** Structures used by the virtual table interface
112996 */
112997 typedef struct sqlite3_vtab sqlite3_vtab;
112998 typedef struct sqlite3_index_info sqlite3_index_info;
112999 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
113000 typedef struct sqlite3_module sqlite3_module;
113001
113002 /*
113003 ** A module is a class of virtual tables.  Each module is defined
113004 ** by an instance of the following structure.  This structure consists
113005 ** mostly of methods for the module.
113006 */
113007 struct sqlite3_module {
113008   int iVersion;
113009   int (*xCreate)(sqlite3*, void *pAux,
113010                int argc, const char *const*argv,
113011                sqlite3_vtab **ppVTab, char**);
113012   int (*xConnect)(sqlite3*, void *pAux,
113013                int argc, const char *const*argv,
113014                sqlite3_vtab **ppVTab, char**);
113015   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
113016   int (*xDisconnect)(sqlite3_vtab *pVTab);
113017   int (*xDestroy)(sqlite3_vtab *pVTab);
113018   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
113019   int (*xClose)(sqlite3_vtab_cursor*);
113020   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
113021                 int argc, sqlite3_value **argv);
113022   int (*xNext)(sqlite3_vtab_cursor*);
113023   int (*xEof)(sqlite3_vtab_cursor*);
113024   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
113025   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
113026   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
113027   int (*xBegin)(sqlite3_vtab *pVTab);
113028   int (*xSync)(sqlite3_vtab *pVTab);
113029   int (*xCommit)(sqlite3_vtab *pVTab);
113030   int (*xRollback)(sqlite3_vtab *pVTab);
113031   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
113032                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
113033                        void **ppArg);
113034
113035   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
113036 };
113037
113038 /*
113039 ** The sqlite3_index_info structure and its substructures is used to
113040 ** pass information into and receive the reply from the xBestIndex
113041 ** method of an sqlite3_module.  The fields under **Inputs** are the
113042 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
113043 ** results into the **Outputs** fields.
113044 **
113045 ** The aConstraint[] array records WHERE clause constraints of the
113046 ** form:
113047 **
113048 **         column OP expr
113049 **
113050 ** Where OP is =, &lt;, &lt;=, &gt;, or &gt;=.  
113051 ** The particular operator is stored
113052 ** in aConstraint[].op.  The index of the column is stored in 
113053 ** aConstraint[].iColumn.  aConstraint[].usable is TRUE if the
113054 ** expr on the right-hand side can be evaluated (and thus the constraint
113055 ** is usable) and false if it cannot.
113056 **
113057 ** The optimizer automatically inverts terms of the form "expr OP column"
113058 ** and makes other simplifications to the WHERE clause in an attempt to
113059 ** get as many WHERE clause terms into the form shown above as possible.
113060 ** The aConstraint[] array only reports WHERE clause terms in the correct
113061 ** form that refer to the particular virtual table being queried.
113062 **
113063 ** Information about the ORDER BY clause is stored in aOrderBy[].
113064 ** Each term of aOrderBy records a column of the ORDER BY clause.
113065 **
113066 ** The xBestIndex method must fill aConstraintUsage[] with information
113067 ** about what parameters to pass to xFilter.  If argvIndex>0 then
113068 ** the right-hand side of the corresponding aConstraint[] is evaluated
113069 ** and becomes the argvIndex-th entry in argv.  If aConstraintUsage[].omit
113070 ** is true, then the constraint is assumed to be fully handled by the
113071 ** virtual table and is not checked again by SQLite.
113072 **
113073 ** The idxNum and idxPtr values are recorded and passed into xFilter.
113074 ** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
113075 **
113076 ** The orderByConsumed means that output from xFilter will occur in
113077 ** the correct order to satisfy the ORDER BY clause so that no separate
113078 ** sorting step is required.
113079 **
113080 ** The estimatedCost value is an estimate of the cost of doing the
113081 ** particular lookup.  A full scan of a table with N entries should have
113082 ** a cost of N.  A binary search of a table of N entries should have a
113083 ** cost of approximately log(N).
113084 */
113085 struct sqlite3_index_info {
113086   /* Inputs */
113087   int nConstraint;           /* Number of entries in aConstraint */
113088   struct sqlite3_index_constraint {
113089      int iColumn;              /* Column on left-hand side of constraint */
113090      unsigned char op;         /* Constraint operator */
113091      unsigned char usable;     /* True if this constraint is usable */
113092      int iTermOffset;          /* Used internally - xBestIndex should ignore */
113093   } *aConstraint;            /* Table of WHERE clause constraints */
113094   int nOrderBy;              /* Number of terms in the ORDER BY clause */
113095   struct sqlite3_index_orderby {
113096      int iColumn;              /* Column number */
113097      unsigned char desc;       /* True for DESC.  False for ASC. */
113098   } *aOrderBy;               /* The ORDER BY clause */
113099
113100   /* Outputs */
113101   struct sqlite3_index_constraint_usage {
113102     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
113103     unsigned char omit;      /* Do not code a test for this constraint */
113104   } *aConstraintUsage;
113105   int idxNum;                /* Number used to identify the index */
113106   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
113107   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
113108   int orderByConsumed;       /* True if output is already ordered */
113109   double estimatedCost;      /* Estimated cost of using this index */
113110 };
113111 #define SQLITE_INDEX_CONSTRAINT_EQ    2
113112 #define SQLITE_INDEX_CONSTRAINT_GT    4
113113 #define SQLITE_INDEX_CONSTRAINT_LE    8
113114 #define SQLITE_INDEX_CONSTRAINT_LT    16
113115 #define SQLITE_INDEX_CONSTRAINT_GE    32
113116 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
113117
113118 /*
113119 ** This routine is used to register a new module name with an SQLite
113120 ** connection.  Module names must be registered before creating new
113121 ** virtual tables on the module, or before using preexisting virtual
113122 ** tables of the module.
113123 */
113124 int sqlite3_create_module(
113125   sqlite3 *db,               /* SQLite connection to register module with */
113126   const char *zName,         /* Name of the module */
113127   const sqlite3_module *,    /* Methods for the module */
113128   void *                     /* Client data for xCreate/xConnect */
113129 );
113130
113131 /*
113132 ** This routine is identical to the sqlite3_create_module() method above,
113133 ** except that it allows a destructor function to be specified. It is
113134 ** even more experimental than the rest of the virtual tables API.
113135 */
113136 int sqlite3_create_module_v2(
113137   sqlite3 *db,               /* SQLite connection to register module with */
113138   const char *zName,         /* Name of the module */
113139   const sqlite3_module *,    /* Methods for the module */
113140   void *,                    /* Client data for xCreate/xConnect */
113141   void(*xDestroy)(void*)     /* Module destructor function */
113142 );
113143
113144 /*
113145 ** Every module implementation uses a subclass of the following structure
113146 ** to describe a particular instance of the module.  Each subclass will
113147 ** be tailored to the specific needs of the module implementation.   The
113148 ** purpose of this superclass is to define certain fields that are common
113149 ** to all module implementations.
113150 **
113151 ** Virtual tables methods can set an error message by assigning a
113152 ** string obtained from sqlite3_mprintf() to zErrMsg.  The method should
113153 ** take care that any prior string is freed by a call to sqlite3_free()
113154 ** prior to assigning a new string to zErrMsg.  After the error message
113155 ** is delivered up to the client application, the string will be automatically
113156 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.  Note
113157 ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
113158 ** since virtual tables are commonly implemented in loadable extensions which
113159 ** do not have access to sqlite3MPrintf() or sqlite3Free().
113160 */
113161 struct sqlite3_vtab {
113162   const sqlite3_module *pModule;  /* The module for this virtual table */
113163   int nRef;                       /* Used internally */
113164   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
113165   /* Virtual table implementations will typically add additional fields */
113166 };
113167
113168 /* Every module implementation uses a subclass of the following structure
113169 ** to describe cursors that point into the virtual table and are used
113170 ** to loop through the virtual table.  Cursors are created using the
113171 ** xOpen method of the module.  Each module implementation will define
113172 ** the content of a cursor structure to suit its own needs.
113173 **
113174 ** This superclass exists in order to define fields of the cursor that
113175 ** are common to all implementations.
113176 */
113177 struct sqlite3_vtab_cursor {
113178   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
113179   /* Virtual table implementations will typically add additional fields */
113180 };
113181
113182 /*
113183 ** The xCreate and xConnect methods of a module use the following API
113184 ** to declare the format (the names and datatypes of the columns) of
113185 ** the virtual tables they implement.
113186 */
113187 int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
113188
113189 /*
113190 ** Virtual tables can provide alternative implementations of functions
113191 ** using the xFindFunction method.  But global versions of those functions
113192 ** must exist in order to be overloaded.
113193 **
113194 ** This API makes sure a global version of a function with a particular
113195 ** name and number of parameters exists.  If no such function exists
113196 ** before this API is called, a new function is created.  The implementation
113197 ** of the new function always causes an exception to be thrown.  So
113198 ** the new function is not good for anything by itself.  Its only
113199 ** purpose is to be a place-holder function that can be overloaded
113200 ** by virtual tables.
113201 **
113202 ** This API should be considered part of the virtual table interface,
113203 ** which is experimental and subject to change.
113204 */
113205 int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
113206
113207 /*
113208 ** The interface to the virtual-table mechanism defined above (back up
113209 ** to a comment remarkably similar to this one) is currently considered
113210 ** to be experimental.  The interface might change in incompatible ways.
113211 ** If this is a problem for you, do not use the interface at this time.
113212 **
113213 ** When the virtual-table mechanism stabilizes, we will declare the
113214 ** interface fixed, support it indefinitely, and remove this comment.
113215 **
113216 ****** EXPERIMENTAL - subject to change without notice **************
113217 */
113218
113219 /*
113220 ** CAPI3REF: A Handle To An Open BLOB {F17800}
113221 **
113222 ** An instance of the following opaque structure is used to 
113223 ** represent an blob-handle.  A blob-handle is created by
113224 ** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()].
113225 ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
113226 ** can be used to read or write small subsections of the blob.
113227 ** The [sqlite3_blob_bytes()] interface returns the size of the
113228 ** blob in bytes.
113229 */
113230 typedef struct sqlite3_blob sqlite3_blob;
113231
113232 /*
113233 ** CAPI3REF: Open A BLOB For Incremental I/O {F17810}
113234 **
113235 ** {F17811} This interfaces opens a handle to the blob located
113236 ** in row iRow,, column zColumn, table zTable in database zDb;
113237 ** in other words,  the same blob that would be selected by:
113238 **
113239 ** <pre>
113240 **     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
113241 ** </pre> {END}
113242 **
113243 ** {F17812} If the flags parameter is non-zero, the blob is opened for 
113244 ** read and write access. If it is zero, the blob is opened for read 
113245 ** access. {END}
113246 **
113247 ** {F17813} On success, [SQLITE_OK] is returned and the new 
113248 ** [sqlite3_blob | blob handle] is written to *ppBlob. 
113249 ** {F17814} Otherwise an error code is returned and 
113250 ** any value written to *ppBlob should not be used by the caller.
113251 ** {F17815} This function sets the database-handle error code and message
113252 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()].
113253 ** <todo>We should go through and mark all interfaces that behave this
113254 ** way with a similar statement</todo>
113255 */
113256 int sqlite3_blob_open(
113257   sqlite3*,
113258   const char *zDb,
113259   const char *zTable,
113260   const char *zColumn,
113261   sqlite3_int64 iRow,
113262   int flags,
113263   sqlite3_blob **ppBlob
113264 );
113265
113266 /*
113267 ** CAPI3REF:  Close A BLOB Handle {F17830}
113268 **
113269 ** Close an open [sqlite3_blob | blob handle].
113270 **
113271 ** {F17831} Closing a BLOB shall cause the current transaction to commit
113272 ** if there are no other BLOBs, no pending prepared statements, and the
113273 ** database connection is in autocommit mode.
113274 ** {F17832} If any writes were made to the BLOB, they might be held in cache
113275 ** until the close operation if they will fit. {END}
113276 ** Closing the BLOB often forces the changes
113277 ** out to disk and so if any I/O errors occur, they will likely occur
113278 ** at the time when the BLOB is closed.  {F17833} Any errors that occur during
113279 ** closing are reported as a non-zero return value.
113280 **
113281 ** {F17839} The BLOB is closed unconditionally.  Even if this routine returns
113282 ** an error code, the BLOB is still closed.
113283 */
113284 int sqlite3_blob_close(sqlite3_blob *);
113285
113286 /*
113287 ** CAPI3REF:  Return The Size Of An Open BLOB {F17805}
113288 **
113289 ** {F16806} Return the size in bytes of the blob accessible via the open 
113290 ** [sqlite3_blob | blob-handle] passed as an argument.
113291 */
113292 int sqlite3_blob_bytes(sqlite3_blob *);
113293
113294 /*
113295 ** CAPI3REF:  Read Data From A BLOB Incrementally {F17850}
113296 **
113297 ** This function is used to read data from an open 
113298 ** [sqlite3_blob | blob-handle] into a caller supplied buffer.
113299 ** {F17851} n bytes of data are copied into buffer
113300 ** z from the open blob, starting at offset iOffset.
113301 **
113302 ** {F17852} If offset iOffset is less than n bytes from the end of the blob, 
113303 ** [SQLITE_ERROR] is returned and no data is read.  {F17853} If n is
113304 ** less than zero [SQLITE_ERROR] is returned and no data is read.
113305 **
113306 ** {F17854} On success, SQLITE_OK is returned. Otherwise, an 
113307 ** [SQLITE_ERROR | SQLite error code] or an
113308 ** [SQLITE_IOERR_READ | extended error code] is returned.
113309 */
113310 int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset);
113311
113312 /*
113313 ** CAPI3REF:  Write Data Into A BLOB Incrementally {F17870}
113314 **
113315 ** This function is used to write data into an open 
113316 ** [sqlite3_blob | blob-handle] from a user supplied buffer.
113317 ** {F17871} n bytes of data are copied from the buffer
113318 ** pointed to by z into the open blob, starting at offset iOffset.
113319 **
113320 ** {F17872} If the [sqlite3_blob | blob-handle] passed as the first argument
113321 ** was not opened for writing (the flags parameter to [sqlite3_blob_open()]
113322 *** was zero), this function returns [SQLITE_READONLY].
113323 **
113324 ** {F17873} This function may only modify the contents of the blob; it is
113325 ** not possible to increase the size of a blob using this API.
113326 ** {F17874} If offset iOffset is less than n bytes from the end of the blob, 
113327 ** [SQLITE_ERROR] is returned and no data is written.  {F17875} If n is
113328 ** less than zero [SQLITE_ERROR] is returned and no data is written.
113329 **
113330 ** {F17876} On success, SQLITE_OK is returned. Otherwise, an 
113331 ** [SQLITE_ERROR | SQLite error code] or an
113332 ** [SQLITE_IOERR_READ | extended error code] is returned.
113333 */
113334 int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
113335
113336 /*
113337 ** CAPI3REF:  Virtual File System Objects {F11200}
113338 **
113339 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
113340 ** that SQLite uses to interact
113341 ** with the underlying operating system.  Most builds come with a
113342 ** single default VFS that is appropriate for the host computer.
113343 ** New VFSes can be registered and existing VFSes can be unregistered.
113344 ** The following interfaces are provided.
113345 **
113346 ** {F11201} The sqlite3_vfs_find() interface returns a pointer to 
113347 ** a VFS given its name.  {F11202} Names are case sensitive.
113348 ** {F11203} Names are zero-terminated UTF-8 strings.
113349 ** {F11204} If there is no match, a NULL
113350 ** pointer is returned. {F11205} If zVfsName is NULL then the default 
113351 ** VFS is returned. {END}
113352 **
113353 ** {F11210} New VFSes are registered with sqlite3_vfs_register().
113354 ** {F11211} Each new VFS becomes the default VFS if the makeDflt flag is set.
113355 ** {F11212} The same VFS can be registered multiple times without injury.
113356 ** {F11213} To make an existing VFS into the default VFS, register it again
113357 ** with the makeDflt flag set. {U11214} If two different VFSes with the
113358 ** same name are registered, the behavior is undefined.  {U11215} If a
113359 ** VFS is registered with a name that is NULL or an empty string,
113360 ** then the behavior is undefined.
113361 ** 
113362 ** {F11220} Unregister a VFS with the sqlite3_vfs_unregister() interface.
113363 ** {F11221} If the default VFS is unregistered, another VFS is chosen as
113364 ** the default.  The choice for the new VFS is arbitrary.
113365 */
113366 sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
113367 int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
113368 int sqlite3_vfs_unregister(sqlite3_vfs*);
113369
113370 /*
113371 ** CAPI3REF: Mutexes {F17000}
113372 **
113373 ** The SQLite core uses these routines for thread
113374 ** synchronization.  Though they are intended for internal
113375 ** use by SQLite, code that links against SQLite is
113376 ** permitted to use any of these routines.
113377 **
113378 ** The SQLite source code contains multiple implementations 
113379 ** of these mutex routines.  An appropriate implementation
113380 ** is selected automatically at compile-time.  The following
113381 ** implementations are available in the SQLite core:
113382 **
113383 ** <ul>
113384 ** <li>   SQLITE_MUTEX_OS2
113385 ** <li>   SQLITE_MUTEX_PTHREAD
113386 ** <li>   SQLITE_MUTEX_W32
113387 ** <li>   SQLITE_MUTEX_NOOP
113388 ** </ul>
113389 **
113390 ** The SQLITE_MUTEX_NOOP implementation is a set of routines 
113391 ** that does no real locking and is appropriate for use in 
113392 ** a single-threaded application.  The SQLITE_MUTEX_OS2,
113393 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
113394 ** are appropriate for use on os/2, unix, and windows.
113395 ** 
113396 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
113397 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
113398 ** implementation is included with the library.  The
113399 ** mutex interface routines defined here become external
113400 ** references in the SQLite library for which implementations
113401 ** must be provided by the application.  This facility allows an
113402 ** application that links against SQLite to provide its own mutex
113403 ** implementation without having to modify the SQLite core.
113404 **
113405 ** {F17011} The sqlite3_mutex_alloc() routine allocates a new
113406 ** mutex and returns a pointer to it. {F17012} If it returns NULL
113407 ** that means that a mutex could not be allocated. {F17013} SQLite
113408 ** will unwind its stack and return an error. {F17014} The argument
113409 ** to sqlite3_mutex_alloc() is one of these integer constants:
113410 **
113411 ** <ul>
113412 ** <li>  SQLITE_MUTEX_FAST
113413 ** <li>  SQLITE_MUTEX_RECURSIVE
113414 ** <li>  SQLITE_MUTEX_STATIC_MASTER
113415 ** <li>  SQLITE_MUTEX_STATIC_MEM
113416 ** <li>  SQLITE_MUTEX_STATIC_MEM2
113417 ** <li>  SQLITE_MUTEX_STATIC_PRNG
113418 ** <li>  SQLITE_MUTEX_STATIC_LRU
113419 ** </ul> {END}
113420 **
113421 ** {F17015} The first two constants cause sqlite3_mutex_alloc() to create
113422 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
113423 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END}
113424 ** The mutex implementation does not need to make a distinction
113425 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
113426 ** not want to.  {F17016} But SQLite will only request a recursive mutex in
113427 ** cases where it really needs one.  {END} If a faster non-recursive mutex
113428 ** implementation is available on the host platform, the mutex subsystem
113429 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
113430 **
113431 ** {F17017} The other allowed parameters to sqlite3_mutex_alloc() each return
113432 ** a pointer to a static preexisting mutex. {END}  Four static mutexes are
113433 ** used by the current version of SQLite.  Future versions of SQLite
113434 ** may add additional static mutexes.  Static mutexes are for internal
113435 ** use by SQLite only.  Applications that use SQLite mutexes should
113436 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
113437 ** SQLITE_MUTEX_RECURSIVE.
113438 **
113439 ** {F17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
113440 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
113441 ** returns a different mutex on every call.  {F17034} But for the static 
113442 ** mutex types, the same mutex is returned on every call that has
113443 ** the same type number. {END}
113444 **
113445 ** {F17019} The sqlite3_mutex_free() routine deallocates a previously
113446 ** allocated dynamic mutex. {F17020} SQLite is careful to deallocate every
113447 ** dynamic mutex that it allocates. {U17021} The dynamic mutexes must not be in 
113448 ** use when they are deallocated. {U17022} Attempting to deallocate a static
113449 ** mutex results in undefined behavior. {F17023} SQLite never deallocates
113450 ** a static mutex. {END}
113451 **
113452 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
113453 ** to enter a mutex. {F17024} If another thread is already within the mutex,
113454 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
113455 ** SQLITE_BUSY. {F17025}  The sqlite3_mutex_try() interface returns SQLITE_OK
113456 ** upon successful entry.  {F17026} Mutexes created using
113457 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
113458 ** {F17027} In such cases the,
113459 ** mutex must be exited an equal number of times before another thread
113460 ** can enter.  {U17028} If the same thread tries to enter any other
113461 ** kind of mutex more than once, the behavior is undefined.
113462 ** {F17029} SQLite will never exhibit
113463 ** such behavior in its own use of mutexes. {END}
113464 **
113465 ** Some systems (ex: windows95) do not the operation implemented by
113466 ** sqlite3_mutex_try().  On those systems, sqlite3_mutex_try() will
113467 ** always return SQLITE_BUSY.  {F17030} The SQLite core only ever uses
113468 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior. {END}
113469 **
113470 ** {F17031} The sqlite3_mutex_leave() routine exits a mutex that was
113471 ** previously entered by the same thread.  {U17032} The behavior
113472 ** is undefined if the mutex is not currently entered by the
113473 ** calling thread or is not currently allocated.  {F17033} SQLite will
113474 ** never do either. {END}
113475 **
113476 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
113477 */
113478 sqlite3_mutex *sqlite3_mutex_alloc(int);
113479 void sqlite3_mutex_free(sqlite3_mutex*);
113480 void sqlite3_mutex_enter(sqlite3_mutex*);
113481 int sqlite3_mutex_try(sqlite3_mutex*);
113482 void sqlite3_mutex_leave(sqlite3_mutex*);
113483
113484 /*
113485 ** CAPI3REF: Mutex Verifcation Routines {F17080}
113486 **
113487 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
113488 ** are intended for use inside assert() statements. {F17081} The SQLite core
113489 ** never uses these routines except inside an assert() and applications
113490 ** are advised to follow the lead of the core.  {F17082} The core only
113491 ** provides implementations for these routines when it is compiled
113492 ** with the SQLITE_DEBUG flag.  {U17087} External mutex implementations
113493 ** are only required to provide these routines if SQLITE_DEBUG is
113494 ** defined and if NDEBUG is not defined.
113495 **
113496 ** {F17083} These routines should return true if the mutex in their argument
113497 ** is held or not held, respectively, by the calling thread. {END}
113498 **
113499 ** {X17084} The implementation is not required to provided versions of these
113500 ** routines that actually work.
113501 ** If the implementation does not provide working
113502 ** versions of these routines, it should at least provide stubs
113503 ** that always return true so that one does not get spurious
113504 ** assertion failures. {END}
113505 **
113506 ** {F17085} If the argument to sqlite3_mutex_held() is a NULL pointer then
113507 ** the routine should return 1.  {END} This seems counter-intuitive since
113508 ** clearly the mutex cannot be held if it does not exist.  But the
113509 ** the reason the mutex does not exist is because the build is not
113510 ** using mutexes.  And we do not want the assert() containing the
113511 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
113512 ** the appropriate thing to do.  {F17086} The sqlite3_mutex_notheld() 
113513 ** interface should also return 1 when given a NULL pointer.
113514 */
113515 int sqlite3_mutex_held(sqlite3_mutex*);
113516 int sqlite3_mutex_notheld(sqlite3_mutex*);
113517
113518 /*
113519 ** CAPI3REF: Mutex Types {F17001}
113520 **
113521 ** {F17002} The [sqlite3_mutex_alloc()] interface takes a single argument
113522 ** which is one of these integer constants. {END}
113523 */
113524 #define SQLITE_MUTEX_FAST             0
113525 #define SQLITE_MUTEX_RECURSIVE        1
113526 #define SQLITE_MUTEX_STATIC_MASTER    2
113527 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
113528 #define SQLITE_MUTEX_STATIC_MEM2      4  /* sqlite3_release_memory() */
113529 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
113530 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
113531
113532 /*
113533 ** CAPI3REF: Low-Level Control Of Database Files {F11300}
113534 **
113535 ** {F11301} The [sqlite3_file_control()] interface makes a direct call to the
113536 ** xFileControl method for the [sqlite3_io_methods] object associated
113537 ** with a particular database identified by the second argument. {F11302} The
113538 ** name of the database is the name assigned to the database by the
113539 ** <a href="lang_attach.html">ATTACH</a> SQL command that opened the
113540 ** database. {F11303} To control the main database file, use the name "main"
113541 ** or a NULL pointer. {F11304} The third and fourth parameters to this routine
113542 ** are passed directly through to the second and third parameters of
113543 ** the xFileControl method.  {F11305} The return value of the xFileControl
113544 ** method becomes the return value of this routine.
113545 **
113546 ** {F11306} If the second parameter (zDbName) does not match the name of any
113547 ** open database file, then SQLITE_ERROR is returned. {F11307} This error
113548 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
113549 ** or [sqlite3_errmsg()]. {U11308} The underlying xFileControl method might
113550 ** also return SQLITE_ERROR.  {U11309} There is no way to distinguish between
113551 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
113552 ** xFileControl method. {END}
113553 **
113554 ** See also: [SQLITE_FCNTL_LOCKSTATE]
113555 */
113556 int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
113557
113558 /*
113559 ** Undo the hack that converts floating point types to integer for
113560 ** builds on processors without floating point support.
113561 */
113562 #ifdef SQLITE_OMIT_FLOATING_POINT
113563 # undef double
113564 #endif
113565
113566 #if 0
113567 }  /* End of the 'extern "C"' block */
113568 #endif
113569 #endif
113570
113571 /************** End of sqlite3.h *********************************************/
113572 /************** Continuing where we left off in fts3_tokenizer.h *************/
113573
113574 /*
113575 ** Structures used by the tokenizer interface. When a new tokenizer
113576 ** implementation is registered, the caller provides a pointer to
113577 ** an sqlite3_tokenizer_module containing pointers to the callback
113578 ** functions that make up an implementation.
113579 **
113580 ** When an fts3 table is created, it passes any arguments passed to
113581 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
113582 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
113583 ** implementation. The xCreate() function in turn returns an 
113584 ** sqlite3_tokenizer structure representing the specific tokenizer to
113585 ** be used for the fts3 table (customized by the tokenizer clause arguments).
113586 **
113587 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
113588 ** method is called. It returns an sqlite3_tokenizer_cursor object
113589 ** that may be used to tokenize a specific input buffer based on
113590 ** the tokenization rules supplied by a specific sqlite3_tokenizer
113591 ** object.
113592 */
113593 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
113594 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
113595 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
113596
113597 struct sqlite3_tokenizer_module {
113598
113599   /*
113600   ** Structure version. Should always be set to 0.
113601   */
113602   int iVersion;
113603
113604   /*
113605   ** Create a new tokenizer. The values in the argv[] array are the
113606   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
113607   ** TABLE statement that created the fts3 table. For example, if
113608   ** the following SQL is executed:
113609   **
113610   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
113611   **
113612   ** then argc is set to 2, and the argv[] array contains pointers
113613   ** to the strings "arg1" and "arg2".
113614   **
113615   ** This method should return either SQLITE_OK (0), or an SQLite error 
113616   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
113617   ** to point at the newly created tokenizer structure. The generic
113618   ** sqlite3_tokenizer.pModule variable should not be initialised by
113619   ** this callback. The caller will do so.
113620   */
113621   int (*xCreate)(
113622     int argc,                           /* Size of argv array */
113623     const char *const*argv,             /* Tokenizer argument strings */
113624     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
113625   );
113626
113627   /*
113628   ** Destroy an existing tokenizer. The fts3 module calls this method
113629   ** exactly once for each successful call to xCreate().
113630   */
113631   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
113632
113633   /*
113634   ** Create a tokenizer cursor to tokenize an input buffer. The caller
113635   ** is responsible for ensuring that the input buffer remains valid
113636   ** until the cursor is closed (using the xClose() method). 
113637   */
113638   int (*xOpen)(
113639     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
113640     const char *pInput, int nBytes,      /* Input buffer */
113641     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
113642   );
113643
113644   /*
113645   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
113646   ** method exactly once for each successful call to xOpen().
113647   */
113648   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
113649
113650   /*
113651   ** Retrieve the next token from the tokenizer cursor pCursor. This
113652   ** method should either return SQLITE_OK and set the values of the
113653   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
113654   ** the end of the buffer has been reached, or an SQLite error code.
113655   **
113656   ** *ppToken should be set to point at a buffer containing the 
113657   ** normalized version of the token (i.e. after any case-folding and/or
113658   ** stemming has been performed). *pnBytes should be set to the length
113659   ** of this buffer in bytes. The input text that generated the token is
113660   ** identified by the byte offsets returned in *piStartOffset and
113661   ** *piEndOffset.
113662   **
113663   ** The buffer *ppToken is set to point at is managed by the tokenizer
113664   ** implementation. It is only required to be valid until the next call
113665   ** to xNext() or xClose(). 
113666   */
113667   /* TODO(shess) current implementation requires pInput to be
113668   ** nul-terminated.  This should either be fixed, or pInput/nBytes
113669   ** should be converted to zInput.
113670   */
113671   int (*xNext)(
113672     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
113673     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
113674     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
113675     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
113676     int *piPosition      /* OUT: Number of tokens returned before this one */
113677   );
113678 };
113679
113680 struct sqlite3_tokenizer {
113681   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
113682   /* Tokenizer implementations will typically add additional fields */
113683 };
113684
113685 struct sqlite3_tokenizer_cursor {
113686   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
113687   /* Tokenizer implementations will typically add additional fields */
113688 };
113689
113690 #endif /* _FTS3_TOKENIZER_H_ */
113691
113692 /************** End of fts3_tokenizer.h **************************************/
113693 /************** Continuing where we left off in fts3_icu.c *******************/
113694
113695 #include <unicode/ubrk.h>
113696 #include <unicode/ucol.h>
113697 #include <unicode/ustring.h>
113698 #include <unicode/utf16.h>
113699
113700 typedef struct IcuTokenizer IcuTokenizer;
113701 typedef struct IcuCursor IcuCursor;
113702
113703 struct IcuTokenizer {
113704   sqlite3_tokenizer base;
113705   char *zLocale;
113706 };
113707
113708 struct IcuCursor {
113709   sqlite3_tokenizer_cursor base;
113710
113711   UBreakIterator *pIter;      /* ICU break-iterator object */
113712   int nChar;                  /* Number of UChar elements in pInput */
113713   UChar *aChar;               /* Copy of input using utf-16 encoding */
113714   int *aOffset;               /* Offsets of each character in utf-8 input */
113715
113716   int nBuffer;
113717   char *zBuffer;
113718
113719   int iToken;
113720 };
113721
113722 /*
113723 ** Create a new tokenizer instance.
113724 */
113725 static int icuCreate(
113726   int argc,                            /* Number of entries in argv[] */
113727   const char * const *argv,            /* Tokenizer creation arguments */
113728   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
113729 ){
113730   IcuTokenizer *p;
113731   int n = 0;
113732
113733   if( argc>0 ){
113734     n = strlen(argv[0])+1;
113735   }
113736   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
113737   if( !p ){
113738     return SQLITE_NOMEM;
113739   }
113740   memset(p, 0, sizeof(IcuTokenizer));
113741
113742   if( n ){
113743     p->zLocale = (char *)&p[1];
113744     memcpy(p->zLocale, argv[0], n);
113745   }
113746
113747   *ppTokenizer = (sqlite3_tokenizer *)p;
113748
113749   return SQLITE_OK;
113750 }
113751
113752 /*
113753 ** Destroy a tokenizer
113754 */
113755 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
113756   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
113757   sqlite3_free(p);
113758   return SQLITE_OK;
113759 }
113760
113761 /*
113762 ** Prepare to begin tokenizing a particular string.  The input
113763 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
113764 ** used to incrementally tokenize this string is returned in 
113765 ** *ppCursor.
113766 */
113767 static int icuOpen(
113768   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
113769   const char *zInput,                    /* Input string */
113770   int nInput,                            /* Length of zInput in bytes */
113771   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
113772 ){
113773   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
113774   IcuCursor *pCsr;
113775
113776   const int32_t opt = U_FOLD_CASE_DEFAULT;
113777   UErrorCode status = U_ZERO_ERROR;
113778   int nChar;
113779
113780   UChar32 c;
113781   int iInput = 0;
113782   int iOut = 0;
113783
113784   *ppCursor = 0;
113785
113786   if( -1 == nInput ) nInput = strlen(nInput);
113787   nChar = nInput+1;
113788   pCsr = (IcuCursor *)sqlite3_malloc(
113789       sizeof(IcuCursor) +                /* IcuCursor */
113790       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
113791       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
113792   );
113793   if( !pCsr ){
113794     return SQLITE_NOMEM;
113795   }
113796   memset(pCsr, 0, sizeof(IcuCursor));
113797   pCsr->aChar = (UChar *)&pCsr[1];
113798   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
113799
113800   pCsr->aOffset[iOut] = iInput;
113801   U8_NEXT(zInput, iInput, nInput, c); 
113802   while( c>0 ){
113803     int isError = 0;
113804     c = u_foldCase(c, opt);
113805     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
113806     if( isError ){
113807       sqlite3_free(pCsr);
113808       return SQLITE_ERROR;
113809     }
113810     pCsr->aOffset[iOut] = iInput;
113811
113812     if( iInput<nInput ){
113813       U8_NEXT(zInput, iInput, nInput, c);
113814     }else{
113815       c = 0;
113816     }
113817   }
113818
113819   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
113820   if( !U_SUCCESS(status) ){
113821     sqlite3_free(pCsr);
113822     return SQLITE_ERROR;
113823   }
113824   pCsr->nChar = iOut;
113825
113826   ubrk_first(pCsr->pIter);
113827   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
113828   return SQLITE_OK;
113829 }
113830
113831 /*
113832 ** Close a tokenization cursor previously opened by a call to icuOpen().
113833 */
113834 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
113835   IcuCursor *pCsr = (IcuCursor *)pCursor;
113836   ubrk_close(pCsr->pIter);
113837   sqlite3_free(pCsr->zBuffer);
113838   sqlite3_free(pCsr);
113839   return SQLITE_OK;
113840 }
113841
113842 /*
113843 ** Extract the next token from a tokenization cursor.
113844 */
113845 static int icuNext(
113846   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
113847   const char **ppToken,               /* OUT: *ppToken is the token text */
113848   int *pnBytes,                       /* OUT: Number of bytes in token */
113849   int *piStartOffset,                 /* OUT: Starting offset of token */
113850   int *piEndOffset,                   /* OUT: Ending offset of token */
113851   int *piPosition                     /* OUT: Position integer of token */
113852 ){
113853   IcuCursor *pCsr = (IcuCursor *)pCursor;
113854
113855   int iStart = 0;
113856   int iEnd = 0;
113857   int nByte = 0;
113858
113859   while( iStart==iEnd ){
113860     UChar32 c;
113861
113862     iStart = ubrk_current(pCsr->pIter);
113863     iEnd = ubrk_next(pCsr->pIter);
113864     if( iEnd==UBRK_DONE ){
113865       return SQLITE_DONE;
113866     }
113867
113868     while( iStart<iEnd ){
113869       int iWhite = iStart;
113870       U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
113871       if( u_isspace(c) ){
113872         iStart = iWhite;
113873       }else{
113874         break;
113875       }
113876     }
113877     assert(iStart<=iEnd);
113878   }
113879
113880   do {
113881     UErrorCode status = U_ZERO_ERROR;
113882     if( nByte ){
113883       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
113884       if( !zNew ){
113885         return SQLITE_NOMEM;
113886       }
113887       pCsr->zBuffer = zNew;
113888       pCsr->nBuffer = nByte;
113889     }
113890
113891     u_strToUTF8(
113892         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
113893         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
113894         &status                                  /* Output success/failure */
113895     );
113896   } while( nByte>pCsr->nBuffer );
113897
113898   *ppToken = pCsr->zBuffer;
113899   *pnBytes = nByte;
113900   *piStartOffset = pCsr->aOffset[iStart];
113901   *piEndOffset = pCsr->aOffset[iEnd];
113902   *piPosition = pCsr->iToken++;
113903
113904   return SQLITE_OK;
113905 }
113906
113907 /*
113908 ** The set of routines that implement the simple tokenizer
113909 */
113910 static const sqlite3_tokenizer_module icuTokenizerModule = {
113911   0,                           /* iVersion */
113912   icuCreate,                   /* xCreate  */
113913   icuDestroy,                  /* xCreate  */
113914   icuOpen,                     /* xOpen    */
113915   icuClose,                    /* xClose   */
113916   icuNext,                     /* xNext    */
113917 };
113918
113919 /*
113920 ** Set *ppModule to point at the implementation of the ICU tokenizer.
113921 */
113922 void sqlite3Fts3IcuTokenizerModule(
113923   sqlite3_tokenizer_module const**ppModule
113924 ){
113925   *ppModule = &icuTokenizerModule;
113926 }
113927
113928 #endif /* defined(SQLITE_ENABLE_ICU) */
113929 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
113930
113931 /************** End of fts3_icu.c ********************************************/