Logo Search packages:      
Sourcecode: paraview version File versions  Download package

vtk_sqlite3.c

/* changed by awilson: replace all instances of 'sqlite' with 'vtk_sqlite' */

/******************************************************************************
** This file is an amalgamation of many separate C source files from SQLite
** version 3.4.1.  By combining all the individual C code files into this 
** single large file, the entire code can be compiled as a one translation
** unit.  This allows many compilers to do optimizations that would not be
** possible if the files were compiled separately.  Performance improvements
** of 5% are more are commonly seen when SQLite is compiled as a single
** translation unit.
**
** This file is all you need to compile SQLite.  To use SQLite in other
** programs, you need this file and the "vtk_sqlite3.h" header file that defines
** the programming interface to the SQLite library.  (If you do not have 
** the "vtk_sqlite3.h" header file at hand, you will find a copy in the first
** 2702 lines past this header comment.)  Additional code files may be
** needed if you want a wrapper to interface SQLite with your choice of
** programming language.  The code for the "vtk_sqlite3" command-line shell
** is also in a separate file.  This file contains only code for the core
** SQLite library.
**
** This amalgamation was generated on 2007-07-20 11:05:39 UTC.
*/
#define VTK_SQLITE_OMIT_LOAD_EXTENSION
#if defined(_MSC_VER)
#pragma warning( disable: 4127 ) /* conditional expression is constant */
#pragma warning( disable: 4049 ) /* too many lines in file */
#endif
#if defined(__BORLANDC__)
#pragma warn -8004 /* assigned a value that is never used */
#pragma warn -8008 /* condition is always true */
#pragma warn -8066 /* unreachable code */
#pragma warn -8019 /* code has no effect */
#endif

#define VTK_SQLITE_AMALGAMATION 1
#ifndef VTK_SQLITE_PRIVATE
# define VTK_SQLITE_PRIVATE static
#endif
#ifndef VTK_SQLITE_API
# define VTK_SQLITE_API
#endif
/************** Begin file vtk_sqlite3.h *****************************************/
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the interface that the Vtk_Sqlite library
** presents to client programs.  If a C-function, structure, datatype,
** or constant definition does not appear in this file, then it is
** not a published API of Vtk_Sqlite, is subject to change without
** notice, and should not be referenced by programs that use Vtk_Sqlite.
**
** Some of the definitions that are in this file are marked as
** "experimental".  Experimental interfaces are normally new
** features recently added to Vtk_Sqlite.  We do not anticipate changes 
** to experimental interfaces but reserve to make minor changes if
** experience from use "in the wild" suggest such changes are prudent.
**
** The official C-language API documentation for Vtk_Sqlite is derived
** from comments in this file.  This file is the authoritative source
** on how Vtk_Sqlite interfaces are suppose to operate.
**
** The name of this file under configuration management is "vtk_sqlite.h.in".
** The makefile makes some minor changes to this file (such as inserting
** the version number) and changes its name to "vtk_sqlite3.h" as
** part of the build process.
**
** @(#) $Id: vtk_sqlite3.c,v 1.15 2007/09/20 18:33:36 king Exp $
*/
#ifndef _VTK_SQLITE3_H_
#define _VTK_SQLITE3_H_
#include <stdarg.h>     /* Needed for the definition of va_list */

/*
** Make sure we can call this stuff from C++.
*/
#if 0
extern "C" {
#endif

/*
** Make sure these symbols where not defined by some previous header
** file.
*/
#ifdef VTK_SQLITE_VERSION
# undef VTK_SQLITE_VERSION
#endif
#ifdef VTK_SQLITE_VERSION_NUMBER
# undef VTK_SQLITE_VERSION_NUMBER
#endif

/*
** CAPI3REF: Compile-Time Library Version Numbers
**
** The version of the Vtk_Sqlite library is contained in the vtk_sqlite3.h
** header file in a #define named VTK_SQLITE_VERSION.  The VTK_SQLITE_VERSION
** macro resolves to a string constant.
**
** The format of the version string is "X.Y.Z", where
** X is the major version number, Y is the minor version number and Z
** is the release number.  The X.Y.Z might be followed by "alpha" or "beta".
** For example "3.1.1beta".
**
** The X value is always 3 in Vtk_Sqlite.  The X value only changes when
** backwards compatibility is broken and we intend to never break
** backwards compatibility.  The Y value only changes when
** there are major feature enhancements that are forwards compatible
** but not backwards compatible.  The Z value is incremented with
** each release but resets back to 0 when Y is incremented.
**
** The VTK_SQLITE_VERSION_NUMBER is an integer with the value 
** (X*1000000 + Y*1000 + Z). For example, for version "3.1.1beta", 
** VTK_SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using 
** version 3.1.1 or greater at compile time, programs may use the test 
** (VTK_SQLITE_VERSION_NUMBER>=3001001).
**
** See also: [vtk_sqlite3_libversion()] and [vtk_sqlite3_libversion_number()].
*/
#define VTK_SQLITE_VERSION         "3.4.1"
#define VTK_SQLITE_VERSION_NUMBER 3004001

/*
** CAPI3REF: Run-Time Library Version Numbers
**
** These routines return values equivalent to the header constants
** [VTK_SQLITE_VERSION] and [VTK_SQLITE_VERSION_NUMBER].  The values returned
** by this routines should only be different from the header values
** if you compile your program using an vtk_sqlite3.h header from a
** different version of Vtk_Sqlite that the version of the library you
** link against.
**
** The vtk_sqlite3_version[] string constant contains the text of the
** [VTK_SQLITE_VERSION] string.  The vtk_sqlite3_libversion() function returns
** a poiner to the vtk_sqlite3_version[] string constant.  The function
** is provided for DLL users who can only access functions and not
** constants within the DLL.
*/
extern const char vtk_sqlite3_version[];
VTK_SQLITE_API const char *vtk_sqlite3_libversion(void);
int vtk_sqlite3_libversion_number(void);

/*
** CAPI3REF: Database Connection Handle
**
** Each open Vtk_Sqlite database is represented by pointer to an instance of the
** opaque structure named "vtk_sqlite3".  It is useful to think of an vtk_sqlite3
** pointer as an object.  The [vtk_sqlite3_open] interface is its constructor
** and [vtk_sqlite3_close] is its destructor.  There are many other interfaces
** (such as [vtk_sqlite3_prepare_v2], [vtk_sqlite3_create_function], and
** [vtk_sqlite3_busy_timeout] to name but three) that are methods on this
** object.
*/
typedef struct vtk_sqlite3 vtk_sqlite3;


/*
** CAPI3REF: 64-Bit Integer Types
**
** Some compilers do not support the "long long" datatype.  So we have
** to do compiler-specific typedefs for 64-bit signed and unsigned integers.
**
** Many Vtk_Sqlite interface functions require a 64-bit integer arguments.
** Those interfaces are declared using this typedef.
*/
#ifdef VTK_SQLITE_INT64_TYPE
  typedef VTK_SQLITE_INT64_TYPE vtk_sqlite_int64;
  typedef unsigned VTK_SQLITE_INT64_TYPE vtk_sqlite_uint64;
#elif defined(_MSC_VER) || defined(__BORLANDC__)
  typedef __int64 vtk_sqlite_int64;
  typedef unsigned __int64 vtk_sqlite_uint64;
#else
  typedef long long int vtk_sqlite_int64;
  typedef unsigned long long int vtk_sqlite_uint64;
#endif

/*
** If compiling for a processor that lacks floating point support,
** substitute integer for floating-point
*/
#ifdef VTK_SQLITE_OMIT_FLOATING_POINT
# define double vtk_sqlite_int64
#endif

/*
** CAPI3REF: Closing A Database Connection
**
** Call this function with a pointer to a structure that was previously
** returned from [vtk_sqlite3_open()] and the corresponding database will by
** closed.
**
** All SQL statements prepared using [vtk_sqlite3_prepare_v2()] or
** [vtk_sqlite3_prepare16_v2()] must be destroyed using [vtk_sqlite3_finalize()]
** before this routine is called. Otherwise, VTK_SQLITE_BUSY is returned and the
** database connection remains open.
*/
VTK_SQLITE_API int vtk_sqlite3_close(vtk_sqlite3 *);

/*
** The type for a callback function.
** This is legacy and deprecated.  It is included for historical
** compatibility and is not documented.
*/
typedef int (*vtk_sqlite3_callback)(void*,int,char**, char**);

/*
** CAPI3REF: One-Step Query Execution Interface
**
** This interface is used to do a one-time evaluatation of zero
** or more SQL statements.  UTF-8 text of the SQL statements to
** be evaluted is passed in as the second parameter.  The statements
** are prepared one by one using [vtk_sqlite3_prepare()], evaluated
** using [vtk_sqlite3_step()], then destroyed using [vtk_sqlite3_finalize()].
**
** If one or more of the SQL statements are queries, then
** the callback function specified by the 3rd parameter is
** invoked once for each row of the query result.  This callback
** should normally return 0.  If the callback returns a non-zero
** value then the query is aborted, all subsequent SQL statements
** are skipped and the vtk_sqlite3_exec() function returns the VTK_SQLITE_ABORT.
**
** The 4th parameter to this interface is an arbitrary pointer that is
** passed through to the callback function as its first parameter.
**
** The 2nd parameter to the callback function is the number of
** columns in the query result.  The 3rd parameter to the callback
** is an array of strings holding the values for each column
** as extracted using [vtk_sqlite3_column_text()].
** The 4th parameter to the callback is an array of strings
** obtained using [vtk_sqlite3_column_name()] and holding
** the names of each column.
**
** The callback function may be NULL, even for queries.  A NULL
** callback is not an error.  It just means that no callback
** will be invoked.
**
** If an error occurs while parsing or evaluating the SQL (but
** not while executing the callback) then an appropriate error
** message is written into memory obtained from [vtk_sqlite3_malloc()] and
** *errmsg is made to point to that message.  The calling function
** is responsible for freeing the memory that holds the error
** message.   Use [vtk_sqlite3_free()] for this.  If errmsg==NULL,
** then no error message is ever written.
**
** The return value is is VTK_SQLITE_OK if there are no errors and
** some other [VTK_SQLITE_OK | return code] if there is an error.  
** The particular return value depends on the type of error. 
**
*/
VTK_SQLITE_API int vtk_sqlite3_exec(
  vtk_sqlite3*,                                  /* An open database */
  const char *sql,                           /* SQL to be evaluted */
  int (*callback)(void*,int,char**,char**),  /* Callback function */
  void *,                                    /* 1st argument to callback */
  char **errmsg                              /* Error msg written here */
);

/*
** CAPI3REF: Result Codes
** KEYWORDS: VTK_SQLITE_OK
**
** Many Vtk_Sqlite functions return an integer result code from the set shown
** above in order to indicates success or failure.
**
** The result codes above are the only ones returned by Vtk_Sqlite in its
** default configuration.  However, the [vtk_sqlite3_extended_result_codes()]
** API can be used to set a database connectoin to return more detailed
** result codes.
**
** See also: [VTK_SQLITE_IOERR_READ | extended result codes]
**
*/
#define VTK_SQLITE_OK           0   /* Successful result */
/* beginning-of-error-codes */
#define VTK_SQLITE_ERROR        1   /* SQL error or missing database */
#define VTK_SQLITE_INTERNAL     2   /* NOT USED. Internal logic error in Vtk_Sqlite */
#define VTK_SQLITE_PERM         3   /* Access permission denied */
#define VTK_SQLITE_ABORT        4   /* Callback routine requested an abort */
#define VTK_SQLITE_BUSY         5   /* The database file is locked */
#define VTK_SQLITE_LOCKED       6   /* A table in the database is locked */
#define VTK_SQLITE_NOMEM        7   /* A malloc() failed */
#define VTK_SQLITE_READONLY     8   /* Attempt to write a readonly database */
#define VTK_SQLITE_INTERRUPT    9   /* Operation terminated by vtk_sqlite3_interrupt()*/
#define VTK_SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
#define VTK_SQLITE_CORRUPT     11   /* The database disk image is malformed */
#define VTK_SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
#define VTK_SQLITE_FULL        13   /* Insertion failed because database is full */
#define VTK_SQLITE_CANTOPEN    14   /* Unable to open the database file */
#define VTK_SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
#define VTK_SQLITE_EMPTY       16   /* Database is empty */
#define VTK_SQLITE_SCHEMA      17   /* The database schema changed */
#define VTK_SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
#define VTK_SQLITE_CONSTRAINT  19   /* Abort due to contraint violation */
#define VTK_SQLITE_MISMATCH    20   /* Data type mismatch */
#define VTK_SQLITE_MISUSE      21   /* Library used incorrectly */
#define VTK_SQLITE_NOLFS       22   /* Uses OS features not supported on host */
#define VTK_SQLITE_AUTH        23   /* Authorization denied */
#define VTK_SQLITE_FORMAT      24   /* Auxiliary database format error */
#define VTK_SQLITE_RANGE       25   /* 2nd parameter to vtk_sqlite3_bind out of range */
#define VTK_SQLITE_NOTADB      26   /* File opened that is not a database file */
#define VTK_SQLITE_ROW         100  /* vtk_sqlite3_step() has another row ready */
#define VTK_SQLITE_DONE        101  /* vtk_sqlite3_step() has finished executing */
/* end-of-error-codes */

/*
** CAPI3REF: Extended Result Codes
**
** In its default configuration, Vtk_Sqlite API routines return one of 26 integer
** result codes described at result-codes.  However, experience has shown that
** many of these result codes are too course-grained.  They do not provide as
** much information about problems as users might like.  In an effort to
** address this, newer versions of Vtk_Sqlite (version 3.3.8 and later) include
** support for additional result codes that provide more detailed information
** about errors.  The extended result codes are enabled (or disabled) for 
** each database
** connection using the [vtk_sqlite3_extended_result_codes()] API.
** 
** Some of the available extended result codes are listed above.
** We expect the number of extended result codes will be expand
** over time.  Software that uses extended result codes should expect
** to see new result codes in future releases of Vtk_Sqlite.
** 
** The symbolic name for an extended result code always contains a related
** primary result code as a prefix.  Primary result codes contain a single
** "_" character.  Extended result codes contain two or more "_" characters.
** The numeric value of an extended result code can be converted to its
** corresponding primary result code by masking off the lower 8 bytes.
**
** The VTK_SQLITE_OK result code will never be extended.  It will always
** be exactly zero.
*/
#define VTK_SQLITE_IOERR_READ          (VTK_SQLITE_IOERR | (1<<8))
#define VTK_SQLITE_IOERR_SHORT_READ    (VTK_SQLITE_IOERR | (2<<8))
#define VTK_SQLITE_IOERR_WRITE         (VTK_SQLITE_IOERR | (3<<8))
#define VTK_SQLITE_IOERR_FSYNC         (VTK_SQLITE_IOERR | (4<<8))
#define VTK_SQLITE_IOERR_DIR_FSYNC     (VTK_SQLITE_IOERR | (5<<8))
#define VTK_SQLITE_IOERR_TRUNCATE      (VTK_SQLITE_IOERR | (6<<8))
#define VTK_SQLITE_IOERR_FSTAT         (VTK_SQLITE_IOERR | (7<<8))
#define VTK_SQLITE_IOERR_UNLOCK        (VTK_SQLITE_IOERR | (8<<8))
#define VTK_SQLITE_IOERR_RDLOCK        (VTK_SQLITE_IOERR | (9<<8))
#define VTK_SQLITE_IOERR_DELETE        (VTK_SQLITE_IOERR | (10<<8))
#define VTK_SQLITE_IOERR_BLOCKED       (VTK_SQLITE_IOERR | (11<<8))

/*
** CAPI3REF: Enable Or Disable Extended Result Codes
**
** This routine enables or disables the
** [VTK_SQLITE_IOERR_READ | extended result codes] feature.
** By default, Vtk_Sqlite API routines return one of only 26 integer
** [VTK_SQLITE_OK | result codes].  When extended result codes
** are enabled by this routine, the repetoire of result codes can be
** much larger and can (hopefully) provide more detailed information
** about the cause of an error.
**
** The second argument is a boolean value that turns extended result
** codes on and off.  Extended result codes are off by default for
** backwards compatibility with older versions of Vtk_Sqlite.
*/
int vtk_sqlite3_extended_result_codes(vtk_sqlite3*, int onoff);

/*
** CAPI3REF: Last Insert Rowid
**
** Each entry in an Vtk_Sqlite table has a unique 64-bit signed integer key
** called the "rowid". The rowid is always available as an undeclared
** column named ROWID, OID, or _ROWID_.  If the table has a column of
** type INTEGER PRIMARY KEY then that column is another an alias for the
** rowid.
**
** This routine returns the rowid of the most recent INSERT into
** the database from the database connection given in the first 
** argument.  If no inserts have ever occurred on this database
** connection, zero is returned.
**
** If an INSERT occurs within a trigger, then the rowid of the
** inserted row is returned by this routine as long as the trigger
** is running.  But once the trigger terminates, the value returned
** by this routine reverts to the last value inserted before the
** trigger fired.
*/
vtk_sqlite_int64 vtk_sqlite3_last_insert_rowid(vtk_sqlite3*);

/*
** CAPI3REF: Count The Number Of Rows Modified
**
** This function returns the number of database rows that were changed
** (or inserted or deleted) by the most recent SQL statement.  Only
** changes that are directly specified by the INSERT, UPDATE, or
** DELETE statement are counted.  Auxiliary changes caused by
** triggers are not counted.  Use the [vtk_sqlite3_total_changes()] function
** to find the total number of changes including changes caused by triggers.
**
** Within the body of a trigger, the vtk_sqlite3_changes() interface can be
** called to find the number of
** changes in the most recently completed INSERT, UPDATE, or DELETE
** statement within the body of the trigger.
**
** All changes are counted, even if they were later undone by a
** ROLLBACK or ABORT.  Except, changes associated with creating and
** dropping tables are not counted.
**
** If a callback invokes [vtk_sqlite3_exec()] or [vtk_sqlite3_step()] recursively,
** then the changes in the inner, recursive call are counted together
** with the changes in the outer call.
**
** Vtk_Sqlite implements the command "DELETE FROM table" without a WHERE clause
** by dropping and recreating the table.  (This is much faster than going
** through and deleting individual elements from the table.)  Because of
** this optimization, the change count for "DELETE FROM table" will be
** zero regardless of the number of elements that were originally in the
** table. To get an accurate count of the number of rows deleted, use
** "DELETE FROM table WHERE 1" instead.
*/
VTK_SQLITE_API int vtk_sqlite3_changes(vtk_sqlite3*);

/*
** CAPI3REF: Total Number Of Rows Modified
***
** This function returns the number of database rows that have been
** modified by INSERT, UPDATE or DELETE statements since the database handle
** was opened. This includes UPDATE, INSERT and DELETE statements executed
** as part of trigger programs. All changes are counted as soon as the
** statement that makes them is completed (when the statement handle is
** passed to [vtk_sqlite3_reset()] or [vtk_sqlite_finalise()]).
**
** See also the [vtk_sqlite3_change()] interface.
**
** Vtk_Sqlite implements the command "DELETE FROM table" without a WHERE clause
** by dropping and recreating the table.  (This is much faster than going
** through and deleting individual elements form the table.)  Because of
** this optimization, the change count for "DELETE FROM table" will be
** zero regardless of the number of elements that were originally in the
** table. To get an accurate count of the number of rows deleted, use
** "DELETE FROM table WHERE 1" instead.
*/
int vtk_sqlite3_total_changes(vtk_sqlite3*);

/*
** CAPI3REF: Interrupt A Long-Running Query
**
** This function causes any pending database operation to abort and
** return at its earliest opportunity.  This routine is typically
** called in response to a user action such as pressing "Cancel"
** or Ctrl-C where the user wants a long query operation to halt
** immediately.
**
** It is safe to call this routine from a thread different from the
** thread that is currently running the database operation.
**
** The SQL operation that is interrupted will return [VTK_SQLITE_INTERRUPT].
** If an interrupted operation was an update that is inside an
** explicit transaction, then the entire transaction will be rolled
** back automatically.
*/
VTK_SQLITE_API void vtk_sqlite3_interrupt(vtk_sqlite3*);

/*
** CAPI3REF: Determine If An SQL Statement Is Complete
**
** These functions return true if the given input string comprises
** one or more complete SQL statements. For the vtk_sqlite3_complete() call,
** the parameter must be a nul-terminated UTF-8 string. For
** vtk_sqlite3_complete16(), a nul-terminated machine byte order UTF-16 string
** is required.
**
** These routines are useful for command-line input to determine if the
** currently entered text forms one or more complete SQL statements or
** if additional input is needed before sending the statements into
** Vtk_Sqlite for parsing. The algorithm is simple.  If the 
** last token other than spaces and comments is a semicolon, then return 
** true.  Actually, the algorithm is a little more complicated than that
** in order to deal with triggers, but the basic idea is the same:  the
** statement is not complete unless it ends in a semicolon.
*/
VTK_SQLITE_API int vtk_sqlite3_complete(const char *sql);
VTK_SQLITE_API int vtk_sqlite3_complete16(const void *sql);

/*
** CAPI3REF: Register A Callback To Handle VTK_SQLITE_BUSY Errors
**
** This routine identifies a callback function that might be invoked
** whenever an attempt is made to open a database table 
** that another thread or process has locked.
** If the busy callback is NULL, then [VTK_SQLITE_BUSY]
** (or sometimes [VTK_SQLITE_IOERR_BLOCKED])
** is returned immediately upon encountering the lock.
** If the busy callback is not NULL, then the
** callback will be invoked with two arguments.  The
** first argument to the handler is a copy of the void* pointer which
** is the third argument to this routine.  The second argument to
** the handler is the number of times that the busy handler has
** been invoked for this locking event. If the
** busy callback returns 0, then no additional attempts are made to
** access the database and [VTK_SQLITE_BUSY] or [VTK_SQLITE_IOERR_BLOCKED] is returned.
** If the callback returns non-zero, then another attempt is made to open the
** database for reading and the cycle repeats.
**
** The presence of a busy handler does not guarantee that
** it will be invoked when there is lock contention.
** If Vtk_Sqlite determines that invoking the busy handler could result in
** a deadlock, it will return [VTK_SQLITE_BUSY] instead.
** Consider a scenario where one process is holding a read lock that
** it is trying to promote to a reserved lock and
** a second process is holding a reserved lock that it is trying
** to promote to an exclusive lock.  The first process cannot proceed
** because it is blocked by the second and the second process cannot
** proceed because it is blocked by the first.  If both processes
** invoke the busy handlers, neither will make any progress.  Therefore,
** Vtk_Sqlite returns [VTK_SQLITE_BUSY] for the first process, hoping that this
** will induce the first process to release its read lock and allow
** the second process to proceed.
**
** The default busy callback is NULL.
**
** The [VTK_SQLITE_BUSY] error is converted to [VTK_SQLITE_IOERR_BLOCKED] when
** Vtk_Sqlite is in the middle of a large transaction where all the
** changes will not fit into the in-memory cache.  Vtk_Sqlite will
** already hold a RESERVED lock on the database file, but it needs
** to promote this lock to EXCLUSIVE so that it can spill cache
** pages into the database file without harm to concurrent
** readers.  If it is unable to promote the lock, then the in-memory
** cache will be left in an inconsistent state and so the error
** code is promoted from the relatively benign [VTK_SQLITE_BUSY] to
** the more severe [VTK_SQLITE_IOERR_BLOCKED].  This error code promotion
** forces an automatic rollback of the changes. See the
** <a href="http://www.vtk_sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError">
** CorruptionFollowingBusyError</a> wiki page for a discussion of why
** this is important.
**      
** Vtk_Sqlite is re-entrant, so the busy handler may start a new query. 
** (It is not clear why anyone would every want to do this, but it
** is allowed, in theory.)  But the busy handler may not close the
** database.  Closing the database from a busy handler will delete 
** data structures out from under the executing query and will 
** probably result in a segmentation fault or other runtime error.
**
** There can only be a single busy handler defined for each database
** connection.  Setting a new busy handler clears any previous one.
** Note that calling [vtk_sqlite3_busy_timeout()] will also set or clear
** the busy handler.
*/
int vtk_sqlite3_busy_handler(vtk_sqlite3*, int(*)(void*,int), void*);

/*
** CAPI3REF: Set A Busy Timeout
**
** This routine sets a busy handler that sleeps for a while when a
** table is locked.  The handler will sleep multiple times until 
** at least "ms" milliseconds of sleeping have been done.  After
** "ms" milliseconds of sleeping, the handler returns 0 which
** causes [vtk_sqlite3_step()] to return [VTK_SQLITE_BUSY] or [VTK_SQLITE_IOERR_BLOCKED].
**
** Calling this routine with an argument less than or equal to zero
** turns off all busy handlers.
**
** There can only be a single busy handler for a particular database
** connection.  If another busy handler was defined  
** (using [vtk_sqlite3_busy_handler()]) prior to calling
** this routine, that other busy handler is cleared.
*/
int vtk_sqlite3_busy_timeout(vtk_sqlite3*, int ms);

/*
** CAPI3REF: Convenience Routines For Running Queries
**
** This next routine is a convenience wrapper around [vtk_sqlite3_exec()].
** Instead of invoking a user-supplied callback for each row of the
** result, this routine remembers each row of the result in memory
** obtained from [vtk_sqlite3_malloc()], then returns all of the result after the
** query has finished. 
**
** As an example, suppose the query result where this table:
**
** <pre>
**        Name        | Age
**        -----------------------
**        Alice       | 43
**        Bob         | 28
**        Cindy       | 21
** </pre>
**
** If the 3rd argument were &azResult then after the function returns
** azResult will contain the following data:
**
** <pre>
**        azResult[0] = "Name";
**        azResult[1] = "Age";
**        azResult[2] = "Alice";
**        azResult[3] = "43";
**        azResult[4] = "Bob";
**        azResult[5] = "28";
**        azResult[6] = "Cindy";
**        azResult[7] = "21";
** </pre>
**
** Notice that there is an extra row of data containing the column
** headers.  But the *nrow return value is still 3.  *ncolumn is
** set to 2.  In general, the number of values inserted into azResult
** will be ((*nrow) + 1)*(*ncolumn).
**
** After the calling function has finished using the result, it should 
** pass the result data pointer to vtk_sqlite3_free_table() in order to 
** release the memory that was malloc-ed.  Because of the way the 
** [vtk_sqlite3_malloc()] happens, the calling function must not try to call 
** [vtk_sqlite3_free()] directly.  Only [vtk_sqlite3_free_table()] is able to release 
** the memory properly and safely.
**
** The return value of this routine is the same as from [vtk_sqlite3_exec()].
*/
int vtk_sqlite3_get_table(
  vtk_sqlite3*,              /* An open database */
  const char *sql,       /* SQL to be executed */
  char ***resultp,       /* Result written to a char *[]  that this points to */
  int *nrow,             /* Number of result rows written here */
  int *ncolumn,          /* Number of result columns written here */
  char **errmsg          /* Error msg written here */
);
void vtk_sqlite3_free_table(char **result);

/*
** CAPI3REF: Formatted String Printing Functions
**
** These routines are workalikes of the "printf()" family of functions
** from the standard C library.
**
** The vtk_sqlite3_mprintf() and vtk_sqlite3_vmprintf() routines write their
** results into memory obtained from [vtk_sqlite_malloc()].
** The strings returned by these two routines should be
** released by [vtk_sqlite3_free()].  Both routines return a
** NULL pointer if [vtk_sqlite3_malloc()] is unable to allocate enough
** memory to hold the resulting string.
**
** In vtk_sqlite3_snprintf() routine is similar to "snprintf()" from
** the standard C library.  The result is written into the
** buffer supplied as the second parameter whose size is given by
** the first parameter.  Note that the order of the
** first two parameters is reversed from snprintf().  This is an
** historical accident that cannot be fixed without breaking
** backwards compatibility.  Note also that vtk_sqlite3_snprintf()
** returns a pointer to its buffer instead of the number of
** characters actually written into the buffer.  We admit that
** the number of characters written would be a more useful return
** value but we cannot change the implementation of vtk_sqlite3_snprintf()
** now without breaking compatibility.
**
** As long as the buffer size is greater than zero, vtk_sqlite3_snprintf()
** guarantees that the buffer is always zero-terminated.  The first
** parameter "n" is the total size of the buffer, including space for
** the zero terminator.  So the longest string that can be completely
** written will be n-1 characters.
**
** These routines all implement some additional formatting
** options that are useful for constructing SQL statements.
** All of the usual printf formatting options apply.  In addition, there
** is are "%q" and "%Q" options.
**
** The %q option works like %s in that it substitutes a null-terminated
** string from the argument list.  But %q also doubles every '\'' character.
** %q is designed for use inside a string literal.  By doubling each '\''
** character it escapes that character and allows it to be inserted into
** the string.
**
** For example, so some string variable contains text as follows:
**
** <blockquote><pre>
**  char *zText = "It's a happy day!";
** </pre></blockquote>
**
** One can use this text in an SQL statement as follows:
**
** <blockquote><pre>
**  char *zSQL = vtk_sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
**  vtk_sqlite3_exec(db, zSQL, 0, 0, 0);
**  vtk_sqlite3_free(zSQL);
** </pre></blockquote>
**
** Because the %q format string is used, the '\'' character in zText
** is escaped and the SQL generated is as follows:
**
** <blockquote><pre>
**  INSERT INTO table1 VALUES('It''s a happy day!')
** </pre></blockquote>
**
** This is correct.  Had we used %s instead of %q, the generated SQL
** would have looked like this:
**
** <blockquote><pre>
**  INSERT INTO table1 VALUES('It's a happy day!');
** </pre></blockquote>
**
** This second example is an SQL syntax error.  As a general rule you
** should always use %q instead of %s when inserting text into a string 
** literal.
**
** The %Q option works like %q except it also adds single quotes around
** the outside of the total string.  Or if the parameter in the argument
** list is a NULL pointer, %Q substitutes the text "NULL" (without single
** quotes) in place of the %Q option.  So, for example, one could say:
**
** <blockquote><pre>
**  char *zSQL = vtk_sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
**  vtk_sqlite3_exec(db, zSQL, 0, 0, 0);
**  vtk_sqlite3_free(zSQL);
** </pre></blockquote>
**
** The code above will render a correct SQL statement in the zSQL
** variable even if the zText variable is a NULL pointer.
*/
VTK_SQLITE_API char *vtk_sqlite3_mprintf(const char*,...);
VTK_SQLITE_API char *vtk_sqlite3_vmprintf(const char*, va_list);
VTK_SQLITE_API char *vtk_sqlite3_snprintf(int,char*,const char*, ...);

/*
** CAPI3REF: Memory Allocation Functions
**
** Vtk_Sqlite uses its own memory allocator.  On some installations, this
** memory allocator is identical to the standard malloc()/realloc()/free()
** and can be used interchangable.  On others, the implementations are
** different.  For maximum portability, it is best not to mix calls
** to the standard malloc/realloc/free with the vtk_sqlite versions.
*/
VTK_SQLITE_API void *vtk_sqlite3_malloc(int);
VTK_SQLITE_API void *vtk_sqlite3_realloc(void*, int);
VTK_SQLITE_API void vtk_sqlite3_free(void*);

/*
** CAPI3REF: Compile-Time Authorization Callbacks
***
** This routine registers a authorizer callback with the Vtk_Sqlite library.  
** The authorizer callback is invoked as SQL statements are being compiled
** by [vtk_sqlite3_prepare()] or its variants [vtk_sqlite3_prepare_v2()],
** [vtk_sqlite3_prepare16()] and [vtk_sqlite3_prepare16_v2()].  At various
** points during the compilation process, as logic is being created
** to perform various actions, the authorizer callback is invoked to
** see if those actions are allowed.  The authorizer callback should
** return VTK_SQLITE_OK to allow the action, [VTK_SQLITE_IGNORE] to disallow the
** specific action but allow the SQL statement to continue to be
** compiled, or [VTK_SQLITE_DENY] to cause the entire SQL statement to be
** rejected with an error.  
**
** Depending on the action, the [VTK_SQLITE_IGNORE] and [VTK_SQLITE_DENY] return
** codes might mean something different or they might mean the same
** thing.  If the action is, for example, to perform a delete opertion,
** then [VTK_SQLITE_IGNORE] and [VTK_SQLITE_DENY] both cause the statement compilation
** to fail with an error.  But if the action is to read a specific column
** from a specific table, then [VTK_SQLITE_DENY] will cause the entire
** statement to fail but [VTK_SQLITE_IGNORE] will cause a NULL value to be
** read instead of the actual column value.
**
** The first parameter to the authorizer callback is a copy of
** the third parameter to the vtk_sqlite3_set_authorizer() interface.
** The second parameter to the callback is an integer 
** [VTK_SQLITE_COPY | action code] that specifies the particular action
** to be authorized.  The available action codes are
** [VTK_SQLITE_COPY | documented separately].  The third through sixth
** parameters to the callback are strings that contain additional
** details about the action to be authorized.
**
** An authorizer is used when preparing SQL statements from an untrusted
** source, to ensure that the SQL statements do not try to access data
** that they are not allowed to see, or that they do not try to
** execute malicious statements that damage the database.  For
** example, an application may allow a user to enter arbitrary
** SQL queries for evaluation by a database.  But the application does
** not want the user to be able to make arbitrary changes to the
** database.  An authorizer could then be put in place while the
** user-entered SQL is being prepared that disallows everything
** except SELECT statements.  
**
** Only a single authorizer can be in place on a database connection
** at a time.  Each call to vtk_sqlite3_set_authorizer overrides the
** previous call.  A NULL authorizer means that no authorization
** callback is invoked.  The default authorizer is NULL.
**
** Note that the authorizer callback is invoked only during 
** [vtk_sqlite3_prepare()] or its variants.  Authorization is not
** performed during statement evaluation in [vtk_sqlite3_step()].
*/
int vtk_sqlite3_set_authorizer(
  vtk_sqlite3*,
  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  void *pUserData
);

/*
** CAPI3REF: Authorizer Return Codes
**
** The [vtk_sqlite3_set_authorizer | authorizer callback function] must
** return either [VTK_SQLITE_OK] or one of these two constants in order
** to signal Vtk_Sqlite whether or not the action is permitted.  See the
** [vtk_sqlite3_set_authorizer | authorizer documentation] for additional
** information.
*/
#define VTK_SQLITE_DENY   1   /* Abort the SQL statement with an error */
#define VTK_SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */

/*
** CAPI3REF: Authorizer Action Codes
**
** The [vtk_sqlite3_set_authorizer()] interface registers a callback function
** that is invoked to authorizer certain SQL statement actions.  The
** second parameter to the callback is an integer code that specifies
** what action is being authorized.  These are the integer action codes that
** the authorizer callback may be passed.
**
** These action code values signify what kind of operation is to be 
** authorized.  The 3rd and 4th parameters to the authorization callback
** function will be parameters or NULL depending on which of these
** codes is used as the second parameter.  The 5th parameter to the
** authorizer callback is the name of the database ("main", "temp", 
** etc.) if applicable.  The 6th parameter to the authorizer callback
** is the name of the inner-most trigger or view that is responsible for
** the access attempt or NULL if this access attempt is directly from 
** top-level SQL code.
*/
/******************************************* 3rd ************ 4th ***********/
#define VTK_SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
#define VTK_SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
#define VTK_SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
#define VTK_SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
#define VTK_SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
#define VTK_SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
#define VTK_SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
#define VTK_SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
#define VTK_SQLITE_DELETE                9   /* Table Name      NULL            */
#define VTK_SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
#define VTK_SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
#define VTK_SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
#define VTK_SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
#define VTK_SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
#define VTK_SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
#define VTK_SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
#define VTK_SQLITE_DROP_VIEW            17   /* View Name       NULL            */
#define VTK_SQLITE_INSERT               18   /* Table Name      NULL            */
#define VTK_SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
#define VTK_SQLITE_READ                 20   /* Table Name      Column Name     */
#define VTK_SQLITE_SELECT               21   /* NULL            NULL            */
#define VTK_SQLITE_TRANSACTION          22   /* NULL            NULL            */
#define VTK_SQLITE_UPDATE               23   /* Table Name      Column Name     */
#define VTK_SQLITE_ATTACH               24   /* Filename        NULL            */
#define VTK_SQLITE_DETACH               25   /* Database Name   NULL            */
#define VTK_SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
#define VTK_SQLITE_REINDEX              27   /* Index Name      NULL            */
#define VTK_SQLITE_ANALYZE              28   /* Table Name      NULL            */
#define VTK_SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
#define VTK_SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
#define VTK_SQLITE_FUNCTION             31   /* Function Name   NULL            */
#define VTK_SQLITE_COPY                  0   /* No longer used */

/*
** CAPI3REF: Tracing And Profiling Functions
**
** These routines register callback functions that can be used for
** tracing and profiling the execution of SQL statements.
** The callback function registered by vtk_sqlite3_trace() is invoked
** at the first [vtk_sqlite3_step()] for the evaluation of an SQL statement.
** The callback function registered by vtk_sqlite3_profile() is invoked
** as each SQL statement finishes and includes
** information on how long that statement ran.
**
** The vtk_sqlite3_profile() API is currently considered experimental and
** is subject to change.
*/
VTK_SQLITE_API void *vtk_sqlite3_trace(vtk_sqlite3*, void(*xTrace)(void*,const char*), void*);
VTK_SQLITE_API void *vtk_sqlite3_profile(vtk_sqlite3*,
   void(*xProfile)(void*,const char*,vtk_sqlite_uint64), void*);

/*
** CAPI3REF: Query Progress Callbacks
**
** This routine configures a callback function - the progress callback - that
** is invoked periodically during long running calls to [vtk_sqlite3_exec()],
** [vtk_sqlite3_step()] and [vtk_sqlite3_get_table()].  An example use for this 
** interface is to keep a GUI updated during a large query.
**
** The progress callback is invoked once for every N virtual machine opcodes,
** where N is the second argument to this function. The progress callback
** itself is identified by the third argument to this function. The fourth
** argument to this function is a void pointer passed to the progress callback
** function each time it is invoked.
**
** If a call to [vtk_sqlite3_exec()], [vtk_sqlite3_step()], or [vtk_sqlite3_get_table()]
** results in fewer than N opcodes being executed, then the progress 
** callback is never invoked.
** 
** Only a single progress callback function may be registered for each
** open database connection.  Every call to vtk_sqlite3_progress_handler()
** overwrites the results of the previous call.
** To remove the progress callback altogether, pass NULL as the third
** argument to this function.
**
** If the progress callback returns a result other than 0, then the current 
** query is immediately terminated and any database changes rolled back.
** The containing [vtk_sqlite3_exec()], [vtk_sqlite3_step()], or
** [vtk_sqlite3_get_table()] call returns VTK_SQLITE_INTERRUPT.   This feature
** can be used, for example, to implement the "Cancel" button on a
** progress dialog box in a GUI.
*/
void vtk_sqlite3_progress_handler(vtk_sqlite3*, int, int(*)(void*), void*);

/*
** CAPI3REF: Opening A New Database Connection
**
** Open the vtk_sqlite database file "filename".  The "filename" is UTF-8
** encoded for vtk_sqlite3_open() and UTF-16 encoded in the native byte order
** for vtk_sqlite3_open16().  An [vtk_sqlite3*] handle is returned in *ppDb, even
** if an error occurs. If the database is opened (or created) successfully,
** then VTK_SQLITE_OK is returned. Otherwise an error code is returned. The
** vtk_sqlite3_errmsg() or vtk_sqlite3_errmsg16()  routines can be used to obtain
** an English language description of the error.
**
** If the database file does not exist, then a new database will be created
** as needed.  The default encoding for the database will be UTF-8 if
** vtk_sqlite3_open() is called and UTF-16 if vtk_sqlite3_open16 is used.
**
** Whether or not an error occurs when it is opened, resources associated
** with the [vtk_sqlite3*] handle should be released by passing it to
** vtk_sqlite3_close() when it is no longer required.
**
** Note to windows users:  The encoding used for the filename argument
** of vtk_sqlite3_open() must be UTF-8, not whatever codepage is currently
** defined.  Filenames containing international characters must be converted
** to UTF-8 prior to passing them into vtk_sqlite3_open().
*/
VTK_SQLITE_API int vtk_sqlite3_open(
  const char *filename,   /* Database filename (UTF-8) */
  vtk_sqlite3 **ppDb          /* OUT: Vtk_Sqlite db handle */
);
VTK_SQLITE_API int vtk_sqlite3_open16(
  const void *filename,   /* Database filename (UTF-16) */
  vtk_sqlite3 **ppDb          /* OUT: Vtk_Sqlite db handle */
);

/*
** CAPI3REF: Error Codes And Messages
**
** The vtk_sqlite3_errcode() interface returns the numeric
** [VTK_SQLITE_OK | result code] or [VTK_SQLITE_IOERR_READ | extended result code]
** for the most recent failed vtk_sqlite3_* API call associated
** with [vtk_sqlite3] handle 'db'.  If a prior API call failed but the
** most recent API call succeeded, the return value from vtk_sqlite3_errcode()
** is undefined. 
**
** The vtk_sqlite3_errmsg() and vtk_sqlite3_errmsg16() return English-langauge
** text that describes the error, as either UTF8 or UTF16 respectively.
** Memory to hold the error message string is managed internally.  The 
** string may be overwritten or deallocated by subsequent calls to Vtk_Sqlite
** interface functions.
**
** Calls to many vtk_sqlite3_* functions set the error code and string returned
** by [vtk_sqlite3_errcode()], [vtk_sqlite3_errmsg()], and [vtk_sqlite3_errmsg16()]
** (overwriting the previous values). Note that calls to [vtk_sqlite3_errcode()],
** [vtk_sqlite3_errmsg()], and [vtk_sqlite3_errmsg16()] themselves do not affect the
** results of future invocations.  Calls to API routines that do not return
** an error code (examples: [vtk_sqlite3_data_count()] or [vtk_sqlite3_mprintf()]) do
** not change the error code returned by this routine.
**
** Assuming no other intervening vtk_sqlite3_* API calls are made, the error
** code returned by this function is associated with the same error as
** the strings returned by [vtk_sqlite3_errmsg()] and [vtk_sqlite3_errmsg16()].
*/
VTK_SQLITE_API int vtk_sqlite3_errcode(vtk_sqlite3 *db);
VTK_SQLITE_API const char *vtk_sqlite3_errmsg(vtk_sqlite3*);
VTK_SQLITE_API const void *vtk_sqlite3_errmsg16(vtk_sqlite3*);

/*
** CAPI3REF: SQL Statement Object
**
** Instance of this object represent single SQL statements.  This
** is variously known as a "prepared statement" or a 
** "compiled SQL statement" or simply as a "statement".
** 
** The life of a statement object goes something like this:
**
** <ol>
** <li> Create the object using [vtk_sqlite3_prepare_v2()] or a related
**      function.
** <li> Bind values to host parameters using
**      [vtk_sqlite3_bind_blob | vtk_sqlite3_bind_* interfaces].
** <li> Run the SQL by calling [vtk_sqlite3_step()] one or more times.
** <li> Reset the statement using [vtk_sqlite3_reset()] then go back
**      to step 2.  Do this zero or more times.
** <li> Destroy the object using [vtk_sqlite3_finalize()].
** </ol>
**
** Refer to documentation on individual methods above for additional
** information.
*/
typedef struct vtk_sqlite3_stmt vtk_sqlite3_stmt;

/*
** CAPI3REF: Compiling An SQL Statement
**
** To execute an SQL query, it must first be compiled into a byte-code
** program using one of these routines. 
**
** The first argument "db" is an [vtk_sqlite3 | Vtk_Sqlite database handle] 
** obtained from a prior call to [vtk_sqlite3_open()] or [vtk_sqlite3_open16()].
** The second argument "zSql" is the statement to be compiled, encoded
** as either UTF-8 or UTF-16.  The vtk_sqlite3_prepare() and vtk_sqlite3_prepare_v2()
** interfaces uses UTF-8 and vtk_sqlite3_prepare16() and vtk_sqlite3_prepare16_v2()
** use UTF-16.
**
** If the nByte argument is less
** than zero, then zSql is read up to the first zero terminator.  If
** nByte is non-negative, then it is the maximum number of 
** bytes read from zSql.  When nByte is non-negative, the
** zSql string ends at either the first '\000' character or 
** until the nByte-th byte, whichever comes first.
**
** *pzTail is made to point to the first byte past the end of the first
** SQL statement in zSql.  This routine only compiles the first statement
** in zSql, so *pzTail is left pointing to what remains uncompiled.
**
** *ppStmt is left pointing to a compiled 
** [vtk_sqlite3_stmt | SQL statement structure] that can be
** executed using [vtk_sqlite3_step()].  Or if there is an error, *ppStmt may be
** set to NULL.  If the input text contained no SQL (if the input is and
** empty string or a comment) then *ppStmt is set to NULL.  The calling
** procedure is responsible for deleting the compiled SQL statement
** using [vtk_sqlite3_finalize()] after it has finished with it.
**
** On success, [VTK_SQLITE_OK] is returned.  Otherwise an 
** [VTK_SQLITE_ERROR | error code] is returned.
**
** The vtk_sqlite3_prepare_v2() and vtk_sqlite3_prepare16_v2() interfaces are
** recommended for all new programs. The two older interfaces are retained
** for backwards compatibility, but their use is discouraged.
** In the "v2" interfaces, the prepared statement
** that is returned (the [vtk_sqlite3_stmt] object) contains a copy of the 
** original SQL text. This causes the [vtk_sqlite3_step()] interface to
** behave a differently in two ways:
**
** <ol>
** <li>
** If the database schema changes, instead of returning [VTK_SQLITE_SCHEMA] as it
** always used to do, [vtk_sqlite3_step()] will automatically recompile the SQL
** statement and try to run it again.  If the schema has changed in a way
** that makes the statement no longer valid, [vtk_sqlite3_step()] will still
** return [VTK_SQLITE_SCHEMA].  But unlike the legacy behavior, [VTK_SQLITE_SCHEMA] is
** now a fatal error.  Calling [vtk_sqlite3_prepare_v2()] again will not make the
** error go away.  Note: use [vtk_sqlite3_errmsg()] to find the text of the parsing
** error that results in an [VTK_SQLITE_SCHEMA] return.
** </li>
**
** <li>
** When an error occurs, 
** [vtk_sqlite3_step()] will return one of the detailed 
** [VTK_SQLITE_ERROR | result codes] or
** [VTK_SQLITE_IOERR_READ | extended result codes] such as directly.
** The legacy behavior was that [vtk_sqlite3_step()] would only return a generic
** [VTK_SQLITE_ERROR] result code and you would have to make a second call to
** [vtk_sqlite3_reset()] in order to find the underlying cause of the problem.
** With the "v2" prepare interfaces, the underlying reason for the error is
** returned immediately.
** </li>
** </ol>
*/
VTK_SQLITE_API int vtk_sqlite3_prepare(
  vtk_sqlite3 *db,            /* Database handle */
  const char *zSql,       /* SQL statement, UTF-8 encoded */
  int nByte,              /* Maximum length of zSql in bytes. */
  vtk_sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
);
int vtk_sqlite3_prepare_v2(
  vtk_sqlite3 *db,            /* Database handle */
  const char *zSql,       /* SQL statement, UTF-8 encoded */
  int nByte,              /* Maximum length of zSql in bytes. */
  vtk_sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
);
VTK_SQLITE_API int vtk_sqlite3_prepare16(
  vtk_sqlite3 *db,            /* Database handle */
  const void *zSql,       /* SQL statement, UTF-16 encoded */
  int nByte,              /* Maximum length of zSql in bytes. */
  vtk_sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
);
int vtk_sqlite3_prepare16_v2(
  vtk_sqlite3 *db,            /* Database handle */
  const void *zSql,       /* SQL statement, UTF-16 encoded */
  int nByte,              /* Maximum length of zSql in bytes. */
  vtk_sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
);

/*
** CAPI3REF:  Dynamically Typed Value Object
**
** Vtk_Sqlite uses dynamic typing for the values it stores.  Values can 
** be integers, floating point values, strings, BLOBs, or NULL.  When
** passing around values internally, each value is represented as
** an instance of the vtk_sqlite3_value object.
*/
typedef struct Mem vtk_sqlite3_value;

/*
** CAPI3REF:  SQL Function Context Object
**
** The context in which an SQL function executes is stored in an
** vtk_sqlite3_context object.  A pointer to such an object is the
** first parameter to user-defined SQL functions.
*/
typedef struct vtk_sqlite3_context vtk_sqlite3_context;

/*
** CAPI3REF:  Binding Values To Prepared Statements
**
** In the SQL strings input to [vtk_sqlite3_prepare_v2()] and its variants,
** one or more literals can be replace by a parameter in one of these
** forms:
**
** <ul>
** <li>  ?
** <li>  ?NNN
** <li>  :AAA
** <li>  @AAA
** <li>  $VVV
** </ul>
**
** In the parameter forms shown above NNN is an integer literal,
** AAA is an alphanumeric identifier and VVV is a variable name according
** to the syntax rules of the TCL programming language.
** The values of these parameters (also called "host parameter names")
** can be set using the vtk_sqlite3_bind_*() routines defined here.
**
** The first argument to the vtk_sqlite3_bind_*() routines always is a pointer
** to the [vtk_sqlite3_stmt] object returned from [vtk_sqlite3_prepare_v2()] or
** its variants.  The second
** argument is the index of the parameter to be set.  The first parameter has
** an index of 1. When the same named parameter is used more than once, second
** and subsequent
** occurrences have the same index as the first occurrence.  The index for
** named parameters can be looked up using the
** [vtk_sqlite3_bind_parameter_name()] API if desired.  The index for "?NNN"
** parametes is the value of NNN.
** The NNN value must be between 1 and the compile-time
** parameter VTK_SQLITE_MAX_VARIABLE_NUMBER (default value: 999).
** See <a href="limits.html">limits.html</a> for additional information.
**
** The third argument is the value to bind to the parameter.
**
** In those
** routines that have a fourth argument, its value is the number of bytes
** in the parameter.  To be clear: the value is the number of bytes in the
** string, not the number of characters.  The number
** of bytes does not include the zero-terminator at the end of strings.
** If the fourth parameter is negative, the length of the string is
** number of bytes up to the first zero terminator.
**
** The fifth argument to vtk_sqlite3_bind_blob(), vtk_sqlite3_bind_text(), and
** vtk_sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
** text after Vtk_Sqlite has finished with it.  If the fifth argument is the
** special value [VTK_SQLITE_STATIC], then the library assumes that the information
** is in static, unmanaged space and does not need to be freed.  If the
** fifth argument has the value [VTK_SQLITE_TRANSIENT], then Vtk_Sqlite makes its
** own private copy of the data immediately, before the vtk_sqlite3_bind_*()
** routine returns.
**
** The vtk_sqlite3_bind_zeroblob() routine binds a BLOB of length n that
** is filled with zeros.  A zeroblob uses a fixed amount of memory
** (just an integer to hold it size) while it is being processed.
** Zeroblobs are intended to serve as place-holders for BLOBs whose
** content is later written using 
** [vtk_sqlite3_blob_open | increment BLOB I/O] routines.
**
** The vtk_sqlite3_bind_*() routines must be called after
** [vtk_sqlite3_prepare_v2()] (and its variants) or [vtk_sqlite3_reset()] and
** before [vtk_sqlite3_step()].
** Bindings are not cleared by the [vtk_sqlite3_reset()] routine.
** Unbound parameters are interpreted as NULL.
**
** These routines return [VTK_SQLITE_OK] on success or an error code if
** anything goes wrong.  [VTK_SQLITE_RANGE] is returned if the parameter
** index is out of range.  [VTK_SQLITE_NOMEM] is returned if malloc fails.
** [VTK_SQLITE_MISUSE] is returned if these routines are called on a virtual
** machine that is the wrong state or which has already been finalized.
*/
int vtk_sqlite3_bind_blob(vtk_sqlite3_stmt*, int, const void*, int n, void(*)(void*));
int vtk_sqlite3_bind_double(vtk_sqlite3_stmt*, int, double);
int vtk_sqlite3_bind_int(vtk_sqlite3_stmt*, int, int);
int vtk_sqlite3_bind_int64(vtk_sqlite3_stmt*, int, vtk_sqlite_int64);
int vtk_sqlite3_bind_null(vtk_sqlite3_stmt*, int);
int vtk_sqlite3_bind_text(vtk_sqlite3_stmt*, int, const char*, int n, void(*)(void*));
int vtk_sqlite3_bind_text16(vtk_sqlite3_stmt*, int, const void*, int, void(*)(void*));
int vtk_sqlite3_bind_value(vtk_sqlite3_stmt*, int, const vtk_sqlite3_value*);
int vtk_sqlite3_bind_zeroblob(vtk_sqlite3_stmt*, int, int n);

/*
** CAPI3REF: Number Of Host Parameters
**
** Return the largest host parameter index in the precompiled statement given
** as the argument.  When the host parameters are of the forms like ":AAA"
** or "?", then they are assigned sequential increasing numbers beginning
** with one, so the value returned is the number of parameters.  However
** if the same host parameter name is used multiple times, each occurrance
** is given the same number, so the value returned in that case is the number
** of unique host parameter names.  If host parameters of the form "?NNN"
** are used (where NNN is an integer) then there might be gaps in the
** numbering and the value returned by this interface is the index of the
** host parameter with the largest index value.
*/
int vtk_sqlite3_bind_parameter_count(vtk_sqlite3_stmt*);

/*
** CAPI3REF: Name Of A Host Parameter
**
** This routine returns a pointer to the name of the n-th parameter in a 
** [vtk_sqlite3_stmt | prepared statement].
** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name
** which is the string ":AAA" or "@AAA" or "$VVV".  
** In other words, the initial ":" or "$" or "@"
** is included as part of the name.
** Parameters of the form "?" or "?NNN" have no name.
**
** The first bound parameter has an index of 1, not 0.
**
** If the value n is out of range or if the n-th parameter is nameless,
** then NULL is returned.  The returned string is always in the
** UTF-8 encoding even if the named parameter was originally specified
** as UTF-16 in [vtk_sqlite3_prepare16()] or [vtk_sqlite3_prepare16_v2()].
*/
const char *vtk_sqlite3_bind_parameter_name(vtk_sqlite3_stmt*, int);

/*
** CAPI3REF: Index Of A Parameter With A Given Name
**
** This routine returns the index of a host parameter with the given name.
** The name must match exactly.  If no parameter with the given name is 
** found, return 0.  Parameter names must be UTF8.
*/
int vtk_sqlite3_bind_parameter_index(vtk_sqlite3_stmt*, const char *zName);

/*
** CAPI3REF: Reset All Bindings On A Prepared Statement
**
** Contrary to the intuition of many, [vtk_sqlite3_reset()] does not
** reset the [vtk_sqlite3_bind_blob | bindings] on a 
** [vtk_sqlite3_stmt | prepared statement].  Use this routine to
** reset all host parameters to NULL.
*/
int vtk_sqlite3_clear_bindings(vtk_sqlite3_stmt*);

/*
** CAPI3REF: Number Of Columns In A Result Set
**
** Return the number of columns in the result set returned by the 
** [vtk_sqlite3_stmt | compiled SQL statement]. This routine returns 0
** if pStmt is an SQL statement that does not return data (for 
** example an UPDATE).
*/
int vtk_sqlite3_column_count(vtk_sqlite3_stmt *pStmt);

/*
** CAPI3REF: Column Names In A Result Set
**
** These routines return the name assigned to a particular column
** in the result set of a SELECT statement.  The vtk_sqlite3_column_name()
** interface returns a pointer to a UTF8 string and vtk_sqlite3_column_name16()
** returns a pointer to a UTF16 string.  The first parameter is the
** [vtk_sqlite_stmt | prepared statement] that implements the SELECT statement.
** The second parameter is the column number.  The left-most column is
** number 0.
**
** The returned string pointer is valid until either the 
** [vtk_sqlite_stmt | prepared statement] is destroyed by [vtk_sqlite3_finalize()]
** or until the next call vtk_sqlite3_column_name() or vtk_sqlite3_column_name16()
** on the same column.
*/
const char *vtk_sqlite3_column_name(vtk_sqlite3_stmt*, int N);
const void *vtk_sqlite3_column_name16(vtk_sqlite3_stmt*, int N);

/*
** CAPI3REF: Source Of Data In A Query Result
**
** These routines provide a means to determine what column of what
** table in which database a result of a SELECT statement comes from.
** The name of the database or table or column can be returned as
** either a UTF8 or UTF16 string.  The _database_ routines return
** the database name, the _table_ routines return the table name, and
** the origin_ routines return the column name.
** The returned string is valid until
** the [vtk_sqlite3_stmt | prepared statement] is destroyed using
** [vtk_sqlite3_finalize()] or until the same information is requested
** again in a different encoding.
**
** The names returned are the original un-aliased names of the
** database, table, and column.
**
** The first argument to the following calls is a 
** [vtk_sqlite3_stmt | compiled SQL statement].
** These functions return information about the Nth column returned by 
** the statement, where N is the second function argument.
**
** If the Nth column returned by the statement is an expression
** or subquery and is not a column value, then all of these functions
** return NULL. Otherwise, they return the 
** name of the attached database, table and column that query result
** column was extracted from.
**
** As with all other Vtk_Sqlite APIs, those postfixed with "16" return UTF-16
** encoded strings, the other functions return UTF-8.
**
** These APIs are only available if the library was compiled with the 
** VTK_SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
*/
const char *vtk_sqlite3_column_database_name(vtk_sqlite3_stmt*,int);
const void *vtk_sqlite3_column_database_name16(vtk_sqlite3_stmt*,int);
const char *vtk_sqlite3_column_table_name(vtk_sqlite3_stmt*,int);
const void *vtk_sqlite3_column_table_name16(vtk_sqlite3_stmt*,int);
const char *vtk_sqlite3_column_origin_name(vtk_sqlite3_stmt*,int);
const void *vtk_sqlite3_column_origin_name16(vtk_sqlite3_stmt*,int);

/*
** CAPI3REF: Declared Datatype Of A Query Result
**
** The first parameter is a [vtk_sqlite3_stmt | compiled SQL statement]. 
** If this statement is a SELECT statement and the Nth column of the 
** returned result set  of that SELECT is a table column (not an
** expression or subquery) then the declared type of the table
** column is returned. If the Nth column of the result set is an
** expression or subquery, then a NULL pointer is returned.
** The returned string is always UTF-8 encoded. For example, in
** the database schema:
**
** CREATE TABLE t1(c1 VARIANT);
**
** And the following statement compiled:
**
** SELECT c1 + 1, c1 FROM t1;
**
** Then this routine would return the string "VARIANT" for the second
** result column (i==1), and a NULL pointer for the first result column
** (i==0).
**
** Vtk_Sqlite uses dynamic run-time typing.  So just because a column
** is declared to contain a particular type does not mean that the
** data stored in that column is of the declared type.  Vtk_Sqlite is
** strongly typed, but the typing is dynamic not static.  Type
** is associated with individual values, not with the containers
** used to hold those values.
*/
const char *vtk_sqlite3_column_decltype(vtk_sqlite3_stmt *, int i);
const void *vtk_sqlite3_column_decltype16(vtk_sqlite3_stmt*,int);

/* 
** CAPI3REF:  Evaluate An SQL Statement
**
** After an [vtk_sqlite3_stmt | SQL statement] has been prepared with a call
** to either [vtk_sqlite3_prepare_v2()] or [vtk_sqlite3_prepare16_v2()] or to one of
** the legacy interfaces [vtk_sqlite3_prepare()] or [vtk_sqlite3_prepare16()],
** then this function must be called one or more times to evaluate the 
** statement.
**
** The details of the behavior of this vtk_sqlite3_step() interface depend
** on whether the statement was prepared using the newer "v2" interface
** [vtk_sqlite3_prepare_v2()] and [vtk_sqlite3_prepare16_v2()] or the older legacy
** interface [vtk_sqlite3_prepare()] and [vtk_sqlite3_prepare16()].  The use of the
** new "v2" interface is recommended for new applications but the legacy
** interface will continue to be supported.
**
** In the lagacy interface, the return value will be either [VTK_SQLITE_BUSY], 
** [VTK_SQLITE_DONE], [VTK_SQLITE_ROW], [VTK_SQLITE_ERROR], or [VTK_SQLITE_MISUSE].
** With the "v2" interface, any of the other [VTK_SQLITE_OK | result code]
** or [VTK_SQLITE_IOERR_READ | extended result code] might be returned as
** well.
**
** [VTK_SQLITE_BUSY] means that the database engine was unable to acquire the
** database locks it needs to do its job.  If the statement is a COMMIT
** or occurs outside of an explicit transaction, then you can retry the
** statement.  If the statement is not a COMMIT and occurs within a
** explicit transaction then you should rollback the transaction before
** continuing.
**
** [VTK_SQLITE_DONE] means that the statement has finished executing
** successfully.  vtk_sqlite3_step() should not be called again on this virtual
** machine without first calling [vtk_sqlite3_reset()] to reset the virtual
** machine back to its initial state.
**
** If the SQL statement being executed returns any data, then 
** [VTK_SQLITE_ROW] is returned each time a new row of data is ready
** for processing by the caller. The values may be accessed using
** the [vtk_sqlite3_column_int | column access functions].
** vtk_sqlite3_step() is called again to retrieve the next row of data.
** 
** [VTK_SQLITE_ERROR] means that a run-time error (such as a constraint
** violation) has occurred.  vtk_sqlite3_step() should not be called again on
** the VM. More information may be found by calling [vtk_sqlite3_errmsg()].
** With the legacy interface, a more specific error code (example:
** [VTK_SQLITE_INTERRUPT], [VTK_SQLITE_SCHEMA], [VTK_SQLITE_CORRUPT], and so forth)
** can be obtained by calling [vtk_sqlite3_reset()] on the
** [vtk_sqlite_stmt | prepared statement].  In the "v2" interface,
** the more specific error code is returned directly by vtk_sqlite3_step().
**
** [VTK_SQLITE_MISUSE] means that the this routine was called inappropriately.
** Perhaps it was called on a [vtk_sqlite_stmt | prepared statement] that has
** already been [vtk_sqlite3_finalize | finalized] or on one that had 
** previously returned [VTK_SQLITE_ERROR] or [VTK_SQLITE_DONE].  Or it could
** be the case that the same database connection is being used by two or
** more threads at the same moment in time.
**
** <b>Goofy Interface Alert:</b>
** In the legacy interface, 
** the vtk_sqlite3_step() API always returns a generic error code,
** [VTK_SQLITE_ERROR], following any error other than [VTK_SQLITE_BUSY]
** and [VTK_SQLITE_MISUSE].  You must call [vtk_sqlite3_reset()] or
** [vtk_sqlite3_finalize()] in order to find one of the specific
** [VTK_SQLITE_ERROR | result codes] that better describes the error.
** We admit that this is a goofy design.  The problem has been fixed
** with the "v2" interface.  If you prepare all of your SQL statements
** using either [vtk_sqlite3_prepare_v2()] or [vtk_sqlite3_prepare16_v2()] instead
** of the legacy [vtk_sqlite3_prepare()] and [vtk_sqlite3_prepare16()], then the 
** more specific [VTK_SQLITE_ERROR | result codes] are returned directly
** by vtk_sqlite3_step().  The use of the "v2" interface is recommended.
*/
VTK_SQLITE_API int vtk_sqlite3_step(vtk_sqlite3_stmt*);

/*
** CAPI3REF:
**
** Return the number of values in the current row of the result set.
**
** After a call to [vtk_sqlite3_step()] that returns [VTK_SQLITE_ROW], this routine
** will return the same value as the [vtk_sqlite3_column_count()] function.
** After [vtk_sqlite3_step()] has returned an [VTK_SQLITE_DONE], [VTK_SQLITE_BUSY], or
** a [VTK_SQLITE_ERROR | error code], or before [vtk_sqlite3_step()] has been 
** called on the [vtk_sqlite_stmt | prepared statement] for the first time,
** this routine returns zero.
*/
int vtk_sqlite3_data_count(vtk_sqlite3_stmt *pStmt);

/*
** CAPI3REF: Fundamental Datatypes
**
** Every value in Vtk_Sqlite has one of five fundamental datatypes:
**
** <ul>
** <li> 64-bit signed integer
** <li> 64-bit IEEE floating point number
** <li> string
** <li> BLOB
** <li> NULL
** </ul>
**
** These constants are codes for each of those types.
**
** Note that the VTK_SQLITE_TEXT constant was also used in Vtk_Sqlite version 2
** for a completely different meaning.  Software that links against both
** Vtk_Sqlite version 2 and Vtk_Sqlite version 3 should use VTK_SQLITE3_TEXT not
** VTK_SQLITE_TEXT.
*/
#define VTK_SQLITE_INTEGER  1
#define VTK_SQLITE_FLOAT    2
#define VTK_SQLITE_BLOB     4
#define VTK_SQLITE_NULL     5
#ifdef VTK_SQLITE_TEXT
# undef VTK_SQLITE_TEXT
#else
# define VTK_SQLITE_TEXT     3
#endif
#define VTK_SQLITE3_TEXT     3

/*
** CAPI3REF: Results Values From A Query
**
** These routines return information about the information
** in a single column of the current result row of a query.  In every
** case the first argument is a pointer to the 
** [vtk_sqlite3_stmt | SQL statement] that is being
** evaluate (the [vtk_sqlite_stmt*] that was returned from 
** [vtk_sqlite3_prepare_v2()] or one of its variants) and
** the second argument is the index of the column for which information 
** should be returned.  The left-most column has an index of 0.
**
** If the SQL statement is not currently point to a valid row, or if the
** the column index is out of range, the result is undefined.
**
** The vtk_sqlite3_column_type() routine returns 
** [VTK_SQLITE_INTEGER | datatype code] for the initial data type
** of the result column.  The returned value is one of [VTK_SQLITE_INTEGER],
** [VTK_SQLITE_FLOAT], [VTK_SQLITE_TEXT], [VTK_SQLITE_BLOB], or [VTK_SQLITE_NULL].  The value
** returned by vtk_sqlite3_column_type() is only meaningful if no type
** conversions have occurred as described below.  After a type conversion,
** the value returned by vtk_sqlite3_column_type() is undefined.  Future
** versions of Vtk_Sqlite may change the behavior of vtk_sqlite3_column_type()
** following a type conversion.
**
** If the result is a BLOB or UTF-8 string then the vtk_sqlite3_column_bytes() 
** routine returns the number of bytes in that BLOB or string.
** If the result is a UTF-16 string, then vtk_sqlite3_column_bytes() converts
** the string to UTF-8 and then returns the number of bytes.
** If the result is a numeric value then vtk_sqlite3_column_bytes() uses
** [vtk_sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
** the number of bytes in that string.
** The value returned does not include the zero terminator at the end
** of the string.  For clarity: the value returned is the number of
** bytes in the string, not the number of characters.
**
** The vtk_sqlite3_column_bytes16() routine is similar to vtk_sqlite3_column_bytes()
** but leaves the result in UTF-16 instead of UTF-8.  
** The zero terminator is not included in this count.
**
** These routines attempt to convert the value where appropriate.  For
** example, if the internal representation is FLOAT and a text result
** is requested, [vtk_sqlite3_snprintf()] is used internally to do the conversion
** automatically.  The following table details the conversions that
** are applied:
**
** <blockquote>
** <table border="1">
** <tr><th> Internal <th> Requested <th> 
** <tr><th>  Type    <th>    Type   <th> Conversion
**
** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
** <tr><td> INTEGER  <td>   BLOB    <td> Same as for INTEGER->TEXT
** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
** <tr><td>  TEXT    <td>   BLOB    <td> No change
** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
** </table>
** </blockquote>
**
** The table above makes reference to standard C library functions atoi()
** and atof().  Vtk_Sqlite does not really use these functions.  It has its
** on equavalent internal routines.  The atoi() and atof() names are
** used in the table for brevity and because they are familiar to most
** C programmers.
**
** Note that when type conversions occur, pointers returned by prior
** calls to vtk_sqlite3_column_blob(), vtk_sqlite3_column_text(), and/or
** vtk_sqlite3_column_text16() may be invalidated. 
** Type conversions and pointer invalidations might occur
** in the following cases:
**
** <ul>
** <li><p>  The initial content is a BLOB and vtk_sqlite3_column_text() 
**          or vtk_sqlite3_column_text16() is called.  A zero-terminator might
**          need to be added to the string.</p></li>
**
** <li><p>  The initial content is UTF-8 text and vtk_sqlite3_column_bytes16() or
**          vtk_sqlite3_column_text16() is called.  The content must be converted
**          to UTF-16.</p></li>
**
** <li><p>  The initial content is UTF-16 text and vtk_sqlite3_column_bytes() or
**          vtk_sqlite3_column_text() is called.  The content must be converted
**          to UTF-8.</p></li>
** </ul>
**
** Conversions between UTF-16be and UTF-16le are always done in place and do
** not invalidate a prior pointer, though of course the content of the buffer
** that the prior pointer points to will have been modified.  Other kinds
** of conversion are done in place when it is possible, but sometime it is
** not possible and in those cases prior pointers are invalidated.  
**
** The safest and easiest to remember policy is to invoke these routines
** in one of the following ways:
**
**  <ul>
**  <li>vtk_sqlite3_column_text() followed by vtk_sqlite3_column_bytes()</li>
**  <li>vtk_sqlite3_column_blob() followed by vtk_sqlite3_column_bytes()</li>
**  <li>vtk_sqlite3_column_text16() followed by vtk_sqlite3_column_bytes16()</li>
**  </ul>
**
** In other words, you should call vtk_sqlite3_column_text(), vtk_sqlite3_column_blob(),
** or vtk_sqlite3_column_text16() first to force the result into the desired
** format, then invoke vtk_sqlite3_column_bytes() or vtk_sqlite3_column_bytes16() to
** find the size of the result.  Do not mix call to vtk_sqlite3_column_text() or
** vtk_sqlite3_column_blob() with calls to vtk_sqlite3_column_bytes16().  And do not
** mix calls to vtk_sqlite3_column_text16() with calls to vtk_sqlite3_column_bytes().
*/
const void *vtk_sqlite3_column_blob(vtk_sqlite3_stmt*, int iCol);
int vtk_sqlite3_column_bytes(vtk_sqlite3_stmt*, int iCol);
int vtk_sqlite3_column_bytes16(vtk_sqlite3_stmt*, int iCol);
double vtk_sqlite3_column_double(vtk_sqlite3_stmt*, int iCol);
int vtk_sqlite3_column_int(vtk_sqlite3_stmt*, int iCol);
vtk_sqlite_int64 vtk_sqlite3_column_int64(vtk_sqlite3_stmt*, int iCol);
const unsigned char *vtk_sqlite3_column_text(vtk_sqlite3_stmt*, int iCol);
const void *vtk_sqlite3_column_text16(vtk_sqlite3_stmt*, int iCol);
int vtk_sqlite3_column_type(vtk_sqlite3_stmt*, int iCol);
vtk_sqlite3_value *vtk_sqlite3_column_value(vtk_sqlite3_stmt*, int iCol);

/*
** CAPI3REF: Destroy A Prepared Statement Object
**
** The vtk_sqlite3_finalize() function is called to delete a 
** [vtk_sqlite3_stmt | compiled SQL statement]. If the statement was
** executed successfully, or not executed at all, then VTK_SQLITE_OK is returned.
** If execution of the statement failed then an 
** [VTK_SQLITE_ERROR | error code] or [VTK_SQLITE_IOERR_READ | extended error code]
** is returned. 
**
** This routine can be called at any point during the execution of the
** [vtk_sqlite3_stmt | virtual machine].  If the virtual machine has not 
** completed execution when this routine is called, that is like
** encountering an error or an interrupt.  (See [vtk_sqlite3_interrupt()].) 
** Incomplete updates may be rolled back and transactions cancelled,  
** depending on the circumstances, and the 
** [VTK_SQLITE_ERROR | result code] returned will be [VTK_SQLITE_ABORT].
*/
VTK_SQLITE_API int vtk_sqlite3_finalize(vtk_sqlite3_stmt *pStmt);

/*
** CAPI3REF: Reset A Prepared Statement Object
**
** The vtk_sqlite3_reset() function is called to reset a 
** [vtk_sqlite_stmt | compiled SQL statement] object.
** back to it's initial state, ready to be re-executed.
** Any SQL statement variables that had values bound to them using
** the [vtk_sqlite3_bind_blob | vtk_sqlite3_bind_*() API] retain their values.
** Use [vtk_sqlite3_clear_bindings()] to reset the bindings.
*/
VTK_SQLITE_API int vtk_sqlite3_reset(vtk_sqlite3_stmt *pStmt);

/*
** CAPI3REF: Create Or Redefine SQL Functions
**
** The following two functions are used to add SQL functions or aggregates
** or to redefine the behavior of existing SQL functions or aggregates.  The
** difference only between the two is that the second parameter, the
** name of the (scalar) function or aggregate, is encoded in UTF-8 for
** vtk_sqlite3_create_function() and UTF-16 for vtk_sqlite3_create_function16().
**
** The first argument is the [vtk_sqlite3 | database handle] that holds the
** SQL function or aggregate is to be added or redefined. If a single
** program uses more than one database handle internally, then SQL
** functions or aggregates must be added individually to each database
** handle with which they will be used.
**
** The second parameter is the name of the SQL function to be created
** or redefined.
** The length of the name is limited to 255 bytes, exclusive of the 
** zero-terminator.  Note that the name length limit is in bytes, not
** characters.  Any attempt to create a function with a longer name
** will result in an VTK_SQLITE_ERROR error.
**
** The third parameter is the number of arguments that the SQL function or
** aggregate takes. If this parameter is negative, then the SQL function or
** aggregate may take any number of arguments.
**
** The fourth parameter, eTextRep, specifies what 
** [VTK_SQLITE_UTF8 | text encoding] this SQL function prefers for
** its parameters.  Any SQL function implementation should be able to work
** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
** more efficient with one encoding than another.  It is allowed to
** invoke vtk_sqlite_create_function() or vtk_sqlite3_create_function16() multiple
** times with the same function but with different values of eTextRep.
** When multiple implementations of the same function are available, Vtk_Sqlite
** will pick the one that involves the least amount of data conversion.
** If there is only a single implementation which does not care what
** text encoding is used, then the fourth argument should be
** [VTK_SQLITE_ANY].
**
** The fifth parameter is an arbitrary pointer.  The implementation
** of the function can gain access to this pointer using
** [vtk_sqlite_user_data()].
**
** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
** pointers to C-language functions that implement the SQL
** function or aggregate. A scalar SQL function requires an implementation of
** the xFunc callback only, NULL pointers should be passed as the xStep
** and xFinal parameters. An aggregate SQL function requires an implementation
** of xStep and xFinal and NULL should be passed for xFunc. To delete an
** existing SQL function or aggregate, pass NULL for all three function
** callback.
**
** It is permitted to register multiple implementations of the same
** functions with the same name but with either differing numbers of
** arguments or differing perferred text encodings.  Vtk_Sqlite will use
** the implementation most closely matches the way in which the
** SQL function is used.
*/
int vtk_sqlite3_create_function(
  vtk_sqlite3 *,
  const char *zFunctionName,
  int nArg,
  int eTextRep,
  void*,
  void (*xFunc)(vtk_sqlite3_context*,int,vtk_sqlite3_value**),
  void (*xStep)(vtk_sqlite3_context*,int,vtk_sqlite3_value**),
  void (*xFinal)(vtk_sqlite3_context*)
);
int vtk_sqlite3_create_function16(
  vtk_sqlite3*,
  const void *zFunctionName,
  int nArg,
  int eTextRep,
  void*,
  void (*xFunc)(vtk_sqlite3_context*,int,vtk_sqlite3_value**),
  void (*xStep)(vtk_sqlite3_context*,int,vtk_sqlite3_value**),
  void (*xFinal)(vtk_sqlite3_context*)
);

/*
** CAPI3REF: Text Encodings
**
** These constant define integer codes that represent the various
** text encodings supported by Vtk_Sqlite.
*/
#define VTK_SQLITE_UTF8           1
#define VTK_SQLITE_UTF16LE        2
#define VTK_SQLITE_UTF16BE        3
#define VTK_SQLITE_UTF16          4    /* Use native byte order */
#define VTK_SQLITE_ANY            5    /* vtk_sqlite3_create_function only */
#define VTK_SQLITE_UTF16_ALIGNED  8    /* vtk_sqlite3_create_collation only */

/*
** CAPI3REF: Obsolete Functions
**
** These functions are all now obsolete.  In order to maintain
** backwards compatibility with older code, we continue to support
** these functions.  However, new development projects should avoid
** the use of these functions.  To help encourage people to avoid
** using these functions, we are not going to tell you want they do.
*/
int vtk_sqlite3_aggregate_count(vtk_sqlite3_context*);
VTK_SQLITE_API int vtk_sqlite3_expired(vtk_sqlite3_stmt*);
int vtk_sqlite3_transfer_bindings(vtk_sqlite3_stmt*, vtk_sqlite3_stmt*);
int vtk_sqlite3_global_recover(void);


/*
** CAPI3REF: Obtaining SQL Function Parameter Values
**
** The C-language implementation of SQL functions and aggregates uses
** this set of interface routines to access the parameter values on
** the function or aggregate.
**
** The xFunc (for scalar functions) or xStep (for aggregates) parameters
** to [vtk_sqlite3_create_function()] and [vtk_sqlite3_create_function16()]
** define callbacks that implement the SQL functions and aggregates.
** The 4th parameter to these callbacks is an array of pointers to
** [vtk_sqlite3_value] objects.  There is one [vtk_sqlite3_value] object for
** each parameter to the SQL function.  These routines are used to
** extract values from the [vtk_sqlite3_value] objects.
**
** These routines work just like the corresponding 
** [vtk_sqlite3_column_blob | vtk_sqlite3_column_* routines] except that 
** these routines take a single [vtk_sqlite3_value*] pointer instead
** of an [vtk_sqlite3_stmt*] pointer and an integer column number.
**
** The vtk_sqlite3_value_text16() interface extracts a UTF16 string
** in the native byte-order of the host machine.  The
** vtk_sqlite3_value_text16be() and vtk_sqlite3_value_text16le() interfaces
** extract UTF16 strings as big-endian and little-endian respectively.
**
** The vtk_sqlite3_value_numeric_type() interface attempts to apply
** numeric affinity to the value.  This means that an attempt is
** made to convert the value to an integer or floating point.  If
** such a conversion is possible without loss of information (in order
** words if the value is original a string that looks like a number)
** then it is done.  Otherwise no conversion occurs.  The 
** [VTK_SQLITE_INTEGER | datatype] after conversion is returned.
**
** Please pay particular attention to the fact that the pointer that
** is returned from [vtk_sqlite3_value_blob()], [vtk_sqlite3_value_text()], or
** [vtk_sqlite3_value_text16()] can be invalidated by a subsequent call to
** [vtk_sqlite3_value_bytes()], [vtk_sqlite3_value_bytes16()], [vtk_sqlite_value_text()],
** or [vtk_sqlite3_value_text16()].  
*/
const void *vtk_sqlite3_value_blob(vtk_sqlite3_value*);
int vtk_sqlite3_value_bytes(vtk_sqlite3_value*);
int vtk_sqlite3_value_bytes16(vtk_sqlite3_value*);
double vtk_sqlite3_value_double(vtk_sqlite3_value*);
int vtk_sqlite3_value_int(vtk_sqlite3_value*);
vtk_sqlite_int64 vtk_sqlite3_value_int64(vtk_sqlite3_value*);
const unsigned char *vtk_sqlite3_value_text(vtk_sqlite3_value*);
const void *vtk_sqlite3_value_text16(vtk_sqlite3_value*);
const void *vtk_sqlite3_value_text16le(vtk_sqlite3_value*);
const void *vtk_sqlite3_value_text16be(vtk_sqlite3_value*);
int vtk_sqlite3_value_type(vtk_sqlite3_value*);
int vtk_sqlite3_value_numeric_type(vtk_sqlite3_value*);

/*
** CAPI3REF: Obtain Aggregate Function Context
**
** The implementation of aggregate SQL functions use this routine to allocate
** a structure for storing their state.  The first time this routine
** is called for a particular aggregate, a new structure of size nBytes
** is allocated, zeroed, and returned.  On subsequent calls (for the
** same aggregate instance) the same buffer is returned.  The implementation
** of the aggregate can use the returned buffer to accumulate data.
**
** The buffer allocated is freed automatically by Vtk_Sqlite whan the aggregate
** query concludes.
**
** The first parameter should be a copy of the 
** [vtk_sqlite3_context | SQL function context] that is the first
** parameter to the callback routine that implements the aggregate
** function.
*/
void *vtk_sqlite3_aggregate_context(vtk_sqlite3_context*, int nBytes);

/*
** CAPI3REF: User Data For Functions
**
** The pUserData parameter to the [vtk_sqlite3_create_function()]
** and [vtk_sqlite3_create_function16()] routines
** used to register user functions is available to
** the implementation of the function using this call.
*/
void *vtk_sqlite3_user_data(vtk_sqlite3_context*);

/*
** CAPI3REF: Function Auxiliary Data
**
** The following two functions may be used by scalar SQL functions to
** associate meta-data with argument values. If the same value is passed to
** multiple invocations of the same SQL function during query execution, under
** some circumstances the associated meta-data may be preserved. This may
** be used, for example, to add a regular-expression matching scalar
** function. The compiled version of the regular expression is stored as
** meta-data associated with the SQL value passed as the regular expression
** pattern.  The compiled regular expression can be reused on multiple
** invocations of the same function so that the original pattern string
** does not need to be recompiled on each invocation.
**
** The vtk_sqlite3_get_auxdata() interface returns a pointer to the meta-data
** associated with the Nth argument value to the current SQL function
** call, where N is the second parameter. If no meta-data has been set for
** that value, then a NULL pointer is returned.
**
** The vtk_sqlite3_set_auxdata() is used to associate meta-data with an SQL
** function argument. The third parameter is a pointer to the meta-data
** to be associated with the Nth user function argument value. The fourth
** parameter specifies a destructor that will be called on the meta-
** data pointer to release it when it is no longer required. If the 
** destructor is NULL, it is not invoked.
**
** In practice, meta-data is preserved between function calls for
** expressions that are constant at compile time. This includes literal
** values and SQL variables.
*/
void *vtk_sqlite3_get_auxdata(vtk_sqlite3_context*, int);
void vtk_sqlite3_set_auxdata(vtk_sqlite3_context*, int, void*, void (*)(void*));


/*
** CAPI3REF: Constants Defining Special Destructor Behavior
**
** These are special value for the destructor that is passed in as the
** final argument to routines like [vtk_sqlite3_result_blob()].  If the destructor
** argument is VTK_SQLITE_STATIC, it means that the content pointer is constant
** and will never change.  It does not need to be destroyed.  The 
** VTK_SQLITE_TRANSIENT value means that the content will likely change in
** the near future and that Vtk_Sqlite should make its own private copy of
** the content before returning.
**
** The typedef is necessary to work around problems in certain
** C++ compilers.  See ticket #2191.
*/
typedef void (*vtk_sqlite3_destructor_type)(void*);
#define VTK_SQLITE_STATIC      ((vtk_sqlite3_destructor_type)0)
#define VTK_SQLITE_TRANSIENT   ((vtk_sqlite3_destructor_type)-1)

/*
** CAPI3REF: Setting The Result Of An SQL Function
**
** These routines are used by the xFunc or xFinal callbacks that
** implement SQL functions and aggregates.  See
** [vtk_sqlite3_create_function()] and [vtk_sqlite3_create_function16()]
** for additional information.
**
** These functions work very much like the 
** [vtk_sqlite3_bind_blob | vtk_sqlite3_bind_*] family of functions used
** to bind values to host parameters in prepared statements.
** Refer to the
** [vtk_sqlite3_bind_blob | vtk_sqlite3_bind_* documentation] for
** additional information.
**
** The vtk_sqlite3_result_error() and vtk_sqlite3_result_error16() functions
** cause the implemented SQL function to throw an exception.  The
** parameter to vtk_sqlite3_result_error() or vtk_sqlite3_result_error16()
** is the text of an error message.
**
** The vtk_sqlite3_result_toobig() cause the function implementation
** to throw and error indicating that a string or BLOB is to long
** to represent.
*/
void vtk_sqlite3_result_blob(vtk_sqlite3_context*, const void*, int, void(*)(void*));
void vtk_sqlite3_result_double(vtk_sqlite3_context*, double);
void vtk_sqlite3_result_error(vtk_sqlite3_context*, const char*, int);
void vtk_sqlite3_result_error16(vtk_sqlite3_context*, const void*, int);
void vtk_sqlite3_result_error_toobig(vtk_sqlite3_context*);
void vtk_sqlite3_result_int(vtk_sqlite3_context*, int);
void vtk_sqlite3_result_int64(vtk_sqlite3_context*, vtk_sqlite_int64);
void vtk_sqlite3_result_null(vtk_sqlite3_context*);
void vtk_sqlite3_result_text(vtk_sqlite3_context*, const char*, int, void(*)(void*));
void vtk_sqlite3_result_text16(vtk_sqlite3_context*, const void*, int, void(*)(void*));
void vtk_sqlite3_result_text16le(vtk_sqlite3_context*, const void*, int,void(*)(void*));
void vtk_sqlite3_result_text16be(vtk_sqlite3_context*, const void*, int,void(*)(void*));
void vtk_sqlite3_result_value(vtk_sqlite3_context*, vtk_sqlite3_value*);
void vtk_sqlite3_result_zeroblob(vtk_sqlite3_context*, int n);

/*
** CAPI3REF: Define New Collating Sequences
**
** These functions are used to add new collation sequences to the
** [vtk_sqlite3*] handle specified as the first argument. 
**
** The name of the new collation sequence is specified as a UTF-8 string
** for vtk_sqlite3_create_collation() and vtk_sqlite3_create_collation_v2()
** and a UTF-16 string for vtk_sqlite3_create_collation16().  In all cases
** the name is passed as the second function argument.
**
** The third argument must be one of the constants [VTK_SQLITE_UTF8],
** [VTK_SQLITE_UTF16LE] or [VTK_SQLITE_UTF16BE], indicating that the user-supplied
** routine expects to be passed pointers to strings encoded using UTF-8,
** UTF-16 little-endian or UTF-16 big-endian respectively.
**
** A pointer to the user supplied routine must be passed as the fifth
** argument. If it is NULL, this is the same as deleting the collation
** sequence (so that Vtk_Sqlite cannot call it anymore). Each time the user
** supplied function is invoked, it is passed a copy of the void* passed as
** the fourth argument to vtk_sqlite3_create_collation() or
** vtk_sqlite3_create_collation16() as its first parameter.
**
** The remaining arguments to the user-supplied routine are two strings,
** each represented by a [length, data] pair and encoded in the encoding
** that was passed as the third argument when the collation sequence was
** registered. The user routine should return negative, zero or positive if
** the first string is less than, equal to, or greater than the second
** string. i.e. (STRING1 - STRING2).
**
** The vtk_sqlite3_create_collation_v2() works like vtk_sqlite3_create_collation()
** excapt that it takes an extra argument which is a destructor for
** the collation.  The destructor is called when the collation is
** destroyed and is passed a copy of the fourth parameter void* pointer
** of the vtk_sqlite3_create_collation_v2().  Collations are destroyed when
** they are overridden by later calls to the collation creation functions
** or when the [vtk_sqlite3*] database handle is closed using [vtk_sqlite3_close()].
**
** The vtk_sqlite3_create_collation_v2() interface is experimental and
** subject to change in future releases.  The other collation creation
** functions are stable.
*/
int vtk_sqlite3_create_collation(
  vtk_sqlite3*, 
  const char *zName, 
  int eTextRep, 
  void*,
  int(*xCompare)(void*,int,const void*,int,const void*)
);
int vtk_sqlite3_create_collation_v2(
  vtk_sqlite3*, 
  const char *zName, 
  int eTextRep, 
  void*,
  int(*xCompare)(void*,int,const void*,int,const void*),
  void(*xDestroy)(void*)
);
int vtk_sqlite3_create_collation16(
  vtk_sqlite3*, 
  const char *zName, 
  int eTextRep, 
  void*,
  int(*xCompare)(void*,int,const void*,int,const void*)
);

/*
** CAPI3REF: Collation Needed Callbacks
**
** To avoid having to register all collation sequences before a database
** can be used, a single callback function may be registered with the
** database handle to be called whenever an undefined collation sequence is
** required.
**
** If the function is registered using the vtk_sqlite3_collation_needed() API,
** then it is passed the names of undefined collation sequences as strings
** encoded in UTF-8. If vtk_sqlite3_collation_needed16() is used, the names
** are passed as UTF-16 in machine native byte order. A call to either
** function replaces any existing callback.
**
** When the callback is invoked, the first argument passed is a copy
** of the second argument to vtk_sqlite3_collation_needed() or
** vtk_sqlite3_collation_needed16(). The second argument is the database
** handle. The third argument is one of [VTK_SQLITE_UTF8], [VTK_SQLITE_UTF16BE], or
** [VTK_SQLITE_UTF16LE], indicating the most desirable form of the collation
** sequence function required. The fourth parameter is the name of the
** required collation sequence.
**
** The callback function should register the desired collation using
** [vtk_sqlite3_create_collation()], [vtk_sqlite3_create_collation16()], or
** [vtk_sqlite3_create_collation_v2()].
*/
int vtk_sqlite3_collation_needed(
  vtk_sqlite3*, 
  void*, 
  void(*)(void*,vtk_sqlite3*,int eTextRep,const char*)
);
int vtk_sqlite3_collation_needed16(
  vtk_sqlite3*, 
  void*,
  void(*)(void*,vtk_sqlite3*,int eTextRep,const void*)
);

/*
** Specify the key for an encrypted database.  This routine should be
** called right after vtk_sqlite3_open().
**
** The code to implement this API is not available in the public release
** of Vtk_Sqlite.
*/
VTK_SQLITE_API int vtk_sqlite3_key(
  vtk_sqlite3 *db,                   /* Database to be rekeyed */
  const void *pKey, int nKey     /* The key */
);

/*
** Change the key on an open database.  If the current database is not
** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
** database is decrypted.
**
** The code to implement this API is not available in the public release
** of Vtk_Sqlite.
*/
VTK_SQLITE_API int vtk_sqlite3_rekey(
  vtk_sqlite3 *db,                   /* Database to be rekeyed */
  const void *pKey, int nKey     /* The new key */
);

/*
** CAPI3REF:  Suspend Execution For A Short Time
**
** This function causes the current thread to suspend execution
** a number of milliseconds specified in its parameter.
**
** If the operating system does not support sleep requests with 
** millisecond time resolution, then the time will be rounded up to 
** the nearest second. The number of milliseconds of sleep actually 
** requested from the operating system is returned.
*/
VTK_SQLITE_API int vtk_sqlite3_sleep(int);

/*
** CAPI3REF:  Name Of The Folder Holding Temporary Files
**
** If this global variable is made to point to a string which is
** the name of a folder (a.ka. directory), then all temporary files
** created by Vtk_Sqlite will be placed in that directory.  If this variable
** is NULL pointer, then Vtk_Sqlite does a search for an appropriate temporary
** file directory.
**
** Once [vtk_sqlite3_open()] has been called, changing this variable will
** invalidate the current temporary database, if any.  Generally speaking,
** it is not safe to invoke this routine after [vtk_sqlite3_open()] has
** been called.
*/
extern char *vtk_sqlite3_temp_directory;

/*
** CAPI3REF:  Test To See If The Databse Is In Auto-Commit Mode
**
** Test to see whether or not the database connection is in autocommit
** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
** by default.  Autocommit is disabled by a BEGIN statement and reenabled
** by the next COMMIT or ROLLBACK.
*/
int vtk_sqlite3_get_autocommit(vtk_sqlite3*);

/*
** CAPI3REF:  Find The Database Handle Associated With A Prepared Statement
**
** Return the [vtk_sqlite3*] database handle to which a
** [vtk_sqlite3_stmt | prepared statement] belongs.
** This is the same database handle that was
** the first argument to the [vtk_sqlite3_prepare_v2()] or its variants
** that was used to create the statement in the first place.
*/
vtk_sqlite3 *vtk_sqlite3_db_handle(vtk_sqlite3_stmt*);


/*
** CAPI3REF: Commit And Rollback Notification Callbacks
**
** These routines
** register callback functions to be invoked whenever a transaction
** is committed or rolled back.  The pArg argument is passed through
** to the callback.  If the callback on a commit hook function 
** returns non-zero, then the commit is converted into a rollback.
**
** If another function was previously registered, its pArg value is returned.
** Otherwise NULL is returned.
**
** Registering a NULL function disables the callback.
**
** For the purposes of this API, a transaction is said to have been 
** rolled back if an explicit "ROLLBACK" statement is executed, or
** an error or constraint causes an implicit rollback to occur. The 
** callback is not invoked if a transaction is automatically rolled
** back because the database connection is closed.
**
** These are experimental interfaces and are subject to change.
*/
void *vtk_sqlite3_commit_hook(vtk_sqlite3*, int(*)(void*), void*);
void *vtk_sqlite3_rollback_hook(vtk_sqlite3*, void(*)(void *), void*);

/*
** CAPI3REF: Data Change Notification Callbacks
**
** Register a callback function with the database connection identified by the 
** first argument to be invoked whenever a row is updated, inserted or deleted.
** Any callback set by a previous call to this function for the same 
** database connection is overridden.
**
** The second argument is a pointer to the function to invoke when a 
** row is updated, inserted or deleted. The first argument to the callback is
** a copy of the third argument to vtk_sqlite3_update_hook(). The second callback 
** argument is one of VTK_SQLITE_INSERT, VTK_SQLITE_DELETE or VTK_SQLITE_UPDATE, depending
** on the operation that caused the callback to be invoked. The third and 
** fourth arguments to the callback contain pointers to the database and 
** table name containing the affected row. The final callback parameter is 
** the rowid of the row. In the case of an update, this is the rowid after 
** the update takes place.
**
** The update hook is not invoked when internal system tables are
** modified (i.e. vtk_sqlite_master and vtk_sqlite_sequence).
**
** If another function was previously registered, its pArg value is returned.
** Otherwise NULL is returned.
*/
void *vtk_sqlite3_update_hook(
  vtk_sqlite3*, 
  void(*)(void *,int ,char const *,char const *,vtk_sqlite_int64),
  void*
);

/*
** CAPI3REF:  Enable Or Disable Shared Pager Cache
**
** This routine enables or disables the sharing of the database cache
** and schema data structures between connections to the same database.
** Sharing is enabled if the argument is true and disabled if the argument
** is false.
**
** Cache sharing is enabled and disabled on a thread-by-thread basis.
** Each call to this routine enables or disables cache sharing only for
** connections created in the same thread in which this routine is called.
** There is no mechanism for sharing cache between database connections
** running in different threads.
**
** Sharing must be disabled prior to shutting down a thread or else
** the thread will leak memory.  Call this routine with an argument of
** 0 to turn off sharing.  Or use the vtk_sqlite3_thread_cleanup() API.
**
** This routine must not be called when any database connections
** are active in the current thread.  Enabling or disabling shared
** cache while there are active database connections will result
** in memory corruption.
**
** When the shared cache is enabled, the
** following routines must always be called from the same thread:
** [vtk_sqlite3_open()], [vtk_sqlite3_prepare_v2()], [vtk_sqlite3_step()],
** [vtk_sqlite3_reset()], [vtk_sqlite3_finalize()], and [vtk_sqlite3_close()].
** This is due to the fact that the shared cache makes use of
** thread-specific storage so that it will be available for sharing
** with other connections.
**
** Virtual tables cannot be used with a shared cache.  When shared
** cache is enabled, the vtk_sqlite3_create_module() API used to register
** virtual tables will always return an error.
**
** This routine returns [VTK_SQLITE_OK] if shared cache was
** enabled or disabled successfully.  An [VTK_SQLITE_ERROR | error code]
** is returned otherwise.
**
** Shared cache is disabled by default for backward compatibility.
*/
int vtk_sqlite3_enable_shared_cache(int);

/*
** CAPI3REF:  Attempt To Free Heap Memory
**
** Attempt to free N bytes of heap memory by deallocating non-essential
** memory allocations held by the database library (example: memory 
** used to cache database pages to improve performance).
**
** This function is not a part of standard builds.  It is only created
** if Vtk_Sqlite is compiled with the VTK_SQLITE_ENABLE_MEMORY_MANAGEMENT macro.
*/
int vtk_sqlite3_release_memory(int);

/*
** CAPI3REF:  Impose A Limit On Heap Size
**
** Place a "soft" limit on the amount of heap memory that may be allocated by
** Vtk_Sqlite within the current thread. If an internal allocation is requested 
** that would exceed the specified limit, [vtk_sqlite3_release_memory()] is invoked
** one or more times to free up some space before the allocation is made.
**
** The limit is called "soft", because if [vtk_sqlite3_release_memory()] cannot free
** sufficient memory to prevent the limit from being exceeded, the memory is
** allocated anyway and the current operation proceeds.
**
** Prior to shutting down a thread vtk_sqlite3_soft_heap_limit() must be set to 
** zero (the default) or else the thread will leak memory. Alternatively, use
** the [vtk_sqlite3_thread_cleanup()] API.
**
** A negative or zero value for N means that there is no soft heap limit and
** [vtk_sqlite3_release_memory()] will only be called when memory is exhaused.
** The default value for the soft heap limit is zero.
**
** Vtk_Sqlite makes a best effort to honor the soft heap limit.  But if it
** is unable to reduce memory usage below the soft limit, execution will
** continue without error or notification.  This is why the limit is 
** called a "soft" limit.  It is advisory only.
**
** This function is only available if the library was compiled with the 
** VTK_SQLITE_ENABLE_MEMORY_MANAGEMENT option set.
** memory-management has been enabled.
*/
void vtk_sqlite3_soft_heap_limit(int);

/*
** CAPI3REF:  Clean Up Thread Local Storage
**
** This routine makes sure that all thread-local storage has been
** deallocated for the current thread.
**
** This routine is not technically necessary.  All thread-local storage
** will be automatically deallocated once memory-management and
** shared-cache are disabled and the soft heap limit has been set
** to zero.  This routine is provided as a convenience for users who
** want to make absolutely sure they have not forgotten something
** prior to killing off a thread.
*/
void vtk_sqlite3_thread_cleanup(void);

/*
** CAPI3REF:  Extract Metadata About A Column Of A Table
**
** This routine
** returns meta-data about a specific column of a specific database
** table accessible using the connection handle passed as the first function 
** argument.
**
** The column is identified by the second, third and fourth parameters to 
** this function. The second parameter is either the name of the database
** (i.e. "main", "temp" or an attached database) containing the specified
** table or NULL. If it is NULL, then all attached databases are searched
** for the table using the same algorithm as the database engine uses to 
** resolve unqualified table references.
**
** The third and fourth parameters to this function are the table and column 
** name of the desired column, respectively. Neither of these parameters 
** may be NULL.
**
** Meta information is returned by writing to the memory locations passed as
** the 5th and subsequent parameters to this function. Any of these 
** arguments may be NULL, in which case the corresponding element of meta 
** information is ommitted.
**
** <pre>
** Parameter     Output Type      Description
** -----------------------------------
**
**   5th         const char*      Data type
**   6th         const char*      Name of the default collation sequence 
**   7th         int              True if the column has a NOT NULL constraint
**   8th         int              True if the column is part of the PRIMARY KEY
**   9th         int              True if the column is AUTOINCREMENT
** </pre>
**
**
** The memory pointed to by the character pointers returned for the 
** declaration type and collation sequence is valid only until the next 
** call to any vtk_sqlite API function.
**
** If the specified table is actually a view, then an error is returned.
**
** If the specified column is "rowid", "oid" or "_rowid_" and an 
** INTEGER PRIMARY KEY column has been explicitly declared, then the output 
** parameters are set for the explicitly declared column. If there is no
** explicitly declared IPK column, then the output parameters are set as 
** follows:
**
** <pre>
**     data type: "INTEGER"
**     collation sequence: "BINARY"
**     not null: 0
**     primary key: 1
**     auto increment: 0
** </pre>
**
** This function may load one or more schemas from database files. If an
** error occurs during this process, or if the requested table or column
** cannot be found, an VTK_SQLITE error code is returned and an error message
** left in the database handle (to be retrieved using vtk_sqlite3_errmsg()).
**
** This API is only available if the library was compiled with the
** VTK_SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
*/
int vtk_sqlite3_table_column_metadata(
  vtk_sqlite3 *db,                /* Connection handle */
  const char *zDbName,        /* Database name or NULL */
  const char *zTableName,     /* Table name */
  const char *zColumnName,    /* Column name */
  char const **pzDataType,    /* OUTPUT: Declared data type */
  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
  int *pAutoinc               /* OUTPUT: True if colums is auto-increment */
);

/*
** CAPI3REF: Load An Extension
**
** Attempt to load an Vtk_Sqlite extension library contained in the file
** zFile.  The entry point is zProc.  zProc may be 0 in which case the
** name of the entry point defaults to "vtk_sqlite3_extension_init".
**
** Return [VTK_SQLITE_OK] on success and [VTK_SQLITE_ERROR] if something goes wrong.
**
** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
** error message text.  The calling function should free this memory
** by calling [vtk_sqlite3_free()].
**
** Extension loading must be enabled using [vtk_sqlite3_enable_load_extension()]
** prior to calling this API or an error will be returned.
*/
int vtk_sqlite3_load_extension(
  vtk_sqlite3 *db,          /* Load the extension into this database connection */
  const char *zFile,    /* Name of the shared library containing extension */
  const char *zProc,    /* Entry point.  Derived from zFile if 0 */
  char **pzErrMsg       /* Put error message here if not 0 */
);

/*
** CAPI3REF:  Enable Or Disable Extension Loading
**
** So as not to open security holes in older applications that are
** unprepared to deal with extension loading, and as a means of disabling
** extension loading while evaluating user-entered SQL, the following
** API is provided to turn the [vtk_sqlite3_load_extension()] mechanism on and
** off.  It is off by default.  See ticket #1863.
**
** Call this routine with onoff==1 to turn extension loading on
** and call it with onoff==0 to turn it back off again.
*/
int vtk_sqlite3_enable_load_extension(vtk_sqlite3 *db, int onoff);

/*
** CAPI3REF: Make Arrangements To Automatically Load An Extension
**
** Register an extension entry point that is automatically invoked
** whenever a new database connection is opened using
** [vtk_sqlite3_open()] or [vtk_sqlite3_open16()].
**
** This API can be invoked at program startup in order to register
** one or more statically linked extensions that will be available
** to all new database connections.
**
** Duplicate extensions are detected so calling this routine multiple
** times with the same extension is harmless.
**
** This routine stores a pointer to the extension in an array
** that is obtained from malloc().  If you run a memory leak
** checker on your program and it reports a leak because of this
** array, then invoke [vtk_sqlite3_automatic_extension_reset()] prior
** to shutdown to free the memory.
**
** Automatic extensions apply across all threads.
**
** This interface is experimental and is subject to change or
** removal in future releases of Vtk_Sqlite.
*/
int vtk_sqlite3_auto_extension(void *xEntryPoint);


/*
** CAPI3REF: Reset Automatic Extension Loading
**
** Disable all previously registered automatic extensions.  This
** routine undoes the effect of all prior [vtk_sqlite3_automatic_extension()]
** calls.
**
** This call disabled automatic extensions in all threads.
**
** This interface is experimental and is subject to change or
** removal in future releases of Vtk_Sqlite.
*/
void vtk_sqlite3_reset_auto_extension(void);


/*
****** EXPERIMENTAL - subject to change without notice **************
**
** The interface to the virtual-table mechanism is currently considered
** to be experimental.  The interface might change in incompatible ways.
** If this is a problem for you, do not use the interface at this time.
**
** When the virtual-table mechanism stablizes, we will declare the
** interface fixed, support it indefinitely, and remove this comment.
*/

/*
** Structures used by the virtual table interface
*/
typedef struct vtk_sqlite3_vtab vtk_sqlite3_vtab;
typedef struct vtk_sqlite3_index_info vtk_sqlite3_index_info;
typedef struct vtk_sqlite3_vtab_cursor vtk_sqlite3_vtab_cursor;
typedef struct vtk_sqlite3_module vtk_sqlite3_module;

/*
** A module is a class of virtual tables.  Each module is defined
** by an instance of the following structure.  This structure consists
** mostly of methods for the module.
*/
struct vtk_sqlite3_module {
  int iVersion;
  int (*xCreate)(vtk_sqlite3*, void *pAux,
               int argc, const char *const*argv,
               vtk_sqlite3_vtab **ppVTab, char**);
  int (*xConnect)(vtk_sqlite3*, void *pAux,
               int argc, const char *const*argv,
               vtk_sqlite3_vtab **ppVTab, char**);
  int (*xBestIndex)(vtk_sqlite3_vtab *pVTab, vtk_sqlite3_index_info*);
  int (*xDisconnect)(vtk_sqlite3_vtab *pVTab);
  int (*xDestroy)(vtk_sqlite3_vtab *pVTab);
  int (*xOpen)(vtk_sqlite3_vtab *pVTab, vtk_sqlite3_vtab_cursor **ppCursor);
  int (*xClose)(vtk_sqlite3_vtab_cursor*);
  int (*xFilter)(vtk_sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
                int argc, vtk_sqlite3_value **argv);
  int (*xNext)(vtk_sqlite3_vtab_cursor*);
  int (*xEof)(vtk_sqlite3_vtab_cursor*);
  int (*xColumn)(vtk_sqlite3_vtab_cursor*, vtk_sqlite3_context*, int);
  int (*xRowid)(vtk_sqlite3_vtab_cursor*, vtk_sqlite_int64 *pRowid);
  int (*xUpdate)(vtk_sqlite3_vtab *, int, vtk_sqlite3_value **, vtk_sqlite_int64 *);
  int (*xBegin)(vtk_sqlite3_vtab *pVTab);
  int (*xSync)(vtk_sqlite3_vtab *pVTab);
  int (*xCommit)(vtk_sqlite3_vtab *pVTab);
  int (*xRollback)(vtk_sqlite3_vtab *pVTab);
  int (*xFindFunction)(vtk_sqlite3_vtab *pVtab, int nArg, const char *zName,
                       void (**pxFunc)(vtk_sqlite3_context*,int,vtk_sqlite3_value**),
                       void **ppArg);

  int (*xRename)(vtk_sqlite3_vtab *pVtab, const char *zNew);
};

/*
** The vtk_sqlite3_index_info structure and its substructures is used to
** pass information into and receive the reply from the xBestIndex
** method of an vtk_sqlite3_module.  The fields under **Inputs** are the
** inputs to xBestIndex and are read-only.  xBestIndex inserts its
** results into the **Outputs** fields.
**
** The aConstraint[] array records WHERE clause constraints of the
** form:
**
**         column OP expr
**
** Where OP is =, <, <=, >, or >=.  The particular operator is stored
** in aConstraint[].op.  The index of the column is stored in 
** aConstraint[].iColumn.  aConstraint[].usable is TRUE if the
** expr on the right-hand side can be evaluated (and thus the constraint
** is usable) and false if it cannot.
**
** The optimizer automatically inverts terms of the form "expr OP column"
** and makes other simplificatinos to the WHERE clause in an attempt to
** get as many WHERE clause terms into the form shown above as possible.
** The aConstraint[] array only reports WHERE clause terms in the correct
** form that refer to the particular virtual table being queried.
**
** Information about the ORDER BY clause is stored in aOrderBy[].
** Each term of aOrderBy records a column of the ORDER BY clause.
**
** The xBestIndex method must fill aConstraintUsage[] with information
** about what parameters to pass to xFilter.  If argvIndex>0 then
** the right-hand side of the corresponding aConstraint[] is evaluated
** and becomes the argvIndex-th entry in argv.  If aConstraintUsage[].omit
** is true, then the constraint is assumed to be fully handled by the
** virtual table and is not checked again by Vtk_Sqlite.
**
** The idxNum and idxPtr values are recorded and passed into xFilter.
** vtk_sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
**
** The orderByConsumed means that output from xFilter will occur in
** the correct order to satisfy the ORDER BY clause so that no separate
** sorting step is required.
**
** The estimatedCost value is an estimate of the cost of doing the
** particular lookup.  A full scan of a table with N entries should have
** a cost of N.  A binary search of a table of N entries should have a
** cost of approximately log(N).
*/
struct vtk_sqlite3_index_info {
  /* Inputs */
  const int nConstraint;     /* Number of entries in aConstraint */
  const struct vtk_sqlite3_index_constraint {
     int iColumn;              /* Column on left-hand side of constraint */
     unsigned char op;         /* Constraint operator */
     unsigned char usable;     /* True if this constraint is usable */
     int iTermOffset;          /* Used internally - xBestIndex should ignore */
  } *const aConstraint;      /* Table of WHERE clause constraints */
  const int nOrderBy;        /* Number of terms in the ORDER BY clause */
  const struct vtk_sqlite3_index_orderby {
     int iColumn;              /* Column number */
     unsigned char desc;       /* True for DESC.  False for ASC. */
  } *const aOrderBy;         /* The ORDER BY clause */

  /* Outputs */
  struct vtk_sqlite3_index_constraint_usage {
    int argvIndex;           /* if >0, constraint is part of argv to xFilter */
    unsigned char omit;      /* Do not code a test for this constraint */
  } *const aConstraintUsage;
  int idxNum;                /* Number used to identify the index */
  char *idxStr;              /* String, possibly obtained from vtk_sqlite3_malloc */
  int needToFreeIdxStr;      /* Free idxStr using vtk_sqlite3_free() if true */
  int orderByConsumed;       /* True if output is already ordered */
  double estimatedCost;      /* Estimated cost of using this index */
};
#define VTK_SQLITE_INDEX_CONSTRAINT_EQ    2
#define VTK_SQLITE_INDEX_CONSTRAINT_GT    4
#define VTK_SQLITE_INDEX_CONSTRAINT_LE    8
#define VTK_SQLITE_INDEX_CONSTRAINT_LT    16
#define VTK_SQLITE_INDEX_CONSTRAINT_GE    32
#define VTK_SQLITE_INDEX_CONSTRAINT_MATCH 64

/*
** This routine is used to register a new module name with an Vtk_Sqlite
** connection.  Module names must be registered before creating new
** virtual tables on the module, or before using preexisting virtual
** tables of the module.
*/
int vtk_sqlite3_create_module(
  vtk_sqlite3 *db,               /* Vtk_Sqlite connection to register module with */
  const char *zName,         /* Name of the module */
  const vtk_sqlite3_module *,    /* Methods for the module */
  void *                     /* Client data for xCreate/xConnect */
);

/*
** This routine is identical to the vtk_sqlite3_create_module() method above,
** except that it allows a destructor function to be specified. It is
** even more experimental than the rest of the virtual tables API.
*/
int vtk_sqlite3_create_module_v2(
  vtk_sqlite3 *db,               /* Vtk_Sqlite connection to register module with */
  const char *zName,         /* Name of the module */
  const vtk_sqlite3_module *,    /* Methods for the module */
  void *,                    /* Client data for xCreate/xConnect */
  void(*xDestroy)(void*)     /* Module destructor function */
);

/*
** Every module implementation uses a subclass of the following structure
** to describe a particular instance of the module.  Each subclass will
** be taylored to the specific needs of the module implementation.   The
** purpose of this superclass is to define certain fields that are common
** to all module implementations.
**
** Virtual tables methods can set an error message by assigning a
** string obtained from vtk_sqlite3_mprintf() to zErrMsg.  The method should
** take care that any prior string is freed by a call to vtk_sqlite3_free()
** prior to assigning a new string to zErrMsg.  After the error message
** is delivered up to the client application, the string will be automatically
** freed by vtk_sqlite3_free() and the zErrMsg field will be zeroed.  Note
** that vtk_sqlite3_mprintf() and vtk_sqlite3_free() are used on the zErrMsg field
** since virtual tables are commonly implemented in loadable extensions which
** do not have access to vtk_sqlite3MPrintf() or vtk_sqlite3Free().
*/
struct vtk_sqlite3_vtab {
  const vtk_sqlite3_module *pModule;  /* The module for this virtual table */
  int nRef;                       /* Used internally */
  char *zErrMsg;                  /* Error message from vtk_sqlite3_mprintf() */
  /* Virtual table implementations will typically add additional fields */
};

/* Every module implementation uses a subclass of the following structure
** to describe cursors that point into the virtual table and are used
** to loop through the virtual table.  Cursors are created using the
** xOpen method of the module.  Each module implementation will define
** the content of a cursor structure to suit its own needs.
**
** This superclass exists in order to define fields of the cursor that
** are common to all implementations.
*/
struct vtk_sqlite3_vtab_cursor {
  vtk_sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
  /* Virtual table implementations will typically add additional fields */
};

/*
** The xCreate and xConnect methods of a module use the following API
** to declare the format (the names and datatypes of the columns) of
** the virtual tables they implement.
*/
int vtk_sqlite3_declare_vtab(vtk_sqlite3*, const char *zCreateTable);

/*
** Virtual tables can provide alternative implementations of functions
** using the xFindFunction method.  But global versions of those functions
** must exist in order to be overloaded.
**
** This API makes sure a global version of a function with a particular
** name and number of parameters exists.  If no such function exists
** before this API is called, a new function is created.  The implementation
** of the new function always causes an exception to be thrown.  So
** the new function is not good for anything by itself.  Its only
** purpose is to be a place-holder function that can be overloaded
** by virtual tables.
**
** This API should be considered part of the virtual table interface,
** which is experimental and subject to change.
*/
int vtk_sqlite3_overload_function(vtk_sqlite3*, const char *zFuncName, int nArg);

/*
** The interface to the virtual-table mechanism defined above (back up
** to a comment remarkably similar to this one) is currently considered
** to be experimental.  The interface might change in incompatible ways.
** If this is a problem for you, do not use the interface at this time.
**
** When the virtual-table mechanism stablizes, we will declare the
** interface fixed, support it indefinitely, and remove this comment.
**
****** EXPERIMENTAL - subject to change without notice **************
*/

/*
** CAPI3REF: A Handle To An Open BLOB
**
** An instance of the following opaque structure is used to 
** represent an blob-handle.  A blob-handle is created by
** [vtk_sqlite3_blob_open()] and destroyed by [vtk_sqlite3_blob_close()].
** The [vtk_sqlite3_blob_read()] and [vtk_sqlite3_blob_write()] interfaces
** can be used to read or write small subsections of the blob.
** The [sqltie3_blob_size()] interface returns the size of the
** blob in bytes.
*/
typedef struct vtk_sqlite3_blob vtk_sqlite3_blob;

/*
** CAPI3REF: Open A BLOB For Incremental I/O
**
** Open a handle to the blob located in row iRow,, column zColumn, 
** table zTable in database zDb. i.e. the same blob that would
** be selected by:
**
** <pre>
**     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
** </pre>
**
** If the flags parameter is non-zero, the blob is opened for 
** read and write access. If it is zero, the blob is opened for read 
** access.
**
** On success, [VTK_SQLITE_OK] is returned and the new 
** [vtk_sqlite3_blob | blob handle] is written to *ppBlob.
** Otherwise an error code is returned and 
** any value written to *ppBlob should not be used by the caller.
** This function sets the database-handle error code and message
** accessible via [vtk_sqlite3_errcode()] and [vtk_sqlite3_errmsg()].
*/
int vtk_sqlite3_blob_open(
  vtk_sqlite3*,
  const char *zDb,
  const char *zTable,
  const char *zColumn,
  vtk_sqlite_int64 iRow,
  int flags,
  vtk_sqlite3_blob **ppBlob
);

/*
** CAPI3REF:  Close A BLOB Handle
**
** Close an open [vtk_sqlite3_blob | blob handle].
*/
int vtk_sqlite3_blob_close(vtk_sqlite3_blob *);

/*
** CAPI3REF:  Return The Size Of An Open BLOB
**
** Return the size in bytes of the blob accessible via the open 
** [vtk_sqlite3_blob | blob-handle] passed as an argument.
*/
int vtk_sqlite3_blob_bytes(vtk_sqlite3_blob *);

/*
** CAPI3REF:  Read Data From A BLOB Incrementally
**
** This function is used to read data from an open 
** [vtk_sqlite3_blob | blob-handle] into a caller supplied buffer.
** n bytes of data are copied into buffer
** z from the open blob, starting at offset iOffset.
**
** On success, VTK_SQLITE_OK is returned. Otherwise, an 
** [VTK_SQLITE_ERROR | Vtk_Sqlite error code] or an
** [VTK_SQLITE_IOERR_READ | extended error code] is returned.
*/
int vtk_sqlite3_blob_read(vtk_sqlite3_blob *, void *z, int n, int iOffset);

/*
** CAPI3REF:  Write Data Into A BLOB Incrementally
**
** This function is used to write data into an open 
** [vtk_sqlite3_blob | blob-handle] from a user supplied buffer.
** n bytes of data are copied from the buffer
** pointed to by z into the open blob, starting at offset iOffset.
**
** If the [vtk_sqlite3_blob | blob-handle] passed as the first argument
** was not opened for writing (the flags parameter to [vtk_sqlite3_blob_open()]
*** was zero), this function returns [VTK_SQLITE_READONLY].
**
** This function may only modify the contents of the blob, it is
** not possible to increase the size of a blob using this API. If
** offset iOffset is less than n bytes from the end of the blob, 
** [VTK_SQLITE_ERROR] is returned and no data is written.
**
** On success, VTK_SQLITE_OK is returned. Otherwise, an 
** [VTK_SQLITE_ERROR | Vtk_Sqlite error code] or an
** [VTK_SQLITE_IOERR_READ | extended error code] is returned.
*/
int vtk_sqlite3_blob_write(vtk_sqlite3_blob *, const void *z, int n, int iOffset);

/*
** Undo the hack that converts floating point types to integer for
** builds on processors without floating point support.
*/
#ifdef VTK_SQLITE_OMIT_FLOATING_POINT
# undef double
#endif

#if 0
}  /* End of the 'extern "C"' block */
#endif
#endif

/************** End of vtk_sqlite3.h *********************************************/
/************** Begin file date.c ********************************************/
/*
** 2003 October 31
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the C functions that implement date and time
** functions for Vtk_Sqlite.  
**
** There is only one exported symbol in this file - the function
** vtk_sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
** All other code has file scope.
**
** $Id: vtk_sqlite3.c,v 1.15 2007/09/20 18:33:36 king Exp $
**
** Vtk_Sqlite processes all times and dates as Julian Day numbers.  The
** dates and times are stored as the number of days since noon
** in Greenwich on November 24, 4714 B.C. according to the Gregorian
** calendar system. 
**
** 1970-01-01 00:00:00 is JD 2440587.5
** 2000-01-01 00:00:00 is JD 2451544.5
**
** This implemention requires years to be expressed as a 4-digit number
** which means that only dates between 0000-01-01 and 9999-12-31 can
** be represented, even though julian day numbers allow a much wider
** range of dates.
**
** The Gregorian calendar system is used for all dates and times,
** even those that predate the Gregorian calendar.  Historians usually
** use the Julian calendar for dates prior to 1582-10-15 and for some
** dates afterwards, depending on locale.  Beware of this difference.
**
** The conversion algorithms are implemented based on descriptions
** in the following text:
**
**      Jean Meeus
**      Astronomical Algorithms, 2nd Edition, 1998
**      ISBM 0-943396-61-1
**      Willmann-Bell, Inc
**      Richmond, Virginia (USA)
*/
/************** Include vtk_sqliteInt.h in the middle of date.c ******************/
/************** Begin file vtk_sqliteInt.h ***************************************/
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Internal interface definitions for Vtk_Sqlite.
**
** @(#) $Id: vtk_sqlite3.c,v 1.15 2007/09/20 18:33:36 king Exp $
*/
#ifndef _VTK_SQLITEINT_H_
#define _VTK_SQLITEINT_H_
/************** Include vtk_sqliteLimit.h in the middle of vtk_sqliteInt.h ***********/
/************** Begin file vtk_sqliteLimit.h *************************************/
/*
** 2007 May 7
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** 
** This file defines various limits of what Vtk_Sqlite can process.
**
** @(#) $Id: vtk_sqlite3.c,v 1.15 2007/09/20 18:33:36 king Exp $
*/

/*
** The maximum length of a TEXT or BLOB in bytes.   This also
** limits the size of a row in a table or index.
**
** The hard limit is the ability of a 32-bit signed integer
** to count the size: 2^31-1 or 2147483647.
*/
#ifndef VTK_SQLITE_MAX_LENGTH
# define VTK_SQLITE_MAX_LENGTH 1000000000
#endif

/*
** This is the maximum number of
**
**    * Columns in a table
**    * Columns in an index
**    * Columns in a view
**    * Terms in the SET clause of an UPDATE statement
**    * Terms in the result set of a SELECT statement
**    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
**    * Terms in the VALUES clause of an INSERT statement
**
** The hard upper limit here is 32676.  Most database people will
** tell you that in a well-normalized database, you usually should
** not have more than a dozen or so columns in any table.  And if
** that is the case, there is no point in having more than a few
** dozen values in any of the other situations described above.
*/
#ifndef VTK_SQLITE_MAX_COLUMN
# define VTK_SQLITE_MAX_COLUMN 2000
#endif

/*
** The maximum length of a single SQL statement in bytes.
** The hard limit here is the same as VTK_SQLITE_MAX_LENGTH.
*/
#ifndef VTK_SQLITE_MAX_SQL_LENGTH
# define VTK_SQLITE_MAX_SQL_LENGTH 1000000
#endif

/*
** The maximum depth of an expression tree. This is limited to 
** some extent by VTK_SQLITE_MAX_SQL_LENGTH. But sometime you might 
** want to place more severe limits on the complexity of an 
** expression. A value of 0 (the default) means do not enforce
** any limitation on expression tree depth.
*/
#ifndef VTK_SQLITE_MAX_EXPR_DEPTH
# define VTK_SQLITE_MAX_EXPR_DEPTH 1000
#endif

/*
** The maximum number of terms in a compound SELECT statement.
** The code generator for compound SELECT statements does one
** level of recursion for each term.  A stack overflow can result
** if the number of terms is too large.  In practice, most SQL
** never has more than 3 or 4 terms.  Use a value of 0 to disable
** any limit on the number of terms in a compount SELECT.
*/
#ifndef VTK_SQLITE_MAX_COMPOUND_SELECT
# define VTK_SQLITE_MAX_COMPOUND_SELECT 500
#endif

/*
** The maximum number of opcodes in a VDBE program.
** Not currently enforced.
*/
#ifndef VTK_SQLITE_MAX_VDBE_OP
# define VTK_SQLITE_MAX_VDBE_OP 25000
#endif

/*
** The maximum number of arguments to an SQL function.
*/
#ifndef VTK_SQLITE_MAX_FUNCTION_ARG
# define VTK_SQLITE_MAX_FUNCTION_ARG 100
#endif

/*
** The maximum number of in-memory pages to use for the main database
** table and for temporary tables.  The VTK_SQLITE_DEFAULT_CACHE_SIZE
*/
#ifndef VTK_SQLITE_DEFAULT_CACHE_SIZE
# define VTK_SQLITE_DEFAULT_CACHE_SIZE  2000
#endif
#ifndef VTK_SQLITE_DEFAULT_TEMP_CACHE_SIZE
# define VTK_SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
#endif

/*
** The maximum number of attached databases.  This must be at least 2
** in order to support the main database file (0) and the file used to
** hold temporary tables (1).  And it must be less than 32 because
** we use a bitmask of databases with a u32 in places (for example
** the Parse.cookieMask field).
*/
#ifndef VTK_SQLITE_MAX_ATTACHED
# define VTK_SQLITE_MAX_ATTACHED 10
#endif


/*
** The maximum value of a ?nnn wildcard that the parser will accept.
*/
#ifndef VTK_SQLITE_MAX_VARIABLE_NUMBER
# define VTK_SQLITE_MAX_VARIABLE_NUMBER 999
#endif

/*
** The default size of a database page.
*/
#ifndef VTK_SQLITE_DEFAULT_PAGE_SIZE
# define VTK_SQLITE_DEFAULT_PAGE_SIZE 1024
#endif

/* Maximum page size.  The upper bound on this value is 32768.  This a limit
** imposed by the necessity of storing the value in a 2-byte unsigned integer
** and the fact that the page size must be a power of 2.
*/
#ifndef VTK_SQLITE_MAX_PAGE_SIZE
# define VTK_SQLITE_MAX_PAGE_SIZE 32768
#endif

/*
** Maximum number of pages in one database file.
**
** This is really just the default value for the max_page_count pragma.
** This value can be lowered (or raised) at run-time using that the
** max_page_count macro.
*/
#ifndef VTK_SQLITE_MAX_PAGE_COUNT
# define VTK_SQLITE_MAX_PAGE_COUNT 1073741823
#endif

/*
** Maximum length (in bytes) of the pattern in a LIKE or GLOB
** operator.
*/
#ifndef VTK_SQLITE_MAX_LIKE_PATTERN_LENGTH
# define VTK_SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
#endif

/************** End of vtk_sqliteLimit.h *****************************************/
/************** Continuing where we left off in vtk_sqliteInt.h ******************/


#if defined(VTK_SQLITE_TCL) || defined(TCLSH)
# include <tcl.h>
#endif

/*
** Many people are failing to set -DNDEBUG=1 when compiling Vtk_Sqlite.
** Setting NDEBUG makes the code smaller and run faster.  So the following
** lines are added to automatically set NDEBUG unless the -DVTK_SQLITE_DEBUG=1
** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
** feature.
*/
#if !defined(NDEBUG) && !defined(VTK_SQLITE_DEBUG) 
# define NDEBUG 1
#endif

/*
** These #defines should enable >2GB file support on Posix if the
** underlying operating system supports it.  If the OS lacks
** large file support, or if the OS is windows, these should be no-ops.
**
** Large file support can be disabled using the -DVTK_SQLITE_DISABLE_LFS switch
** on the compiler command line.  This is necessary if you are compiling
** on a recent machine (ex: RedHat 7.2) but you want your code to work
** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
** without this option, LFS is enable.  But LFS does not exist in the kernel
** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
** portability you should omit LFS.
**
** Similar is true for MacOS.  LFS is only supported on MacOS 9 and later.
*/
#ifndef VTK_SQLITE_DISABLE_LFS
# define _LARGE_FILE       1
# ifndef _FILE_OFFSET_BITS
#   define _FILE_OFFSET_BITS 64
# endif
# define _LARGEFILE_SOURCE 1
#endif

/************** Include hash.h in the middle of vtk_sqliteInt.h ******************/
/************** Begin file hash.h ********************************************/
/*
** 2001 September 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This is the header file for the generic hash-table implemenation
** used in Vtk_Sqlite.
**
** $Id: vtk_sqlite3.c,v 1.15 2007/09/20 18:33:36 king Exp $
*/
#ifndef _VTK_SQLITE_HASH_H_
#define _VTK_SQLITE_HASH_H_

/* Forward declarations of structures. */
typedef struct Hash Hash;
typedef struct HashElem HashElem;

/* A complete hash table is an instance of the following structure.
** The internals of this structure are intended to be opaque -- client
** code should not attempt to access or modify the fields of this structure
** directly.  Change this structure only by using the routines below.
** However, many of the "procedures" and "functions" for modifying and
** accessing this structure are really macros, so we can't really make
** this structure opaque.
*/
struct Hash {
  char keyClass;          /* VTK_SQLITE_HASH_INT, _POINTER, _STRING, _BINARY */
  char copyKey;           /* True if copy of key made on insert */
  int count;              /* Number of entries in this table */
  HashElem *first;        /* The first element of the array */
  void *(*xMalloc)(int);  /* malloc() function to use */
  void (*xFree)(void *);  /* free() function to use */
  int htsize;             /* Number of buckets in the hash table */
  struct _ht {            /* the hash table */
    int count;               /* Number of entries with this hash */
    HashElem *chain;         /* Pointer to first entry with this hash */
  } *ht;
};

/* Each element in the hash table is an instance of the following 
** structure.  All elements are stored on a single doubly-linked list.
**
** Again, this structure is intended to be opaque, but it can't really
** be opaque because it is used by macros.
*/
struct HashElem {
  HashElem *next, *prev;   /* Next and previous elements in the table */
  void *data;              /* Data associated with this element */
  void *pKey; int nKey;    /* Key associated with this element */
};

/*
** There are 4 different modes of operation for a hash table:
**
**   VTK_SQLITE_HASH_INT         nKey is used as the key and pKey is ignored.
**
**   VTK_SQLITE_HASH_POINTER     pKey is used as the key and nKey is ignored.
**
**   VTK_SQLITE_HASH_STRING      pKey points to a string that is nKey bytes long
**                           (including the null-terminator, if any).  Case
**                           is ignored in comparisons.
**
**   VTK_SQLITE_HASH_BINARY      pKey points to binary data nKey bytes long. 
**                           memcmp() is used to compare keys.
**
** A copy of the key is made for VTK_SQLITE_HASH_STRING and VTK_SQLITE_HASH_BINARY
** if the copyKey parameter to HashInit is 1.  
*/
/* #define VTK_SQLITE_HASH_INT       1 // NOT USED */
/* #define VTK_SQLITE_HASH_POINTER   2 // NOT USED */
#define VTK_SQLITE_HASH_STRING    3
#define VTK_SQLITE_HASH_BINARY    4

/*
** Access routines.  To delete, insert a NULL pointer.
*/
VTK_SQLITE_PRIVATE void vtk_sqlite3HashInit(Hash*, int keytype, int copyKey);
VTK_SQLITE_PRIVATE void *vtk_sqlite3HashInsert(Hash*, const void *pKey, int nKey, void *pData);
VTK_SQLITE_PRIVATE void *vtk_sqlite3HashFind(const Hash*, const void *pKey, int nKey);
VTK_SQLITE_PRIVATE void vtk_sqlite3HashClear(Hash*);

/*
** Macros for looping over all elements of a hash table.  The idiom is
** like this:
**
**   Hash h;
**   HashElem *p;
**   ...
**   for(p=vtk_sqliteHashFirst(&h); p; p=vtk_sqliteHashNext(p)){
**     SomeStructure *pData = vtk_sqliteHashData(p);
**     // do something with pData
**   }
*/
#define vtk_sqliteHashFirst(H)  ((H)->first)
#define vtk_sqliteHashNext(E)   ((E)->next)
#define vtk_sqliteHashData(E)   ((E)->data)
#define vtk_sqliteHashKey(E)    ((E)->pKey)
#define vtk_sqliteHashKeysize(E) ((E)->nKey)

/*
** Number of entries in a hash table
*/
#define vtk_sqliteHashCount(H)  ((H)->count)

#endif /* _VTK_SQLITE_HASH_H_ */

/************** End of hash.h ************************************************/
/************** Continuing where we left off in vtk_sqliteInt.h ******************/
/************** Include parse.h in the middle of vtk_sqliteInt.h *****************/
/************** Begin file parse.h *******************************************/
#define TK_SEMI                            1
#define TK_EXPLAIN                         2
#define TK_QUERY                           3
#define TK_PLAN                            4
#define TK_BEGIN                           5
#define TK_TRANSACTION                     6
#define TK_DEFERRED                        7
#define TK_IMMEDIATE                       8
#define TK_EXCLUSIVE                       9
#define TK_COMMIT                         10
#define TK_END                            11
#define TK_ROLLBACK                       12
#define TK_CREATE                         13
#define TK_TABLE                          14
#define TK_IF                             15
#define TK_NOT                            16
#define TK_EXISTS                         17
#define TK_TEMP                           18
#define TK_LP                             19
#define TK_RP                             20
#define TK_AS                             21
#define TK_COMMA                          22
#define TK_ID                             23
#define TK_ABORT                          24
#define TK_AFTER                          25
#define TK_ANALYZE                        26
#define TK_ASC                            27
#define TK_ATTACH                         28
#define TK_BEFORE                         29
#define TK_CASCADE                        30
#define TK_CAST                           31
#define TK_CONFLICT                       32
#define TK_DATABASE                       33
#define TK_DESC                           34
#define TK_DETACH                         35
#define TK_EACH                           36
#define TK_FAIL                           37
#define TK_FOR                            38
#define TK_IGNORE                         39
#define TK_INITIALLY                      40
#define TK_INSTEAD                        41
#define TK_LIKE_KW                        42
#define TK_MATCH                          43
#define TK_KEY                            44
#define TK_OF                             45
#define TK_OFFSET                         46
#define TK_PRAGMA                         47
#define TK_RAISE                          48
#define TK_REPLACE                        49
#define TK_RESTRICT                       50
#define TK_ROW                            51
#define TK_TRIGGER                        52
#define TK_VACUUM                         53
#define TK_VIEW                           54
#define TK_VIRTUAL                        55
#define TK_REINDEX                        56
#define TK_RENAME                         57
#define TK_CTIME_KW                       58
#define TK_ANY                            59
#define TK_OR                             60
#define TK_AND                            61
#define TK_IS                             62
#define TK_BETWEEN                        63
#define TK_IN                             64
#define TK_ISNULL                         65
#define TK_NOTNULL                        66
#define TK_NE                             67
#define TK_EQ                             68
#define TK_GT                             69
#define TK_LE                             70
#define TK_LT                             71
#define TK_GE                             72
#define TK_ESCAPE                         73
#define TK_BITAND                         74
#define TK_BITOR                          75
#define TK_LSHIFT                         76
#define TK_RSHIFT                         77
#define TK_PLUS                           78
#define TK_MINUS                          79
#define TK_STAR                           80
#define TK_SLASH                          81
#define TK_REM                            82
#define TK_CONCAT                         83
#define TK_COLLATE                        84
#define TK_UMINUS                         85
#define TK_UPLUS                          86
#define TK_BITNOT                         87
#define TK_STRING                         88
#define TK_JOIN_KW                        89
#define TK_CONSTRAINT                     90
#define TK_DEFAULT                        91
#define TK_NULL                           92
#define TK_PRIMARY                        93
#define TK_UNIQUE                         94
#define TK_CHECK                          95
#define TK_REFERENCES                     96
#define TK_AUTOINCR                       97
#define TK_ON                             98
#define TK_DELETE                         99
#define TK_UPDATE                         100
#define TK_INSERT                         101
#define TK_SET                            102
#define TK_DEFERRABLE                     103
#define TK_FOREIGN                        104
#define TK_DROP                           105
#define TK_UNION                          106
#define TK_ALL                            107
#define TK_EXCEPT                         108
#define TK_INTERSECT                      109
#define TK_SELECT                         110
#define TK_DISTINCT                       111
#define TK_DOT                            112
#define TK_FROM                           113
#define TK_JOIN                           114
#define TK_USING                          115
#define TK_ORDER                          116
#define TK_BY                             117
#define TK_GROUP                          118
#define TK_HAVING                         119
#define TK_LIMIT                          120
#define TK_WHERE                          121
#define TK_INTO                           122
#define TK_VALUES                         123
#define TK_INTEGER                        124
#define TK_FLOAT                          125
#define TK_BLOB                           126
#define TK_REGISTER                       127
#define TK_VARIABLE                       128
#define TK_CASE                           129
#define TK_WHEN                           130
#define TK_THEN                           131
#define TK_ELSE                           132
#define TK_INDEX                          133
#define TK_ALTER                          134
#define TK_TO                             135
#define TK_ADD                            136
#define TK_COLUMNKW                       137
#define TK_TO_TEXT                        138
#define TK_TO_BLOB                        139
#define TK_TO_NUMERIC                     140
#define TK_TO_INT                         141
#define TK_TO_REAL                        142
#define TK_END_OF_FILE                    143
#define TK_ILLEGAL                        144
#define TK_SPACE                          145
#define TK_UNCLOSED_STRING                146
#define TK_COMMENT                        147
#define TK_FUNCTION                       148
#define TK_COLUMN                         149
#define TK_AGG_FUNCTION                   150
#define TK_AGG_COLUMN                     151
#define TK_CONST_FUNC                     152

/************** End of parse.h ***********************************************/
/************** Continuing where we left off in vtk_sqliteInt.h ******************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stddef.h>

#define vtk_sqlite3_isnan(X)  ((X)!=(X))

/*
** If compiling for a processor that lacks floating point support,
** substitute integer for floating-point
*/
#ifdef VTK_SQLITE_OMIT_FLOATING_POINT
# define double vtk_sqlite_int64
# define LONGDOUBLE_TYPE vtk_sqlite_int64
# ifndef VTK_SQLITE_BIG_DBL
#   define VTK_SQLITE_BIG_DBL (0x7fffffffffffffff)
# endif
# define VTK_SQLITE_OMIT_DATETIME_FUNCS 1
# define VTK_SQLITE_OMIT_TRACE 1
# undef VTK_SQLITE_MIXED_ENDIAN_64BIT_FLOAT
#endif
#ifndef VTK_SQLITE_BIG_DBL
# define VTK_SQLITE_BIG_DBL (1e99)
#endif

/*
** OMIT_TEMPDB is set to 1 if VTK_SQLITE_OMIT_TEMPDB is defined, or 0
** afterward. Having this macro allows us to cause the C compiler 
** to omit code used by TEMP tables without messy #ifndef statements.
*/
#ifdef VTK_SQLITE_OMIT_TEMPDB
#define OMIT_TEMPDB 1
#else
#define OMIT_TEMPDB 0
#endif

/*
** If the following macro is set to 1, then NULL values are considered
** distinct when determining whether or not two entries are the same
** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
** is the way things are suppose to work.
**
** If the following macro is set to 0, the NULLs are indistinct for
** a UNIQUE index.  In this mode, you can only have a single NULL entry
** for a column declared UNIQUE.  This is the way Informix and SQL Server
** work.
*/
#define NULL_DISTINCT_FOR_UNIQUE 1

/*
** The "file format" number is an integer that is incremented whenever
** the VDBE-level file format changes.  The following macros define the
** the default file format for new databases and the maximum file format
** that the library can read.
*/
#define VTK_SQLITE_MAX_FILE_FORMAT 4
#ifndef VTK_SQLITE_DEFAULT_FILE_FORMAT
# define VTK_SQLITE_DEFAULT_FILE_FORMAT 1
#endif

/*
** Provide a default value for TEMP_STORE in case it is not specified
** on the command-line
*/
#ifndef TEMP_STORE
# define TEMP_STORE 1
#endif

/*
** GCC does not define the offsetof() macro so we'll have to do it
** ourselves.
*/
#ifndef offsetof
#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
#endif

/*
** Check to see if this machine uses EBCDIC.  (Yes, believe it or
** not, there are still machines out there that use EBCDIC.)
*/
#if 'A' == '\301'
# define VTK_SQLITE_EBCDIC 1
#else
# define VTK_SQLITE_ASCII 1
#endif

/*
** Integers of known sizes.  These typedefs might change for architectures
** where the sizes very.  Preprocessor macros are available so that the
** types can be conveniently redefined at compile-type.  Like this:
**
**         cc '-DUINTPTR_TYPE=long long int' ...
*/
#ifndef UINT32_TYPE
# define UINT32_TYPE unsigned int
#endif
#ifndef UINT16_TYPE
# define UINT16_TYPE unsigned short int
#endif
#ifndef INT16_TYPE
# define INT16_TYPE short int
#endif
#ifndef UINT8_TYPE
# define UINT8_TYPE unsigned char
#endif
#ifndef INT8_TYPE
# define INT8_TYPE signed char
#endif
#ifndef LONGDOUBLE_TYPE
# define LONGDOUBLE_TYPE long double
#endif
typedef vtk_sqlite_int64 i64;          /* 8-byte signed integer */
typedef vtk_sqlite_uint64 u64;         /* 8-byte unsigned integer */
typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
typedef INT16_TYPE i16;            /* 2-byte signed integer */
typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
typedef UINT8_TYPE i8;             /* 1-byte signed integer */

/*
** Macros to determine whether the machine is big or little endian,
** evaluated at runtime.
*/
extern const int vtk_sqlite3one;
#if defined(i386) || defined(__i386__) || defined(_M_IX86)
# define VTK_SQLITE_BIGENDIAN    0
# define VTK_SQLITE_LITTLEENDIAN 1
# define VTK_SQLITE_UTF16NATIVE  VTK_SQLITE_UTF16LE
#else
# define VTK_SQLITE_BIGENDIAN    (*(char *)(&vtk_sqlite3one)==0)
# define VTK_SQLITE_LITTLEENDIAN (*(char *)(&vtk_sqlite3one)==1)
# define VTK_SQLITE_UTF16NATIVE (VTK_SQLITE_BIGENDIAN?VTK_SQLITE_UTF16BE:VTK_SQLITE_UTF16LE)
#endif

/*
** An instance of the following structure is used to store the busy-handler
** callback for a given vtk_sqlite handle. 
**
** The vtk_sqlite.busyHandler member of the vtk_sqlite struct contains the busy
** callback for the database handle. Each pager opened via the vtk_sqlite
** handle is passed a pointer to vtk_sqlite.busyHandler. The busy-handler
** callback is currently invoked only from within pager.c.
*/
typedef struct BusyHandler BusyHandler;
struct BusyHandler {
  int (*xFunc)(void *,int);  /* The busy callback */
  void *pArg;                /* First arg to busy callback */
  int nBusy;                 /* Incremented with each busy call */
};

/*
** Defer sourcing vdbe.h and btree.h until after the "u8" and 
** "BusyHandler typedefs.
*/
/************** Include vdbe.h in the middle of vtk_sqliteInt.h ******************/
/************** Begin file vdbe.h ********************************************/
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Header file for the Virtual DataBase Engine (VDBE)
**
** This header defines the interface to the virtual database engine
** or VDBE.  The VDBE implements an abstract machine that runs a
** simple program to access and modify the underlying database.
**
** $Id: vtk_sqlite3.c,v 1.15 2007/09/20 18:33:36 king Exp $
*/
#ifndef _VTK_SQLITE_VDBE_H_
#define _VTK_SQLITE_VDBE_H_

/*
** A single VDBE is an opaque structure named "Vdbe".  Only routines
** in the source file vtk_sqliteVdbe.c are allowed to see the insides
** of this structure.
*/
typedef struct Vdbe Vdbe;

/*
** A single instruction of the virtual machine has an opcode
** and as many as three operands.  The instruction is recorded
** as an instance of the following structure:
*/
struct VdbeOp {
  u8 opcode;          /* What operation to perform */
  int p1;             /* First operand */
  int p2;             /* Second parameter (often the jump destination) */
  char *p3;           /* Third parameter */
  int p3type;         /* One of the P3_xxx constants defined below */
#ifdef VDBE_PROFILE
  int cnt;            /* Number of times this instruction was executed */
  long long cycles;   /* Total time spend executing this instruction */
#endif
};
typedef struct VdbeOp VdbeOp;

/*
** A smaller version of VdbeOp used for the VdbeAddOpList() function because
** it takes up less space.
*/
struct VdbeOpList {
  u8 opcode;          /* What operation to perform */
  signed char p1;     /* First operand */
  short int p2;       /* Second parameter (often the jump destination) */
  char *p3;           /* Third parameter */
};
typedef struct VdbeOpList VdbeOpList;

/*
** Allowed values of VdbeOp.p3type
*/
#define P3_NOTUSED    0   /* The P3 parameter is not used */
#define P3_DYNAMIC  (-1)  /* Pointer to a string obtained from vtk_sqliteMalloc() */
#define P3_STATIC   (-2)  /* Pointer to a static string */
#define P3_COLLSEQ  (-4)  /* P3 is a pointer to a CollSeq structure */
#define P3_FUNCDEF  (-5)  /* P3 is a pointer to a FuncDef structure */
#define P3_KEYINFO  (-6)  /* P3 is a pointer to a KeyInfo structure */
#define P3_VDBEFUNC (-7)  /* P3 is a pointer to a VdbeFunc structure */
#define P3_MEM      (-8)  /* P3 is a pointer to a Mem*    structure */
#define P3_TRANSIENT (-9) /* P3 is a pointer to a transient string */
#define P3_VTAB     (-10) /* P3 is a pointer to an vtk_sqlite3_vtab structure */
#define P3_MPRINTF  (-11) /* P3 is a string obtained from vtk_sqlite3_mprintf() */

/* When adding a P3 argument using P3_KEYINFO, a copy of the KeyInfo structure
** is made.  That copy is freed when the Vdbe is finalized.  But if the
** argument is P3_KEYINFO_HANDOFF, the passed in pointer is used.  It still
** gets freed when the Vdbe is finalized so it still should be obtained
** from a single vtk_sqliteMalloc().  But no copy is made and the calling
** function should *not* try to free the KeyInfo.
*/
#define P3_KEYINFO_HANDOFF (-9)

/*
** The Vdbe.aColName array contains 5n Mem structures, where n is the 
** number of columns of data returned by the statement.
*/
#define COLNAME_NAME     0
#define COLNAME_DECLTYPE 1
#define COLNAME_DATABASE 2
#define COLNAME_TABLE    3
#define COLNAME_COLUMN   4
#define COLNAME_N        5      /* Number of COLNAME_xxx symbols */

/*
** The following macro converts a relative address in the p2 field
** of a VdbeOp structure into a negative number so that 
** vtk_sqlite3VdbeAddOpList() knows that the address is relative.  Calling
** the macro again restores the address.
*/
#define ADDR(X)  (-1-(X))

/*
** The makefile scans the vdbe.c source file and creates the "opcodes.h"
** header file that defines a number for each opcode used by the VDBE.
*/
/************** Include opcodes.h in the middle of vdbe.h ********************/
/************** Begin file opcodes.h *****************************************/
/* Automatically generated.  Do not edit */
/* See the mkopcodeh.awk script for details */
#define OP_MemLoad                              1
#define OP_VNext                                2
#define OP_HexBlob                            126   /* same as TK_BLOB     */
#define OP_Column                               3
#define OP_SetCookie                            4
#define OP_IfMemPos                             5
#define OP_Real                               125   /* same as TK_FLOAT    */
#define OP_Sequence                             6
#define OP_MoveGt                               7
#define OP_Ge                                  72   /* same as TK_GE       */
#define OP_RowKey                               8
#define OP_Eq                                  68   /* same as TK_EQ       */
#define OP_OpenWrite                            9
#define OP_NotNull                             66   /* same as TK_NOTNULL  */
#define OP_If                                  10
#define OP_ToInt                              141   /* same as TK_TO_INT   */
#define OP_String8                             88   /* same as TK_STRING   */
#define OP_Pop                                 11
#define OP_VRowid                              12
#define OP_CollSeq                             13
#define OP_OpenRead                            14
#define OP_Expire                              15
#define OP_AutoCommit                          17
#define OP_Gt                                  69   /* same as TK_GT       */
#define OP_IntegrityCk                         18
#define OP_Sort                                19
#define OP_Function                            20
#define OP_And                                 61   /* same as TK_AND      */
#define OP_Subtract                            79   /* same as TK_MINUS    */
#define OP_Noop                                21
#define OP_Return                              22
#define OP_Remainder                           82   /* same as TK_REM      */
#define OP_NewRowid                            23
#define OP_Multiply                            80   /* same as TK_STAR     */
#define OP_IfMemNeg                            24
#define OP_Variable                            25
#define OP_String                              26
#define OP_RealAffinity                        27
#define OP_VRename                             28
#define OP_ParseSchema                         29
#define OP_VOpen                               30
#define OP_Close                               31
#define OP_CreateIndex                         32
#define OP_IsUnique                            33
#define OP_NotFound                            34
#define OP_Int64                               35
#define OP_MustBeInt                           36
#define OP_Halt                                37
#define OP_Rowid                               38
#define OP_IdxLT                               39
#define OP_AddImm                              40
#define OP_Statement                           41
#define OP_RowData                             42
#define OP_MemMax                              43
#define OP_Push                                44
#define OP_Or                                  60   /* same as TK_OR       */
#define OP_NotExists                           45
#define OP_MemIncr                             46
#define OP_Gosub                               47
#define OP_Divide                              81   /* same as TK_SLASH    */
#define OP_Integer                             48
#define OP_ToNumeric                          140   /* same as TK_TO_NUMERIC*/
#define OP_MemInt                              49
#define OP_Prev                                50
#define OP_Concat                              83   /* same as TK_CONCAT   */
#define OP_BitAnd                              74   /* same as TK_BITAND   */
#define OP_VColumn                             51
#define OP_CreateTable                         52
#define OP_Last                                53
#define OP_IsNull                              65   /* same as TK_ISNULL   */
#define OP_IncrVacuum                          54
#define OP_IdxRowid                            55
#define OP_MakeIdxRec                          56
#define OP_ShiftRight                          77   /* same as TK_RSHIFT   */
#define OP_ResetCount                          57
#define OP_FifoWrite                           58
#define OP_Callback                            59
#define OP_ContextPush                         62
#define OP_DropTrigger                         63
#define OP_DropIndex                           64
#define OP_IdxGE                               73
#define OP_IdxDelete                           84
#define OP_Vacuum                              86
#define OP_MoveLe                              89
#define OP_IfNot                               90
#define OP_DropTable                           91
#define OP_MakeRecord                          92
#define OP_ToBlob                             139   /* same as TK_TO_BLOB  */
#define OP_Delete                              93
#define OP_AggFinal                            94
#define OP_ShiftLeft                           76   /* same as TK_LSHIFT   */
#define OP_Dup                                 95
#define OP_Goto                                96
#define OP_TableLock                           97
#define OP_FifoRead                            98
#define OP_Clear                               99
#define OP_IdxGT                              100
#define OP_MoveLt                             101
#define OP_Le                                  70   /* same as TK_LE       */
#define OP_VerifyCookie                       102
#define OP_AggStep                            103
#define OP_Pull                               104
#define OP_ToText                             138   /* same as TK_TO_TEXT  */
#define OP_Not                                 16   /* same as TK_NOT      */
#define OP_ToReal                             142   /* same as TK_TO_REAL  */
#define OP_SetNumColumns                      105
#define OP_AbsValue                           106
#define OP_Transaction                        107
#define OP_VFilter                            108
#define OP_Negative                            85   /* same as TK_UMINUS   */
#define OP_Ne                                  67   /* same as TK_NE       */
#define OP_VDestroy                           109
#define OP_ContextPop                         110
#define OP_BitOr                               75   /* same as TK_BITOR    */
#define OP_Next                               111
#define OP_IdxInsert                          112
#define OP_Distinct                           113
#define OP_Lt                                  71   /* same as TK_LT       */
#define OP_Insert                             114
#define OP_Destroy                            115
#define OP_ReadCookie                         116
#define OP_ForceInt                           117
#define OP_LoadAnalysis                       118
#define OP_Explain                            119
#define OP_IfMemZero                          120
#define OP_OpenPseudo                         121
#define OP_OpenEphemeral                      122
#define OP_Null                               123
#define OP_Blob                               124
#define OP_Add                                 78   /* same as TK_PLUS     */
#define OP_MemStore                           127
#define OP_Rewind                             128
#define OP_MoveGe                             129
#define OP_VBegin                             130
#define OP_VUpdate                            131
#define OP_BitNot                              87   /* same as TK_BITNOT   */
#define OP_VCreate                            132
#define OP_MemMove                            133
#define OP_MemNull                            134
#define OP_Found                              135
#define OP_NullRow                            136

/* The following opcode values are never used */
#define OP_NotUsed_137                        137

/* Opcodes that are guaranteed to never push a value onto the stack
** contain a 1 their corresponding position of the following mask
** set.  See the opcodeNoPush() function in vdbeaux.c  */
#define NOPUSH_MASK_0 0xeeb4
#define NOPUSH_MASK_1 0xf96b
#define NOPUSH_MASK_2 0xfbb6
#define NOPUSH_MASK_3 0xfe64
#define NOPUSH_MASK_4 0xffff
#define NOPUSH_MASK_5 0x6ef7
#define NOPUSH_MASK_6 0xfbfb
#define NOPUSH_MASK_7 0x8767
#define NOPUSH_MASK_8 0x7d9f
#define NOPUSH_MASK_9 0x0000

/************** End of opcodes.h *********************************************/
/************** Continuing where we left off in vdbe.h ***********************/

/*
** Prototypes for the VDBE interface.  See comments on the implementation
** for a description of what each of these routines does.
*/
VTK_SQLITE_PRIVATE Vdbe *vtk_sqlite3VdbeCreate(vtk_sqlite3*);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeAddOp(Vdbe*,int,int,int);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeOp3(Vdbe*,int,int,int,const char *zP3,int);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeJumpHere(Vdbe*, int addr);
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeChangeP3(Vdbe*, int addr, const char *zP1, int N);
VTK_SQLITE_PRIVATE VdbeOp *vtk_sqlite3VdbeGetOp(Vdbe*, int);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeMakeLabel(Vdbe*);
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeDelete(Vdbe*);
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeMakeReady(Vdbe*,int,int,int,int);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeFinalize(Vdbe*);
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeResolveLabel(Vdbe*, int);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeCurrentAddr(Vdbe*);
#ifdef VTK_SQLITE_DEBUG
VTK_SQLITE_PRIVATE   void vtk_sqlite3VdbeTrace(Vdbe*,FILE*);
#endif
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeResetStepResult(Vdbe*);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeReset(Vdbe*);
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeSetNumCols(Vdbe*,int);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeSetColName(Vdbe*, int, int, const char *, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeCountChanges(Vdbe*);
VTK_SQLITE_PRIVATE vtk_sqlite3 *vtk_sqlite3VdbeDb(Vdbe*);
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeSetSql(Vdbe*, const char *z, int n);
VTK_SQLITE_PRIVATE const char *vtk_sqlite3VdbeGetSql(Vdbe*);
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeSwap(Vdbe*,Vdbe*);

#ifndef NDEBUG
VTK_SQLITE_PRIVATE   void vtk_sqlite3VdbeComment(Vdbe*, const char*, ...);
# define VdbeComment(X)  vtk_sqlite3VdbeComment X
#else
# define VdbeComment(X)
#endif

#endif

/************** End of vdbe.h ************************************************/
/************** Continuing where we left off in vtk_sqliteInt.h ******************/
/************** Include btree.h in the middle of vtk_sqliteInt.h *****************/
/************** Begin file btree.h *******************************************/
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the interface that the vtk_sqlite B-Tree file
** subsystem.  See comments in the source code for a detailed description
** of what each interface routine does.
**
** @(#) $Id: vtk_sqlite3.c,v 1.15 2007/09/20 18:33:36 king Exp $
*/
#ifndef _BTREE_H_
#define _BTREE_H_

/* TODO: This definition is just included so other modules compile. It
** needs to be revisited.
*/
#define VTK_SQLITE_N_BTREE_META 10

/*
** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
*/
#ifndef VTK_SQLITE_DEFAULT_AUTOVACUUM
  #define VTK_SQLITE_DEFAULT_AUTOVACUUM 0
#endif

#define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
#define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
#define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */

/*
** Forward declarations of structure
*/
typedef struct Btree Btree;
typedef struct BtCursor BtCursor;
typedef struct BtShared BtShared;


VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeOpen(
  const char *zFilename,   /* Name of database file to open */
  vtk_sqlite3 *db,             /* Associated database connection */
  Btree **,                /* Return open Btree* here */
  int flags                /* Flags */
);

/* The flags parameter to vtk_sqlite3BtreeOpen can be the bitwise or of the
** following values.
**
** NOTE:  These values must match the corresponding PAGER_ values in
** pager.h.
*/
#define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
#define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
#define BTREE_MEMORY        4  /* In-memory DB.  No argument */

VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeClose(Btree*);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeSetBusyHandler(Btree*,BusyHandler*);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeSetCacheSize(Btree*,int);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeSetSafetyLevel(Btree*,int,int);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeSyncDisabled(Btree*);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeSetPageSize(Btree*,int,int);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeGetPageSize(Btree*);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeMaxPageCount(Btree*,int);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeGetReserve(Btree*);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeSetAutoVacuum(Btree *, int);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeGetAutoVacuum(Btree *);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeBeginTrans(Btree*,int);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeCommitPhaseTwo(Btree*);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeCommit(Btree*);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeRollback(Btree*);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeBeginStmt(Btree*);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeCommitStmt(Btree*);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeRollbackStmt(Btree*);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeCreateTable(Btree*, int*, int flags);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeIsInTrans(Btree*);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeIsInStmt(Btree*);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeIsInReadTrans(Btree*);
VTK_SQLITE_PRIVATE void *vtk_sqlite3BtreeSchema(Btree *, int, void(*)(void *));
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeSchemaLocked(Btree *);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeLockTable(Btree *, int, u8);

VTK_SQLITE_PRIVATE const char *vtk_sqlite3BtreeGetFilename(Btree *);
VTK_SQLITE_PRIVATE const char *vtk_sqlite3BtreeGetDirname(Btree *);
VTK_SQLITE_PRIVATE const char *vtk_sqlite3BtreeGetJournalname(Btree *);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeCopyFile(Btree *, Btree *);

VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeIncrVacuum(Btree *);

/* The flags parameter to vtk_sqlite3BtreeCreateTable can be the bitwise OR
** of the following flags:
*/
#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
#define BTREE_ZERODATA   2    /* Table has keys only - no data */
#define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */

VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeDropTable(Btree*, int, int*);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeClearTable(Btree*, int);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeGetMeta(Btree*, int idx, u32 *pValue);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);

VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeCursor(
  Btree*,                              /* BTree containing table to open */
  int iTable,                          /* Index of root page */
  int wrFlag,                          /* 1 for writing.  0 for read-only */
  int(*)(void*,int,const void*,int,const void*),  /* Key comparison function */
  void*,                               /* First argument to compare function */
  BtCursor **ppCursor                  /* Returned cursor */
);

VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeCloseCursor(BtCursor*);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeMoveto(BtCursor*,const void *pKey,i64 nKey,int bias,int *pRes);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeDelete(BtCursor*);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
                                  const void *pData, int nData,
                                  int nZero, int bias);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeFirst(BtCursor*, int *pRes);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeLast(BtCursor*, int *pRes);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeNext(BtCursor*, int *pRes);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeEof(BtCursor*);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeFlags(BtCursor*);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreePrevious(BtCursor*, int *pRes);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
VTK_SQLITE_PRIVATE const void *vtk_sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
VTK_SQLITE_PRIVATE const void *vtk_sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);

VTK_SQLITE_PRIVATE char *vtk_sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
VTK_SQLITE_PRIVATE struct Pager *vtk_sqlite3BtreePager(Btree*);

VTK_SQLITE_PRIVATE int vtk_sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
VTK_SQLITE_PRIVATE void vtk_sqlite3BtreeCacheOverflow(BtCursor *);

#ifdef VTK_SQLITE_TEST
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeCursorInfo(BtCursor*, int*, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3BtreeCursorList(Btree*);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreePageDump(Btree*, int, int recursive);
#endif

#endif /* _BTREE_H_ */

/************** End of btree.h ***********************************************/
/************** Continuing where we left off in vtk_sqliteInt.h ******************/
/************** Include pager.h in the middle of vtk_sqliteInt.h *****************/
/************** Begin file pager.h *******************************************/
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the interface that the vtk_sqlite page cache
** subsystem.  The page cache subsystem reads and writes a file a page
** at a time and provides a journal for rollback.
**
** @(#) $Id: vtk_sqlite3.c,v 1.15 2007/09/20 18:33:36 king Exp $
*/

#ifndef _PAGER_H_
#define _PAGER_H_

/*
** The type used to represent a page number.  The first page in a file
** is called page 1.  0 is used to represent "not a page".
*/
typedef unsigned int Pgno;

/*
** Each open file is managed by a separate instance of the "Pager" structure.
*/
typedef struct Pager Pager;

/*
** Handle type for pages.
*/
typedef struct PgHdr DbPage;

/*
** Allowed values for the flags parameter to vtk_sqlite3PagerOpen().
**
** NOTE: This values must match the corresponding BTREE_ values in btree.h.
*/
#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
#define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */

/*
** Valid values for the second argument to vtk_sqlite3PagerLockingMode().
*/
#define PAGER_LOCKINGMODE_QUERY      -1
#define PAGER_LOCKINGMODE_NORMAL      0
#define PAGER_LOCKINGMODE_EXCLUSIVE   1

/*
** See source code comments for a detailed description of the following
** routines:
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerOpen(Pager **ppPager, const char *zFilename,
                     int nExtra, int flags);
VTK_SQLITE_PRIVATE void vtk_sqlite3PagerSetBusyhandler(Pager*, BusyHandler *pBusyHandler);
VTK_SQLITE_PRIVATE void vtk_sqlite3PagerSetDestructor(Pager*, void(*)(DbPage*,int));
VTK_SQLITE_PRIVATE void vtk_sqlite3PagerSetReiniter(Pager*, void(*)(DbPage*,int));
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerSetPagesize(Pager*, int);
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerMaxPageCount(Pager*, int);
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
VTK_SQLITE_PRIVATE void vtk_sqlite3PagerSetCachesize(Pager*, int);
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerClose(Pager *pPager);
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
#define vtk_sqlite3PagerGet(A,B,C) vtk_sqlite3PagerAcquire(A,B,C,0)
VTK_SQLITE_PRIVATE DbPage *vtk_sqlite3PagerLookup(Pager *pPager, Pgno pgno);
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerRef(DbPage*);
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerUnref(DbPage*);
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerWrite(DbPage*);
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerOverwrite(Pager *pPager, Pgno pgno, void*);
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerPagecount(Pager*);
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerTruncate(Pager*,Pgno);
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerBegin(DbPage*, int exFlag);
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, Pgno);
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerCommitPhaseTwo(Pager*);
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerRollback(Pager*);
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerIsreadonly(Pager*);
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerStmtBegin(Pager*);
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerStmtCommit(Pager*);
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerStmtRollback(Pager*);
VTK_SQLITE_PRIVATE void vtk_sqlite3PagerDontRollback(DbPage*);
VTK_SQLITE_PRIVATE void vtk_sqlite3PagerDontWrite(DbPage*);
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerRefcount(Pager*);
VTK_SQLITE_PRIVATE void vtk_sqlite3PagerSetSafetyLevel(Pager*,int,int);
VTK_SQLITE_PRIVATE const char *vtk_sqlite3PagerFilename(Pager*);
VTK_SQLITE_PRIVATE const char *vtk_sqlite3PagerDirname(Pager*);
VTK_SQLITE_PRIVATE const char *vtk_sqlite3PagerJournalname(Pager*);
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerNosync(Pager*);
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerMovepage(Pager*,DbPage*,Pgno);
VTK_SQLITE_PRIVATE void *vtk_sqlite3PagerGetData(DbPage *); 
VTK_SQLITE_PRIVATE void *vtk_sqlite3PagerGetExtra(DbPage *); 
VTK_SQLITE_PRIVATE int vtk_sqlite3PagerLockingMode(Pager *, int);

#if defined(VTK_SQLITE_ENABLE_MEMORY_MANAGEMENT) && !defined(VTK_SQLITE_OMIT_DISKIO)
VTK_SQLITE_PRIVATE   int vtk_sqlite3PagerReleaseMemory(int);
#endif

#ifdef VTK_SQLITE_HAS_CODEC
VTK_SQLITE_PRIVATE   void vtk_sqlite3PagerSetCodec(Pager*,void*(*)(void*,void*,Pgno,int),void*);
#endif

#if !defined(NDEBUG) || defined(VTK_SQLITE_TEST)
VTK_SQLITE_PRIVATE   Pgno vtk_sqlite3PagerPagenumber(DbPage*);
VTK_SQLITE_PRIVATE   int vtk_sqlite3PagerIswriteable(DbPage*);
#endif

#if defined(VTK_SQLITE_DEBUG) || defined(VTK_SQLITE_TEST)
VTK_SQLITE_PRIVATE   int vtk_sqlite3PagerLockstate(Pager*);
#endif

#ifdef VTK_SQLITE_TEST
VTK_SQLITE_PRIVATE   int *vtk_sqlite3PagerStats(Pager*);
VTK_SQLITE_PRIVATE   void vtk_sqlite3PagerRefdump(Pager*);
  int pager3_refinfo_enable;
#endif

#ifdef VTK_SQLITE_TEST
void disable_simulated_io_errors(void);
void enable_simulated_io_errors(void);
#else
# define disable_simulated_io_errors()
# define enable_simulated_io_errors()
#endif

#endif /* _PAGER_H_ */

/************** End of pager.h ***********************************************/
/************** Continuing where we left off in vtk_sqliteInt.h ******************/

#ifdef VTK_SQLITE_MEMDEBUG
/*
** The following global variables are used for testing and debugging
** only.  They only work if VTK_SQLITE_MEMDEBUG is defined.
*/
extern int vtk_sqlite3_nMalloc;      /* Number of vtk_sqliteMalloc() calls */
extern int vtk_sqlite3_nFree;        /* Number of vtk_sqliteFree() calls */
extern int vtk_sqlite3_iMallocFail;  /* Fail vtk_sqliteMalloc() after this many calls */
extern int vtk_sqlite3_iMallocReset; /* Set iMallocFail to this when it reaches 0 */

extern void *vtk_sqlite3_pFirst;         /* Pointer to linked list of allocations */
extern int vtk_sqlite3_nMaxAlloc;        /* High water mark of ThreadData.nAlloc */
extern int vtk_sqlite3_mallocDisallowed; /* assert() in vtk_sqlite3Malloc() if set */
extern int vtk_sqlite3_isFail;           /* True if all malloc calls should fail */
extern const char *vtk_sqlite3_zFile;    /* Filename to associate debug info with */
extern int vtk_sqlite3_iLine;            /* Line number for debug info */

#define ENTER_MALLOC (vtk_sqlite3_zFile = __FILE__, vtk_sqlite3_iLine = __LINE__)
#define vtk_sqliteMalloc(x)          (ENTER_MALLOC, vtk_sqlite3Malloc(x,1))
#define vtk_sqliteMallocRaw(x)       (ENTER_MALLOC, vtk_sqlite3MallocRaw(x,1))
#define vtk_sqliteRealloc(x,y)       (ENTER_MALLOC, vtk_sqlite3Realloc(x,y))
#define vtk_sqliteStrDup(x)          (ENTER_MALLOC, vtk_sqlite3StrDup(x))
#define vtk_sqliteStrNDup(x,y)       (ENTER_MALLOC, vtk_sqlite3StrNDup(x,y))
#define vtk_sqliteReallocOrFree(x,y) (ENTER_MALLOC, vtk_sqlite3ReallocOrFree(x,y))

#else

#define ENTER_MALLOC 0
#define vtk_sqliteMalloc(x)          vtk_sqlite3Malloc(x,1)
#define vtk_sqliteMallocRaw(x)       vtk_sqlite3MallocRaw(x,1)
#define vtk_sqliteRealloc(x,y)       vtk_sqlite3Realloc(x,y)
#define vtk_sqliteStrDup(x)          vtk_sqlite3StrDup(x)
#define vtk_sqliteStrNDup(x,y)       vtk_sqlite3StrNDup(x,y)
#define vtk_sqliteReallocOrFree(x,y) vtk_sqlite3ReallocOrFree(x,y)

#endif

/* Variable vtk_sqlite3_mallocHasFailed is set to true after a malloc() 
** failure occurs. 
**
** The vtk_sqlite3MallocFailed() macro returns true if a malloc has failed
** in this thread since the last call to vtk_sqlite3ApiExit(), or false 
** otherwise.
*/
extern int vtk_sqlite3_mallocHasFailed;
#define vtk_sqlite3MallocFailed() (vtk_sqlite3_mallocHasFailed && vtk_sqlite3OsInMutex(1))

#define vtk_sqliteFree(x)          vtk_sqlite3FreeX(x)
#define vtk_sqliteAllocSize(x)     vtk_sqlite3AllocSize(x)

/*
** An instance of this structure might be allocated to store information
** specific to a single thread.
*/
struct ThreadData {
  int dummy;               /* So that this structure is never empty */

#ifdef VTK_SQLITE_ENABLE_MEMORY_MANAGEMENT
  int nSoftHeapLimit;      /* Suggested max mem allocation.  No limit if <0 */
  int nAlloc;              /* Number of bytes currently allocated */
  Pager *pPager;           /* Linked list of all pagers in this thread */
#endif

#ifndef VTK_SQLITE_OMIT_SHARED_CACHE
  u8 useSharedData;        /* True if shared pagers and schemas are enabled */
  BtShared *pBtree;        /* Linked list of all currently open BTrees */
#endif
};

/*
** Name of the master database table.  The master database table
** is a special table that holds the names and attributes of all
** user tables and indices.
*/
#define MASTER_NAME       "vtk_sqlite_master"
#define TEMP_MASTER_NAME  "vtk_sqlite_temp_master"

/*
** The root-page of the master database table.
*/
#define MASTER_ROOT       1

/*
** The name of the schema table.
*/
#define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)

/*
** A convenience macro that returns the number of elements in
** an array.
*/
#define ArraySize(X)    (sizeof(X)/sizeof(X[0]))

/*
** Forward references to structures
*/
typedef struct AggInfo AggInfo;
typedef struct AuthContext AuthContext;
typedef struct CollSeq CollSeq;
typedef struct Column Column;
typedef struct Db Db;
typedef struct Schema Schema;
typedef struct Expr Expr;
typedef struct ExprList ExprList;
typedef struct FKey FKey;
typedef struct FuncDef FuncDef;
typedef struct IdList IdList;
typedef struct Index Index;
typedef struct KeyClass KeyClass;
typedef struct KeyInfo KeyInfo;
typedef struct Module Module;
typedef struct NameContext NameContext;
typedef struct Parse Parse;
typedef struct Select Select;
typedef struct SrcList SrcList;
typedef struct ThreadData ThreadData;
typedef struct Table Table;
typedef struct TableLock TableLock;
typedef struct Token Token;
typedef struct TriggerStack TriggerStack;
typedef struct TriggerStep TriggerStep;
typedef struct Trigger Trigger;
typedef struct WhereInfo WhereInfo;
typedef struct WhereLevel WhereLevel;

/************** Include os.h in the middle of vtk_sqliteInt.h ********************/
/************** Begin file os.h **********************************************/
/*
** 2001 September 16
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This header file (together with is companion C source-code file
** "os.c") attempt to abstract the underlying operating system so that
** the Vtk_Sqlite library will work on both POSIX and windows systems.
*/
#ifndef _VTK_SQLITE_OS_H_
#define _VTK_SQLITE_OS_H_

/*
** Figure out if we are dealing with Unix, Windows, or some other
** operating system.
*/
#if defined(OS_OTHER)
# if OS_OTHER==1
#   undef OS_UNIX
#   define OS_UNIX 0
#   undef OS_WIN
#   define OS_WIN 0
#   undef OS_OS2
#   define OS_OS2 0
# else
#   undef OS_OTHER
# endif
#endif
#if !defined(OS_UNIX) && !defined(OS_OTHER)
# define OS_OTHER 0
# ifndef OS_WIN
#   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
#     define OS_WIN 1
#     define OS_UNIX 0
#     define OS_OS2 0
#   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
#     define OS_WIN 0
#     define OS_UNIX 0
#     define OS_OS2 1
#   else
#     define OS_WIN 0
#     define OS_UNIX 1
#     define OS_OS2 0
#  endif
# else
#  define OS_UNIX 0
#  define OS_OS2 0
# endif
#else
# ifndef OS_WIN
#  define OS_WIN 0
# endif
#endif


/*
** Define the maximum size of a temporary filename
*/
#if OS_WIN
# include <windows.h>
# define VTK_SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
#elif OS_OS2
# if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
#  include <os2safe.h> /* has to be included before os2.h for linking to work */
# endif
# define INCL_DOSDATETIME
# define INCL_DOSFILEMGR
# define INCL_DOSERRORS
# define INCL_DOSMISC
# define INCL_DOSPROCESS
# define INCL_DOSMODULEMGR
# include <os2.h>
# define VTK_SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
#else
# define VTK_SQLITE_TEMPNAME_SIZE 200
#endif

/* If the SET_FULLSYNC macro is not defined above, then make it
** a no-op
*/
#ifndef SET_FULLSYNC
# define SET_FULLSYNC(x,y)
#endif

/*
** The default size of a disk sector
*/
#ifndef VTK_SQLITE_DEFAULT_SECTOR_SIZE
# define VTK_SQLITE_DEFAULT_SECTOR_SIZE 512
#endif

/*
** Temporary files are named starting with this prefix followed by 16 random
** alphanumeric characters, and no file extension. They are stored in the
** OS's standard temporary file directory, and are deleted prior to exit.
** If vtk_sqlite is being embedded in another program, you may wish to change the
** prefix to reflect your program's name, so that if your program exits
** prematurely, old temporary files can be easily identified. This can be done
** using -DTEMP_FILE_PREFIX=myprefix_ on the compiler command line.
**
** 2006-10-31:  The default prefix used to be "vtk_sqlite_".  But then
** Mcafee started using Vtk_Sqlite in their anti-virus product and it
** started putting files with the "vtk_sqlite" name in the c:/temp folder.
** This annoyed many windows users.  Those users would then do a 
** Google search for "vtk_sqlite", find the telephone numbers of the
** developers and call to wake them up at night and complain.
** For this reason, the default name prefix is changed to be "vtk_sqlite" 
** spelled backwards.  So the temp files are still identified, but
** anybody smart enough to figure out the code is also likely smart
** enough to know that calling the developer will not help get rid
** of the file.
*/
#ifndef TEMP_FILE_PREFIX
# define TEMP_FILE_PREFIX "etilqs_"
#endif

/*
** Define the interfaces for Unix, Windows, and OS/2.
*/
#if OS_UNIX
#define vtk_sqlite3OsOpenReadWrite      vtk_sqlite3UnixOpenReadWrite
#define vtk_sqlite3OsOpenExclusive      vtk_sqlite3UnixOpenExclusive
#define vtk_sqlite3OsOpenReadOnly       vtk_sqlite3UnixOpenReadOnly
#define vtk_sqlite3OsDelete             vtk_sqlite3UnixDelete
#define vtk_sqlite3OsFileExists         vtk_sqlite3UnixFileExists
#define vtk_sqlite3OsFullPathname       vtk_sqlite3UnixFullPathname
#define vtk_sqlite3OsIsDirWritable      vtk_sqlite3UnixIsDirWritable
#define vtk_sqlite3OsSyncDirectory      vtk_sqlite3UnixSyncDirectory
#define vtk_sqlite3OsTempFileName       vtk_sqlite3UnixTempFileName
#define vtk_sqlite3OsRandomSeed         vtk_sqlite3UnixRandomSeed
#define vtk_sqlite3OsSleep              vtk_sqlite3UnixSleep
#define vtk_sqlite3OsCurrentTime        vtk_sqlite3UnixCurrentTime
#define vtk_sqlite3OsEnterMutex         vtk_sqlite3UnixEnterMutex
#define vtk_sqlite3OsLeaveMutex         vtk_sqlite3UnixLeaveMutex
#define vtk_sqlite3OsInMutex            vtk_sqlite3UnixInMutex
#define vtk_sqlite3OsThreadSpecificData vtk_sqlite3UnixThreadSpecificData
#define vtk_sqlite3OsMalloc             vtk_sqlite3GenericMalloc
#define vtk_sqlite3OsRealloc            vtk_sqlite3GenericRealloc
#define vtk_sqlite3OsFree               vtk_sqlite3GenericFree
#define vtk_sqlite3OsAllocationSize     vtk_sqlite3GenericAllocationSize
#define vtk_sqlite3OsDlopen             vtk_sqlite3UnixDlopen
#define vtk_sqlite3OsDlsym              vtk_sqlite3UnixDlsym
#define vtk_sqlite3OsDlclose            vtk_sqlite3UnixDlclose
#endif
#if OS_WIN
#define vtk_sqlite3OsOpenReadWrite      vtk_sqlite3WinOpenReadWrite
#define vtk_sqlite3OsOpenExclusive      vtk_sqlite3WinOpenExclusive
#define vtk_sqlite3OsOpenReadOnly       vtk_sqlite3WinOpenReadOnly
#define vtk_sqlite3OsDelete             vtk_sqlite3WinDelete
#define vtk_sqlite3OsFileExists         vtk_sqlite3WinFileExists
#define vtk_sqlite3OsFullPathname       vtk_sqlite3WinFullPathname
#define vtk_sqlite3OsIsDirWritable      vtk_sqlite3WinIsDirWritable
#define vtk_sqlite3OsSyncDirectory      vtk_sqlite3WinSyncDirectory
#define vtk_sqlite3OsTempFileName       vtk_sqlite3WinTempFileName
#define vtk_sqlite3OsRandomSeed         vtk_sqlite3WinRandomSeed
#define vtk_sqlite3OsSleep              vtk_sqlite3WinSleep
#define vtk_sqlite3OsCurrentTime        vtk_sqlite3WinCurrentTime
#define vtk_sqlite3OsEnterMutex         vtk_sqlite3WinEnterMutex
#define vtk_sqlite3OsLeaveMutex         vtk_sqlite3WinLeaveMutex
#define vtk_sqlite3OsInMutex            vtk_sqlite3WinInMutex
#define vtk_sqlite3OsThreadSpecificData vtk_sqlite3WinThreadSpecificData
#define vtk_sqlite3OsMalloc             vtk_sqlite3GenericMalloc
#define vtk_sqlite3OsRealloc            vtk_sqlite3GenericRealloc
#define vtk_sqlite3OsFree               vtk_sqlite3GenericFree
#define vtk_sqlite3OsAllocationSize     vtk_sqlite3GenericAllocationSize
#define vtk_sqlite3OsDlopen             vtk_sqlite3WinDlopen
#define vtk_sqlite3OsDlsym              vtk_sqlite3WinDlsym
#define vtk_sqlite3OsDlclose            vtk_sqlite3WinDlclose
#endif
#if OS_OS2
#define vtk_sqlite3OsOpenReadWrite      vtk_sqlite3Os2OpenReadWrite
#define vtk_sqlite3OsOpenExclusive      vtk_sqlite3Os2OpenExclusive
#define vtk_sqlite3OsOpenReadOnly       vtk_sqlite3Os2OpenReadOnly
#define vtk_sqlite3OsDelete             vtk_sqlite3Os2Delete
#define vtk_sqlite3OsFileExists         vtk_sqlite3Os2FileExists
#define vtk_sqlite3OsFullPathname       vtk_sqlite3Os2FullPathname
#define vtk_sqlite3OsIsDirWritable      vtk_sqlite3Os2IsDirWritable
#define vtk_sqlite3OsSyncDirectory      vtk_sqlite3Os2SyncDirectory
#define vtk_sqlite3OsTempFileName       vtk_sqlite3Os2TempFileName
#define vtk_sqlite3OsRandomSeed         vtk_sqlite3Os2RandomSeed
#define vtk_sqlite3OsSleep              vtk_sqlite3Os2Sleep
#define vtk_sqlite3OsCurrentTime        vtk_sqlite3Os2CurrentTime
#define vtk_sqlite3OsEnterMutex         vtk_sqlite3Os2EnterMutex
#define vtk_sqlite3OsLeaveMutex         vtk_sqlite3Os2LeaveMutex
#define vtk_sqlite3OsInMutex            vtk_sqlite3Os2InMutex
#define vtk_sqlite3OsThreadSpecificData vtk_sqlite3Os2ThreadSpecificData
#define vtk_sqlite3OsMalloc             vtk_sqlite3GenericMalloc
#define vtk_sqlite3OsRealloc            vtk_sqlite3GenericRealloc
#define vtk_sqlite3OsFree               vtk_sqlite3GenericFree
#define vtk_sqlite3OsAllocationSize     vtk_sqlite3GenericAllocationSize
#define vtk_sqlite3OsDlopen             vtk_sqlite3Os2Dlopen
#define vtk_sqlite3OsDlsym              vtk_sqlite3Os2Dlsym
#define vtk_sqlite3OsDlclose            vtk_sqlite3Os2Dlclose
#endif




/*
** If using an alternative OS interface, then we must have an "os_other.h"
** header file available for that interface.  Presumably the "os_other.h"
** header file contains #defines similar to those above.
*/
#if OS_OTHER
# include "os_other.h"
#endif



/*
** Forward declarations
*/
typedef struct OsFile OsFile;
typedef struct IoMethod IoMethod;

/*
** An instance of the following structure contains pointers to all
** methods on an OsFile object.
*/
struct IoMethod {
  int (*xClose)(OsFile**);
  int (*xOpenDirectory)(OsFile*, const char*);
  int (*xRead)(OsFile*, void*, int amt);
  int (*xWrite)(OsFile*, const void*, int amt);
  int (*xSeek)(OsFile*, i64 offset);
  int (*xTruncate)(OsFile*, i64 size);
  int (*xSync)(OsFile*, int);
  void (*xSetFullSync)(OsFile *id, int setting);
  int (*xFileHandle)(OsFile *id);
  int (*xFileSize)(OsFile*, i64 *pSize);
  int (*xLock)(OsFile*, int);
  int (*xUnlock)(OsFile*, int);
  int (*xLockState)(OsFile *id);
  int (*xCheckReservedLock)(OsFile *id);
  int (*xSectorSize)(OsFile *id);
};

/*
** The OsFile object describes an open disk file in an OS-dependent way.
** The version of OsFile defined here is a generic version.  Each OS
** implementation defines its own subclass of this structure that contains
** additional information needed to handle file I/O.  But the pMethod
** entry (pointing to the virtual function table) always occurs first
** so that we can always find the appropriate methods.
*/
struct OsFile {
  IoMethod const *pMethod;
};

/*
** The following values may be passed as the second argument to
** vtk_sqlite3OsLock(). The various locks exhibit the following semantics:
**
** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
** RESERVED:  A single process may hold a RESERVED lock on a file at
**            any time. Other processes may hold and obtain new SHARED locks.
** PENDING:   A single process may hold a PENDING lock on a file at
**            any one time. Existing SHARED locks may persist, but no new
**            SHARED locks may be obtained by other processes.
** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
**
** PENDING_LOCK may not be passed directly to vtk_sqlite3OsLock(). Instead, a
** process that requests an EXCLUSIVE lock may actually obtain a PENDING
** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
** vtk_sqlite3OsLock().
*/
#define NO_LOCK         0
#define SHARED_LOCK     1
#define RESERVED_LOCK   2
#define PENDING_LOCK    3
#define EXCLUSIVE_LOCK  4

/*
** File Locking Notes:  (Mostly about windows but also some info for Unix)
**
** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
** those functions are not available.  So we use only LockFile() and
** UnlockFile().
**
** LockFile() prevents not just writing but also reading by other processes.
** A SHARED_LOCK is obtained by locking a single randomly-chosen 
** byte out of a specific range of bytes. The lock byte is obtained at 
** random so two separate readers can probably access the file at the 
** same time, unless they are unlucky and choose the same lock byte.
** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
** There can only be one writer.  A RESERVED_LOCK is obtained by locking
** a single byte of the file that is designated as the reserved lock byte.
** A PENDING_LOCK is obtained by locking a designated byte different from
** the RESERVED_LOCK byte.
**
** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
** which means we can use reader/writer locks.  When reader/writer locks
** are used, the lock is placed on the same range of bytes that is used
** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
** will support two or more Win95 readers or two or more WinNT readers.
** But a single Win95 reader will lock out all WinNT readers and a single
** WinNT reader will lock out all other Win95 readers.
**
** The following #defines specify the range of bytes used for locking.
** SHARED_SIZE is the number of bytes available in the pool from which
** a random byte is selected for a shared lock.  The pool of bytes for
** shared locks begins at SHARED_FIRST. 
**
** These #defines are available in vtk_sqlite_aux.h so that adaptors for
** connecting Vtk_Sqlite to other operating systems can use the same byte
** ranges for locking.  In particular, the same locking strategy and
** byte ranges are used for Unix.  This leaves open the possiblity of having
** clients on win95, winNT, and unix all talking to the same shared file
** and all locking correctly.  To do so would require that samba (or whatever
** tool is being used for file sharing) implements locks correctly between
** windows and unix.  I'm guessing that isn't likely to happen, but by
** using the same locking range we are at least open to the possibility.
**
** Locking in windows is manditory.  For this reason, we cannot store
** actual data in the bytes used for locking.  The pager never allocates
** the pages involved in locking therefore.  SHARED_SIZE is selected so
** that all locks will fit on a single page even at the minimum page size.
** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
** is set high so that we don't have to allocate an unused page except
** for very large databases.  But one should test the page skipping logic 
** by setting PENDING_BYTE low and running the entire regression suite.
**
** Changing the value of PENDING_BYTE results in a subtly incompatible
** file format.  Depending on how it is changed, you might not notice
** the incompatibility right away, even running a full regression test.
** The default location of PENDING_BYTE is the first byte past the
** 1GB boundary.
**
*/
#ifndef VTK_SQLITE_TEST
#define PENDING_BYTE      0x40000000  /* First byte past the 1GB boundary */
#else
extern unsigned int vtk_sqlite3_pending_byte;
#define PENDING_BYTE vtk_sqlite3_pending_byte
#endif

#define RESERVED_BYTE     (PENDING_BYTE+1)
#define SHARED_FIRST      (PENDING_BYTE+2)
#define SHARED_SIZE       510

/*
** Prototypes for operating system interface routines.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3OsClose(OsFile**);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsOpenDirectory(OsFile*, const char*);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsRead(OsFile*, void*, int amt);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsWrite(OsFile*, const void*, int amt);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsSeek(OsFile*, i64 offset);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsTruncate(OsFile*, i64 size);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsSync(OsFile*, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3OsSetFullSync(OsFile *id, int setting);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsFileSize(OsFile*, i64 *pSize);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsLock(OsFile*, int);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsUnlock(OsFile*, int);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsCheckReservedLock(OsFile *id);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsOpenReadWrite(const char*, OsFile**, int*);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsOpenExclusive(const char*, OsFile**, int);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsOpenReadOnly(const char*, OsFile**);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsDelete(const char*);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsFileExists(const char*);
VTK_SQLITE_PRIVATE char *vtk_sqlite3OsFullPathname(const char*);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsIsDirWritable(char*);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsSyncDirectory(const char*);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsSectorSize(OsFile *id);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsTempFileName(char*);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsRandomSeed(char*);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsSleep(int ms);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsCurrentTime(double*);
VTK_SQLITE_PRIVATE void vtk_sqlite3OsEnterMutex(void);
VTK_SQLITE_PRIVATE void vtk_sqlite3OsLeaveMutex(void);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsInMutex(int);
VTK_SQLITE_PRIVATE ThreadData *vtk_sqlite3OsThreadSpecificData(int);
VTK_SQLITE_PRIVATE void *vtk_sqlite3OsMalloc(int);
VTK_SQLITE_PRIVATE void *vtk_sqlite3OsRealloc(void *, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3OsFree(void *);
/* function is defined but never used */
/* We can get rid of this because REDEF_IO is off */
/* VTK_SQLITE_PRIVATE int vtk_sqlite3OsAllocationSize(void *); */

#ifndef VTK_SQLITE_OMIT_LOAD_EXTENSION
VTK_SQLITE_PRIVATE void *vtk_sqlite3OsDlopen(const char*);
VTK_SQLITE_PRIVATE void *vtk_sqlite3OsDlsym(void*, const char*);
VTK_SQLITE_PRIVATE int vtk_sqlite3OsDlclose(void*);
#endif

#if defined(VTK_SQLITE_TEST) || defined(VTK_SQLITE_DEBUG)
VTK_SQLITE_PRIVATE   int vtk_sqlite3OsFileHandle(OsFile *id);
VTK_SQLITE_PRIVATE   int vtk_sqlite3OsLockState(OsFile *id);
#endif

/*
** If the VTK_SQLITE_ENABLE_REDEF_IO macro is defined, then the OS-layer
** interface routines are not called directly but are invoked using
** pointers to functions.  This allows the implementation of various
** OS-layer interface routines to be modified at run-time.  There are
** obscure but legitimate reasons for wanting to do this.  But for
** most users, a direct call to the underlying interface is preferable
** so the the redefinable I/O interface is turned off by default.
*/
#ifdef VTK_SQLITE_ENABLE_REDEF_IO

/*
** When redefinable I/O is enabled, a single global instance of the
** following structure holds pointers to the routines that Vtk_Sqlite 
** uses to talk with the underlying operating system.  Modify this
** structure (before using any Vtk_Sqlite API!) to accomodate perculiar
** operating system interfaces or behaviors.
*/
struct vtk_sqlite3OsVtbl {
  int (*xOpenReadWrite)(const char*, OsFile**, int*);
  int (*xOpenExclusive)(const char*, OsFile**, int);
  int (*xOpenReadOnly)(const char*, OsFile**);

  int (*xDelete)(const char*);
  int (*xFileExists)(const char*);
  char *(*xFullPathname)(const char*);
  int (*xIsDirWritable)(char*);
  int (*xSyncDirectory)(const char*);
  int (*xTempFileName)(char*);

  int (*xRandomSeed)(char*);
  int (*xSleep)(int ms);
  int (*xCurrentTime)(double*);

  void (*xEnterMutex)(void);
  void (*xLeaveMutex)(void);
  int (*xInMutex)(int);
  ThreadData *(*xThreadSpecificData)(int);

  void *(*xMalloc)(int);
  void *(*xRealloc)(void *, int);
  void (*xFree)(void *);
  int (*xAllocationSize)(void *);

  void *(*xDlopen)(const char*);
  void *(*xDlsym)(void*, const char*);
  int (*xDlclose)(void*);
};

/* Macro used to comment out routines that do not exists when there is
** no disk I/O or extension loading
*/
#ifdef VTK_SQLITE_OMIT_DISKIO
# define IF_DISKIO(X)  0
#else
# define IF_DISKIO(X)  X
#endif
#ifdef VTK_SQLITE_OMIT_LOAD_EXTENSION
# define IF_DLOPEN(X)  0
#else
# define IF_DLOPEN(X)  X
#endif


#if defined(_VTK_SQLITE_OS_C_) || defined(VTK_SQLITE_AMALGAMATION)
  /*
  ** The os.c file implements the global virtual function table.
  ** We have to put this file here because the initializers
  ** (ex: vtk_sqlite3OsRandomSeed) are macros that are about to be
  ** redefined.
  */
  struct vtk_sqlite3OsVtbl vtk_sqlite3Os = {
    IF_DISKIO( vtk_sqlite3OsOpenReadWrite ),
    IF_DISKIO( vtk_sqlite3OsOpenExclusive ),
    IF_DISKIO( vtk_sqlite3OsOpenReadOnly ),
    IF_DISKIO( vtk_sqlite3OsDelete ),
    IF_DISKIO( vtk_sqlite3OsFileExists ),
    IF_DISKIO( vtk_sqlite3OsFullPathname ),
    IF_DISKIO( vtk_sqlite3OsIsDirWritable ),
    IF_DISKIO( vtk_sqlite3OsSyncDirectory ),
    IF_DISKIO( vtk_sqlite3OsTempFileName ),
    vtk_sqlite3OsRandomSeed,
    vtk_sqlite3OsSleep,
    vtk_sqlite3OsCurrentTime,
    vtk_sqlite3OsEnterMutex,
    vtk_sqlite3OsLeaveMutex,
    vtk_sqlite3OsInMutex,
    vtk_sqlite3OsThreadSpecificData,
    vtk_sqlite3OsMalloc,
    vtk_sqlite3OsRealloc,
    vtk_sqlite3OsFree,
    vtk_sqlite3OsAllocationSize,
    IF_DLOPEN( vtk_sqlite3OsDlopen ),
    IF_DLOPEN( vtk_sqlite3OsDlsym ),
    IF_DLOPEN( vtk_sqlite3OsDlclose ),
  };
#else
  /*
  ** Files other than os.c just reference the global virtual function table. 
  */
  extern struct vtk_sqlite3OsVtbl vtk_sqlite3Os;
#endif /* _VTK_SQLITE_OS_C_ */


/* This additional API routine is available with redefinable I/O */
struct vtk_sqlite3OsVtbl *vtk_sqlite3_os_switch(void);


/*
** Redefine the OS interface to go through the virtual function table
** rather than calling routines directly.
*/
#undef vtk_sqlite3OsOpenReadWrite
#undef vtk_sqlite3OsOpenExclusive
#undef vtk_sqlite3OsOpenReadOnly
#undef vtk_sqlite3OsDelete
#undef vtk_sqlite3OsFileExists
#undef vtk_sqlite3OsFullPathname
#undef vtk_sqlite3OsIsDirWritable
#undef vtk_sqlite3OsSyncDirectory
#undef vtk_sqlite3OsTempFileName
#undef vtk_sqlite3OsRandomSeed
#undef vtk_sqlite3OsSleep
#undef vtk_sqlite3OsCurrentTime
#undef vtk_sqlite3OsEnterMutex
#undef vtk_sqlite3OsLeaveMutex
#undef vtk_sqlite3OsInMutex
#undef vtk_sqlite3OsThreadSpecificData
#undef vtk_sqlite3OsMalloc
#undef vtk_sqlite3OsRealloc
#undef vtk_sqlite3OsFree
#undef vtk_sqlite3OsAllocationSize
#define vtk_sqlite3OsOpenReadWrite      vtk_sqlite3Os.xOpenReadWrite
#define vtk_sqlite3OsOpenExclusive      vtk_sqlite3Os.xOpenExclusive
#define vtk_sqlite3OsOpenReadOnly       vtk_sqlite3Os.xOpenReadOnly
#define vtk_sqlite3OsDelete             vtk_sqlite3Os.xDelete
#define vtk_sqlite3OsFileExists         vtk_sqlite3Os.xFileExists
#define vtk_sqlite3OsFullPathname       vtk_sqlite3Os.xFullPathname
#define vtk_sqlite3OsIsDirWritable      vtk_sqlite3Os.xIsDirWritable
#define vtk_sqlite3OsSyncDirectory      vtk_sqlite3Os.xSyncDirectory
#define vtk_sqlite3OsTempFileName       vtk_sqlite3Os.xTempFileName
#define vtk_sqlite3OsRandomSeed         vtk_sqlite3Os.xRandomSeed
#define vtk_sqlite3OsSleep              vtk_sqlite3Os.xSleep
#define vtk_sqlite3OsCurrentTime        vtk_sqlite3Os.xCurrentTime
#define vtk_sqlite3OsEnterMutex         vtk_sqlite3Os.xEnterMutex
#define vtk_sqlite3OsLeaveMutex         vtk_sqlite3Os.xLeaveMutex
#define vtk_sqlite3OsInMutex            vtk_sqlite3Os.xInMutex
#define vtk_sqlite3OsThreadSpecificData vtk_sqlite3Os.xThreadSpecificData
#define vtk_sqlite3OsMalloc             vtk_sqlite3Os.xMalloc
#define vtk_sqlite3OsRealloc            vtk_sqlite3Os.xRealloc
#define vtk_sqlite3OsFree               vtk_sqlite3Os.xFree
#define vtk_sqlite3OsAllocationSize     vtk_sqlite3Os.xAllocationSize

#endif /* VTK_SQLITE_ENABLE_REDEF_IO */

#endif /* _VTK_SQLITE_OS_H_ */

/************** End of os.h **************************************************/
/************** Continuing where we left off in vtk_sqliteInt.h ******************/

/*
** Each database file to be accessed by the system is an instance
** of the following structure.  There are normally two of these structures
** in the vtk_sqlite.aDb[] array.  aDb[0] is the main database file and
** aDb[1] is the database file used to hold temporary tables.  Additional
** databases may be attached.
*/
struct Db {
  char *zName;         /* Name of this database */
  Btree *pBt;          /* The B*Tree structure for this database file */
  u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
  u8 safety_level;     /* How aggressive at synching data to disk */
  void *pAux;               /* Auxiliary data.  Usually NULL */
  void (*xFreeAux)(void*);  /* Routine to free pAux */
  Schema *pSchema;     /* Pointer to database schema (possibly shared) */
};

/*
** An instance of the following structure stores a database schema.
**
** If there are no virtual tables configured in this schema, the
** Schema.db variable is set to NULL. After the first virtual table
** has been added, it is set to point to the database connection 
** used to create the connection. Once a virtual table has been
** added to the Schema structure and the Schema.db variable populated, 
** only that database connection may use the Schema to prepare 
** statements.
*/
struct Schema {
  int schema_cookie;   /* Database schema version number for this file */
  Hash tblHash;        /* All tables indexed by name */
  Hash idxHash;        /* All (named) indices indexed by name */
  Hash trigHash;       /* All triggers indexed by name */
  Hash aFKey;          /* Foreign keys indexed by to-table */
  Table *pSeqTab;      /* The vtk_sqlite_sequence table used by AUTOINCREMENT */
  u8 file_format;      /* Schema format version for this file */
  u8 enc;              /* Text encoding used by this database */
  u16 flags;           /* Flags associated with this schema */
  int cache_size;      /* Number of pages to use in the cache */
#ifndef VTK_SQLITE_OMIT_VIRTUALTABLE
  vtk_sqlite3 *db;         /* "Owner" connection. See comment above */
#endif
};

/*
** These macros can be used to test, set, or clear bits in the 
** Db.flags field.
*/
#define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
#define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
#define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
#define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)

/*
** Allowed values for the DB.flags field.
**
** The DB_SchemaLoaded flag is set after the database schema has been
** read into internal hash tables.
**
** DB_UnresetViews means that one or more views have column names that
** have been filled out.  If the schema changes, these column names might
** changes and so the view will need to be reset.
*/
#define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
#define DB_UnresetViews    0x0002  /* Some views have defined column names */
#define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */


/*
** Each database is an instance of the following structure.
**
** The vtk_sqlite.lastRowid records the last insert rowid generated by an
** insert statement.  Inserts on views do not affect its value.  Each
** trigger has its own context, so that lastRowid can be updated inside
** triggers as usual.  The previous value will be restored once the trigger
** exits.  Upon entering a before or instead of trigger, lastRowid is no
** longer (since after version 2.8.12) reset to -1.
**
** The vtk_sqlite.nChange does not count changes within triggers and keeps no
** context.  It is reset at start of vtk_sqlite3_exec.
** The vtk_sqlite.lsChange represents the number of changes made by the last
** insert, update, or delete statement.  It remains constant throughout the
** length of a statement and is then updated by OP_SetCounts.  It keeps a
** context stack just like lastRowid so that the count of changes
** within a trigger is not seen outside the trigger.  Changes to views do not
** affect the value of lsChange.
** The vtk_sqlite.csChange keeps track of the number of current changes (since
** the last statement) and is used to update vtk_sqlite_lsChange.
**
** The member variables vtk_sqlite.errCode, vtk_sqlite.zErrMsg and vtk_sqlite.zErrMsg16
** store the most recent error code and, if applicable, string. The
** internal function vtk_sqlite3Error() is used to set these variables
** consistently.
*/
struct vtk_sqlite3 {
  int nDb;                      /* Number of backends currently in use */
  Db *aDb;                      /* All backends */
  int flags;                    /* Miscellanous flags. See below */
  int errCode;                  /* Most recent error code (VTK_SQLITE_*) */
  int errMask;                  /* & result codes with this before returning */
  u8 autoCommit;                /* The auto-commit flag. */
  u8 temp_store;                /* 1: file 2: memory 0: default */
  int nTable;                   /* Number of tables in the database */
  CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
  i64 lastRowid;                /* ROWID of most recent insert (see above) */
  i64 priorNewRowid;            /* Last randomly generated ROWID */
  int magic;                    /* Magic number for detect library misuse */
  int nChange;                  /* Value returned by vtk_sqlite3_changes() */
  int nTotalChange;             /* Value returned by vtk_sqlite3_total_changes() */
  struct vtk_sqlite3InitInfo {      /* Information used during initialization */
    int iDb;                    /* When back is being initialized */
    int newTnum;                /* Rootpage of table being initialized */
    u8 busy;                    /* TRUE if currently initializing */
  } init;
  int nExtension;               /* Number of loaded extensions */
  void **aExtension;            /* Array of shared libraray handles */
  struct Vdbe *pVdbe;           /* List of active virtual machines */
  int activeVdbeCnt;            /* Number of vdbes currently executing */
  void (*xTrace)(void*,const char*);        /* Trace function */
  void *pTraceArg;                          /* Argument to the trace function */
  void (*xProfile)(void*,const char*,u64);  /* Profiling function */
  void *pProfileArg;                        /* Argument to profile function */
  void *pCommitArg;                 /* Argument to xCommitCallback() */   
  int (*xCommitCallback)(void*);    /* Invoked at every commit. */
  void *pRollbackArg;               /* Argument to xRollbackCallback() */   
  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  void *pUpdateArg;
  void (*xUpdateCallback)(void*,int, const char*,const char*,vtk_sqlite_int64);
  void(*xCollNeeded)(void*,vtk_sqlite3*,int eTextRep,const char*);
  void(*xCollNeeded16)(void*,vtk_sqlite3*,int eTextRep,const void*);
  void *pCollNeededArg;
  vtk_sqlite3_value *pErr;          /* Most recent error message */
  char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
  char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
  union {
    int isInterrupted;          /* True if vtk_sqlite3_interrupt has been called */
    double notUsed1;            /* Spacer */
  } u1;
#ifndef VTK_SQLITE_OMIT_AUTHORIZATION
  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
                                /* Access authorization function */
  void *pAuthArg;               /* 1st argument to the access auth function */
#endif
#ifndef VTK_SQLITE_OMIT_PROGRESS_CALLBACK
  int (*xProgress)(void *);     /* The progress callback */
  void *pProgressArg;           /* Argument to the progress callback */
  int nProgressOps;             /* Number of opcodes for progress callback */
#endif
#ifndef VTK_SQLITE_OMIT_VIRTUALTABLE
  Hash aModule;                 /* populated by vtk_sqlite3_create_module() */
  Table *pVTab;                 /* vtab with active Connect/Create method */
  vtk_sqlite3_vtab **aVTrans;       /* Virtual tables with open transactions */
  int nVTrans;                  /* Allocated size of aVTrans */
#endif
  Hash aFunc;                   /* All functions that can be in SQL exprs */
  Hash aCollSeq;                /* All collating sequences */
  BusyHandler busyHandler;      /* Busy callback */
  int busyTimeout;              /* Busy handler timeout, in msec */
  Db aDbStatic[2];              /* Static space for the 2 default backends */
#ifdef VTK_SQLITE_SSE
  vtk_sqlite3_stmt *pFetch;         /* Used by SSE to fetch stored statements */
#endif
  u8 dfltLockMode;              /* Default locking-mode for attached dbs */
};

/*
** A macro to discover the encoding of a database.
*/
#define ENC(db) ((db)->aDb[0].pSchema->enc)

/*
** Possible values for the vtk_sqlite.flags and or Db.flags fields.
**
** On vtk_sqlite.flags, the VTK_SQLITE_InTrans value means that we have
** executed a BEGIN.  On Db.flags, VTK_SQLITE_InTrans means a statement
** transaction is active on that particular database file.
*/
#define VTK_SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
#define VTK_SQLITE_InTrans        0x00000008  /* True if in a transaction */
#define VTK_SQLITE_InternChanges  0x00000010  /* Uncommitted Hash table changes */
#define VTK_SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
#define VTK_SQLITE_ShortColNames  0x00000040  /* Show short columns names */
#define VTK_SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
                                          /*   DELETE, or UPDATE and return */
                                          /*   the count using a callback. */
#define VTK_SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
                                          /*   result set is empty */
#define VTK_SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
#define VTK_SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
#define VTK_SQLITE_WriteSchema    0x00000800  /* OK to update VTK_SQLITE_MASTER */
#define VTK_SQLITE_NoReadlock     0x00001000  /* Readlocks are omitted when 
                                          ** accessing read-only databases */
#define VTK_SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
#define VTK_SQLITE_ReadUncommitted 0x00004000 /* For shared-cache mode */
#define VTK_SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
#define VTK_SQLITE_FullFSync      0x00010000  /* Use full fsync on the backend */
#define VTK_SQLITE_LoadExtension  0x00020000  /* Enable load_extension */

#define VTK_SQLITE_RecoveryMode   0x00040000  /* Ignore schema errors */

/*
** Possible values for the vtk_sqlite.magic field.
** The numbers are obtained at random and have no special meaning, other
** than being distinct from one another.
*/
#define VTK_SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
#define VTK_SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
#define VTK_SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
#define VTK_SQLITE_MAGIC_ERROR    0xb5357930  /* An VTK_SQLITE_MISUSE error occurred */

/*
** Each SQL function is defined by an instance of the following
** structure.  A pointer to this structure is stored in the vtk_sqlite.aFunc
** hash table.  When multiple functions have the same name, the hash table
** points to a linked list of these structures.
*/
struct FuncDef {
  i16 nArg;            /* Number of arguments.  -1 means unlimited */
  u8 iPrefEnc;         /* Preferred text encoding (VTK_SQLITE_UTF8, 16LE, 16BE) */
  u8 needCollSeq;      /* True if vtk_sqlite3GetFuncCollSeq() might be called */
  u8 flags;            /* Some combination of VTK_SQLITE_FUNC_* */
  void *pUserData;     /* User data parameter */
  FuncDef *pNext;      /* Next function with same name */
  void (*xFunc)(vtk_sqlite3_context*,int,vtk_sqlite3_value**); /* Regular function */
  void (*xStep)(vtk_sqlite3_context*,int,vtk_sqlite3_value**); /* Aggregate step */
  void (*xFinalize)(vtk_sqlite3_context*);                /* Aggregate finializer */
  char zName[1];       /* SQL name of the function.  MUST BE LAST */
};

/*
** Each Vtk_Sqlite module (virtual table definition) is defined by an
** instance of the following structure, stored in the vtk_sqlite3.aModule
** hash table.
*/
struct Module {
  const vtk_sqlite3_module *pModule;       /* Callback pointers */
  const char *zName;                   /* Name passed to create_module() */
  void *pAux;                          /* pAux passed to create_module() */
  void (*xDestroy)(void *);            /* Module destructor function */
};

/*
** Possible values for FuncDef.flags
*/
#define VTK_SQLITE_FUNC_LIKE   0x01  /* Candidate for the LIKE optimization */
#define VTK_SQLITE_FUNC_CASE   0x02  /* Case-sensitive LIKE-type function */
#define VTK_SQLITE_FUNC_EPHEM  0x04  /* Ephermeral.  Delete with VDBE */

/*
** information about each column of an SQL table is held in an instance
** of this structure.
*/
struct Column {
  char *zName;     /* Name of this column */
  Expr *pDflt;     /* Default value of this column */
  char *zType;     /* Data type for this column */
  char *zColl;     /* Collating sequence.  If NULL, use the default */
  u8 notNull;      /* True if there is a NOT NULL constraint */
  u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
  char affinity;   /* One of the VTK_SQLITE_AFF_... values */
#ifndef VTK_SQLITE_OMIT_VIRTUALTABLE
  u8 isHidden;     /* True if this column is 'hidden' */
#endif
};

/*
** A "Collating Sequence" is defined by an instance of the following
** structure. Conceptually, a collating sequence consists of a name and
** a comparison routine that defines the order of that sequence.
**
** There may two seperate implementations of the collation function, one
** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
** native byte order. When a collation sequence is invoked, Vtk_Sqlite selects
** the version that will require the least expensive encoding
** translations, if any.
**
** The CollSeq.pUser member variable is an extra parameter that passed in
** as the first argument to the UTF-8 comparison function, xCmp.
** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
** xCmp16.
**
** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
** collating sequence is undefined.  Indices built on an undefined
** collating sequence may not be read or written.
*/
struct CollSeq {
  char *zName;          /* Name of the collating sequence, UTF-8 encoded */
  u8 enc;               /* Text encoding handled by xCmp() */
  u8 type;              /* One of the VTK_SQLITE_COLL_... values below */
  void *pUser;          /* First argument to xCmp() */
  int (*xCmp)(void*,int, const void*, int, const void*);
  void (*xDel)(void*);  /* Destructor for pUser */
};

/*
** Allowed values of CollSeq flags:
*/
#define VTK_SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
#define VTK_SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
#define VTK_SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
#define VTK_SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */

/*
** A sort order can be either ASC or DESC.
*/
#define VTK_SQLITE_SO_ASC       0  /* Sort in ascending order */
#define VTK_SQLITE_SO_DESC      1  /* Sort in ascending order */

/*
** Column affinity types.
**
** These used to have mnemonic name like 'i' for VTK_SQLITE_AFF_INTEGER and
** 't' for VTK_SQLITE_AFF_TEXT.  But we can save a little space and improve
** the speed a little by number the values consecutively.  
**
** But rather than start with 0 or 1, we begin with 'a'.  That way,
** when multiple affinity types are concatenated into a string and
** used as the P3 operand, they will be more readable.
**
** Note also that the numeric types are grouped together so that testing
** for a numeric type is a single comparison.
*/
#define VTK_SQLITE_AFF_TEXT     'a'
#define VTK_SQLITE_AFF_NONE     'b'
#define VTK_SQLITE_AFF_NUMERIC  'c'
#define VTK_SQLITE_AFF_INTEGER  'd'
#define VTK_SQLITE_AFF_REAL     'e'

#define vtk_sqlite3IsNumericAffinity(X)  ((X)>=VTK_SQLITE_AFF_NUMERIC)

/*
** Each SQL table is represented in memory by an instance of the
** following structure.
**
** Table.zName is the name of the table.  The case of the original
** CREATE TABLE statement is stored, but case is not significant for
** comparisons.
**
** Table.nCol is the number of columns in this table.  Table.aCol is a
** pointer to an array of Column structures, one for each column.
**
** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
** the column that is that key.   Otherwise Table.iPKey is negative.  Note
** that the datatype of the PRIMARY KEY must be INTEGER for this field to
** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
** is generated for each row of the table.  Table.hasPrimKey is true if
** the table has any PRIMARY KEY, INTEGER or otherwise.
**
** Table.tnum is the page number for the root BTree page of the table in the
** database file.  If Table.iDb is the index of the database table backend
** in vtk_sqlite.aDb[].  0 is for the main database and 1 is for the file that
** holds temporary tables and indices.  If Table.isEphem
** is true, then the table is stored in a file that is automatically deleted
** when the VDBE cursor to the table is closed.  In this case Table.tnum 
** refers VDBE cursor number that holds the table open, not to the root
** page number.  Transient tables are used to hold the results of a
** sub-query that appears instead of a real table name in the FROM clause 
** of a SELECT statement.
*/
struct Table {
  char *zName;     /* Name of the table */
  int nCol;        /* Number of columns in this table */
  Column *aCol;    /* Information about each column */
  int iPKey;       /* If not less then 0, use aCol[iPKey] as the primary key */
  Index *pIndex;   /* List of SQL indexes on this table. */
  int tnum;        /* Root BTree node for this table (see note above) */
  Select *pSelect; /* NULL for tables.  Points to definition if a view. */
  int nRef;          /* Number of pointers to this Table */
  Trigger *pTrigger; /* List of SQL triggers on this table */
  FKey *pFKey;       /* Linked list of all foreign keys in this table */
  char *zColAff;     /* String defining the affinity of each column */
#ifndef VTK_SQLITE_OMIT_CHECK
  Expr *pCheck;      /* The AND of all CHECK constraints */
#endif
#ifndef VTK_SQLITE_OMIT_ALTERTABLE
  int addColOffset;  /* Offset in CREATE TABLE statement to add a new column */
#endif
  u8 readOnly;     /* True if this table should not be written by the user */
  u8 isEphem;      /* True if created using OP_OpenEphermeral */
  u8 hasPrimKey;   /* True if there exists a primary key */
  u8 keyConf;      /* What to do in case of uniqueness conflict on iPKey */
  u8 autoInc;      /* True if the integer primary key is autoincrement */
#ifndef VTK_SQLITE_OMIT_VIRTUALTABLE
  u8 isVirtual;             /* True if this is a virtual table */
  u8 isCommit;              /* True once the CREATE TABLE has been committed */
  Module *pMod;             /* Pointer to the implementation of the module */
  vtk_sqlite3_vtab *pVtab;      /* Pointer to the module instance */
  int nModuleArg;           /* Number of arguments to the module */
  char **azModuleArg;       /* Text of all module args. [0] is module name */
#endif
  Schema *pSchema;
};

/*
** Test to see whether or not a table is a virtual table.  This is
** done as a macro so that it will be optimized out when virtual
** table support is omitted from the build.
*/
#ifndef VTK_SQLITE_OMIT_VIRTUALTABLE
#  define IsVirtual(X)      ((X)->isVirtual)
#  define IsHiddenColumn(X) ((X)->isHidden)
#else
#  define IsVirtual(X)      0
#  define IsHiddenColumn(X) 0
#endif

/*
** Each foreign key constraint is an instance of the following structure.
**
** A foreign key is associated with two tables.  The "from" table is
** the table that contains the REFERENCES clause that creates the foreign
** key.  The "to" table is the table that is named in the REFERENCES clause.
** Consider this example:
**
**     CREATE TABLE ex1(
**       a INTEGER PRIMARY KEY,
**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
**     );
**
** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
**
** Each REFERENCES clause generates an instance of the following structure
** which is attached to the from-table.  The to-table need not exist when
** the from-table is created.  The existance of the to-table is not checked
** until an attempt is made to insert data into the from-table.
**
** The vtk_sqlite.aFKey hash table stores pointers to this structure
** given the name of a to-table.  For each to-table, all foreign keys
** associated with that table are on a linked list using the FKey.pNextTo
** field.
*/
struct FKey {
  Table *pFrom;     /* The table that constains the REFERENCES clause */
  FKey *pNextFrom;  /* Next foreign key in pFrom */
  char *zTo;        /* Name of table that the key points to */
  FKey *pNextTo;    /* Next foreign key that points to zTo */
  int nCol;         /* Number of columns in this key */
  struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
    int iFrom;         /* Index of column in pFrom */
    char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
  } *aCol;          /* One entry for each of nCol column s */
  u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
  u8 updateConf;    /* How to resolve conflicts that occur on UPDATE */
  u8 deleteConf;    /* How to resolve conflicts that occur on DELETE */
  u8 insertConf;    /* How to resolve conflicts that occur on INSERT */
};

/*
** Vtk_Sqlite supports many different ways to resolve a contraint
** error.  ROLLBACK processing means that a constraint violation
** causes the operation in process to fail and for the current transaction
** to be rolled back.  ABORT processing means the operation in process
** fails and any prior changes from that one operation are backed out,
** but the transaction is not rolled back.  FAIL processing means that
** the operation in progress stops and returns an error code.  But prior
** changes due to the same operation are not backed out and no rollback
** occurs.  IGNORE means that the particular row that caused the constraint
** error is not inserted or updated.  Processing continues and no error
** is returned.  REPLACE means that preexisting database rows that caused
** a UNIQUE constraint violation are removed so that the new insert or
** update can proceed.  Processing continues and no error is reported.
**
** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
** referenced table row is propagated into the row that holds the
** foreign key.
** 
** The following symbolic values are used to record which type
** of action to take.
*/
#define OE_None     0   /* There is no constraint to check */
#define OE_Rollback 1   /* Fail the operation and rollback the transaction */
#define OE_Abort    2   /* Back out changes but do no rollback transaction */
#define OE_Fail     3   /* Stop the operation but leave all prior changes */
#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */

#define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
#define OE_SetNull  7   /* Set the foreign key value to NULL */
#define OE_SetDflt  8   /* Set the foreign key value to its default */
#define OE_Cascade  9   /* Cascade the changes */

#define OE_Default  99  /* Do whatever the default action is */


/*
** An instance of the following structure is passed as the first
** argument to vtk_sqlite3VdbeKeyCompare and is used to control the 
** comparison of the two index keys.
**
** If the KeyInfo.incrKey value is true and the comparison would
** otherwise be equal, then return a result as if the second key
** were larger.
*/
struct KeyInfo {
  u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
  u8 incrKey;         /* Increase 2nd key by epsilon before comparison */
  int nField;         /* Number of entries in aColl[] */
  u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
  CollSeq *aColl[1];  /* Collating sequence for each term of the key */
};

/*
** Each SQL index is represented in memory by an
** instance of the following structure.
**
** The columns of the table that are to be indexed are described
** by the aiColumn[] field of this structure.  For example, suppose
** we have the following table and index:
**
**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
**     CREATE INDEX Ex2 ON Ex1(c3,c1);
**
** In the Table structure describing Ex1, nCol==3 because there are
** three columns in the table.  In the Index structure describing
** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
** The second column to be indexed (c1) has an index of 0 in
** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
**
** The Index.onError field determines whether or not the indexed columns
** must be unique and what to do if they are not.  When Index.onError=OE_None,
** it means this is not a unique index.  Otherwise it is a unique index
** and the value of Index.onError indicate the which conflict resolution 
** algorithm to employ whenever an attempt is made to insert a non-unique
** element.
*/
struct Index {
  char *zName;     /* Name of this index */
  int nColumn;     /* Number of columns in the table used by this index */
  int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
  unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
  Table *pTable;   /* The SQL table being indexed */
  int tnum;        /* Page containing root of this index in database file */
  u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
  char *zColAff;   /* String defining the affinity of each column */
  Index *pNext;    /* The next index associated with the same table */
  Schema *pSchema; /* Schema containing this index */
  u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
  char **azColl;   /* Array of collation sequence names for index */
};

/*
** Each token coming out of the lexer is an instance of
** this structure.  Tokens are also used as part of an expression.
**
** Note if Token.z==0 then Token.dyn and Token.n are undefined and
** may contain random values.  Do not make any assuptions about Token.dyn
** and Token.n when Token.z==0.
*/
struct Token {
  const unsigned char *z; /* Text of the token.  Not NULL-terminated! */
  unsigned dyn  : 1;      /* True for malloced memory, false for static */
  unsigned n    : 31;     /* Number of characters in this token */
};

/*
** An instance of this structure contains information needed to generate
** code for a SELECT that contains aggregate functions.
**
** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
** pointer to this structure.  The Expr.iColumn field is the index in
** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
** code for that node.
**
** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
** original Select structure that describes the SELECT statement.  These
** fields do not need to be freed when deallocating the AggInfo structure.
*/
struct AggInfo {
  u8 directMode;          /* Direct rendering mode means take data directly
                          ** from source tables rather than from accumulators */
  u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
                          ** than the source table */
  int sortingIdx;         /* Cursor number of the sorting index */
  ExprList *pGroupBy;     /* The group by clause */
  int nSortingColumn;     /* Number of columns in the sorting index */
  struct AggInfo_col {    /* For each column used in source tables */
    Table *pTab;             /* Source table */
    int iTable;              /* Cursor number of the source table */
    int iColumn;             /* Column number within the source table */
    int iSorterColumn;       /* Column number in the sorting index */
    int iMem;                /* Memory location that acts as accumulator */
    Expr *pExpr;             /* The original expression */
  } *aCol;
  int nColumn;            /* Number of used entries in aCol[] */
  int nColumnAlloc;       /* Number of slots allocated for aCol[] */
  int nAccumulator;       /* Number of columns that show through to the output.
                          ** Additional columns are used only as parameters to
                          ** aggregate functions */
  struct AggInfo_func {   /* For each aggregate function */
    Expr *pExpr;             /* Expression encoding the function */
    FuncDef *pFunc;          /* The aggregate function implementation */
    int iMem;                /* Memory location that acts as accumulator */
    int iDistinct;           /* Ephermeral table used to enforce DISTINCT */
  } *aFunc;
  int nFunc;              /* Number of entries in aFunc[] */
  int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
};

/*
** Each node of an expression in the parse tree is an instance
** of this structure.
**
** Expr.op is the opcode.  The integer parser token codes are reused
** as opcodes here.  For example, the parser defines TK_GE to be an integer
** code representing the ">=" operator.  This same integer code is reused
** to represent the greater-than-or-equal-to operator in the expression
** tree.
**
** Expr.pRight and Expr.pLeft are subexpressions.  Expr.pList is a list
** of argument if the expression is a function.
**
** Expr.token is the operator token for this node.  For some expressions
** that have subexpressions, Expr.token can be the complete text that gave
** rise to the Expr.  In the latter case, the token is marked as being
** a compound token.
**
** An expression of the form ID or ID.ID refers to a column in a table.
** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
** the integer cursor number of a VDBE cursor pointing to that table and
** Expr.iColumn is the column number for the specific column.  If the
** expression is used as a result in an aggregate SELECT, then the
** value is also stored in the Expr.iAgg column in the aggregate so that
** it can be accessed after all aggregates are computed.
**
** If the expression is a function, the Expr.iTable is an integer code
** representing which function.  If the expression is an unbound variable
** marker (a question mark character '?' in the original SQL) then the
** Expr.iTable holds the index number for that variable.
**
** If the expression is a subquery then Expr.iColumn holds an integer
** register number containing the result of the subquery.  If the
** subquery gives a constant result, then iTable is -1.  If the subquery
** gives a different answer at different times during statement processing
** then iTable is the address of a subroutine that computes the subquery.
**
** The Expr.pSelect field points to a SELECT statement.  The SELECT might
** be the right operand of an IN operator.  Or, if a scalar SELECT appears
** in an expression the opcode is TK_SELECT and Expr.pSelect is the only
** operand.
**
** If the Expr is of type OP_Column, and the table it is selecting from
** is a disk table or the "old.*" pseudo-table, then pTab points to the
** corresponding table definition.
*/
struct Expr {
  u8 op;                 /* Operation performed by this node */
  char affinity;         /* The affinity of the column or 0 if not a column */
  u16 flags;             /* Various flags.  See below */
  CollSeq *pColl;        /* The collation type of the column or 0 */
  Expr *pLeft, *pRight;  /* Left and right subnodes */
  ExprList *pList;       /* A list of expressions used as function arguments
                         ** or in "<expr> IN (<expr-list)" */
  Token token;           /* An operand token */
  Token span;            /* Complete text of the expression */
  int iTable, iColumn;   /* When op==TK_COLUMN, then this expr node means the
                         ** iColumn-th field of the iTable-th table. */
  AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  int iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  int iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
  Select *pSelect;       /* When the expression is a sub-select.  Also the
                         ** right side of "<expr> IN (<select>)" */
  Table *pTab;           /* Table for OP_Column expressions. */
  Schema *pSchema;
#if VTK_SQLITE_MAX_EXPR_DEPTH>0
  int nHeight;           /* Height of the tree headed by this node */
#endif
};

/*
** The following are the meanings of bits in the Expr.flags field.
*/
#define EP_FromJoin     0x01  /* Originated in ON or USING clause of a join */
#define EP_Agg          0x02  /* Contains one or more aggregate functions */
#define EP_Resolved     0x04  /* IDs have been resolved to COLUMNs */
#define EP_Error        0x08  /* Expression contains one or more errors */
#define EP_Distinct     0x10  /* Aggregate function with DISTINCT keyword */
#define EP_VarSelect    0x20  /* pSelect is correlated, not constant */
#define EP_Dequoted     0x40  /* True if the string has been dequoted */
#define EP_InfixFunc    0x80  /* True for an infix function: LIKE, GLOB, etc */
#define EP_ExpCollate  0x100  /* Collating sequence specified explicitly */

/*
** These macros can be used to test, set, or clear bits in the 
** Expr.flags field.
*/
#define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
#define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
#define ExprSetProperty(E,P)     (E)->flags|=(P)
#define ExprClearProperty(E,P)   (E)->flags&=~(P)

/*
** A list of expressions.  Each expression may optionally have a
** name.  An expr/name combination can be used in several ways, such
** as the list of "expr AS ID" fields following a "SELECT" or in the
** list of "ID = expr" items in an UPDATE.  A list of expressions can
** also be used as the argument to a function, in which case the a.zName
** field is not used.
*/
struct ExprList {
  int nExpr;             /* Number of expressions on the list */
  int nAlloc;            /* Number of entries allocated below */
  int iECursor;          /* VDBE Cursor associated with this ExprList */
  struct ExprList_item {
    Expr *pExpr;           /* The list of expressions */
    char *zName;           /* Token associated with this expression */
    u8 sortOrder;          /* 1 for DESC or 0 for ASC */
    u8 isAgg;              /* True if this is an aggregate like count(*) */
    u8 done;               /* A flag to indicate when processing is finished */
  } *a;                  /* One entry for each expression */
};

/*
** An instance of this structure can hold a simple list of identifiers,
** such as the list "a,b,c" in the following statements:
**
**      INSERT INTO t(a,b,c) VALUES ...;
**      CREATE INDEX idx ON t(a,b,c);
**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
**
** The IdList.a.idx field is used when the IdList represents the list of
** column names after a table name in an INSERT statement.  In the statement
**
**     INSERT INTO t(a,b,c) ...
**
** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
*/
struct IdList {
  struct IdList_item {
    char *zName;      /* Name of the identifier */
    int idx;          /* Index in some Table.aCol[] of a column named zName */
  } *a;
  int nId;         /* Number of identifiers on the list */
  int nAlloc;      /* Number of entries allocated for a[] below */
};

/*
** The bitmask datatype defined below is used for various optimizations.
**
** Changing this from a 64-bit to a 32-bit type limits the number of
** tables in a join to 32 instead of 64.  But it also reduces the size
** of the library by 738 bytes on ix86.
*/
typedef u64 Bitmask;

/*
** The following structure describes the FROM clause of a SELECT statement.
** Each table or subquery in the FROM clause is a separate element of
** the SrcList.a[] array.
**
** With the addition of multiple database support, the following structure
** can also be used to describe a particular table such as the table that
** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
** such a table must be a simple name: ID.  But in Vtk_Sqlite, the table can
** now be identified by a database name, a dot, then the table name: ID.ID.
**
** The jointype starts out showing the join type between the current table
** and the next table on the list.  The parser builds the list this way.
** But vtk_sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
** jointype expresses the join between the table and the previous table.
*/
struct SrcList {
  i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
  i16 nAlloc;      /* Number of entries allocated in a[] below */
  struct SrcList_item {
    char *zDatabase;  /* Name of database holding this table */
    char *zName;      /* Name of the table */
    char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
    Table *pTab;      /* An SQL table corresponding to zName */
    Select *pSelect;  /* A SELECT statement used in place of a table name */
    u8 isPopulated;   /* Temporary table associated with SELECT is populated */
    u8 jointype;      /* Type of join between this able and the previous */
    int iCursor;      /* The VDBE cursor number used to access this table */
    Expr *pOn;        /* The ON clause of a join */
    IdList *pUsing;   /* The USING clause of a join */
    Bitmask colUsed;  /* Bit N (1<<N) set if column N or pTab is used */
  } a[1];             /* One entry for each identifier on the list */
};

/*
** Permitted values of the SrcList.a.jointype field
*/
#define JT_INNER     0x0001    /* Any kind of inner or cross join */
#define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
#define JT_NATURAL   0x0004    /* True for a "natural" join */
#define JT_LEFT      0x0008    /* Left outer join */
#define JT_RIGHT     0x0010    /* Right outer join */
#define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
#define JT_ERROR     0x0040    /* unknown or unsupported join type */

/*
** For each nested loop in a WHERE clause implementation, the WhereInfo
** structure contains a single instance of this structure.  This structure
** is intended to be private the the where.c module and should not be
** access or modified by other modules.
**
** The pIdxInfo and pBestIdx fields are used to help pick the best
** index on a virtual table.  The pIdxInfo pointer contains indexing
** information for the i-th table in the FROM clause before reordering.
** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
** The pBestIdx pointer is a copy of pIdxInfo for the i-th table after
** FROM clause ordering.  This is a little confusing so I will repeat
** it in different words.  WhereInfo.a[i].pIdxInfo is index information 
** for WhereInfo.pTabList.a[i].  WhereInfo.a[i].pBestInfo is the
** index information for the i-th loop of the join.  pBestInfo is always
** either NULL or a copy of some pIdxInfo.  So for cleanup it is 
** sufficient to free all of the pIdxInfo pointers.
** 
*/
struct WhereLevel {
  int iFrom;            /* Which entry in the FROM clause */
  int flags;            /* Flags associated with this level */
  int iMem;             /* First memory cell used by this level */
  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
  Index *pIdx;          /* Index used.  NULL if no index */
  int iTabCur;          /* The VDBE cursor used to access the table */
  int iIdxCur;          /* The VDBE cursor used to acesss pIdx */
  int brk;              /* Jump here to break out of the loop */
  int nxt;              /* Jump here to start the next IN combination */
  int cont;             /* Jump here to continue with the next loop cycle */
  int top;              /* First instruction of interior of the loop */
  int op, p1, p2;       /* Opcode used to terminate the loop */
  int nEq;              /* Number of == or IN constraints on this loop */
  int nIn;              /* Number of IN operators constraining this loop */
  struct InLoop {
    int iCur;              /* The VDBE cursor used by this IN operator */
    int topAddr;           /* Top of the IN loop */
  } *aInLoop;           /* Information about each nested IN operator */
  vtk_sqlite3_index_info *pBestIdx;  /* Index information for this level */

  /* The following field is really not part of the current level.  But
  ** we need a place to cache index information for each table in the
  ** FROM clause and the WhereLevel structure is a convenient place.
  */
  vtk_sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
};

/*
** The WHERE clause processing routine has two halves.  The
** first part does the start of the WHERE loop and the second
** half does the tail of the WHERE loop.  An instance of
** this structure is returned by the first half and passed
** into the second half to give some continuity.
*/
struct WhereInfo {
  Parse *pParse;
  SrcList *pTabList;   /* List of tables in the join */
  int iTop;            /* The very beginning of the WHERE loop */
  int iContinue;       /* Jump here to continue with next record */
  int iBreak;          /* Jump here to break out of the loop */
  int nLevel;          /* Number of nested loop */
  vtk_sqlite3_index_info **apInfo;  /* Array of pointers to index info structures */
  WhereLevel a[1];     /* Information about each nest loop in the WHERE */
};

/*
** A NameContext defines a context in which to resolve table and column
** names.  The context consists of a list of tables (the pSrcList) field and
** a list of named expression (pEList).  The named expression list may
** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
** to the table being operated on by INSERT, UPDATE, or DELETE.  The
** pEList corresponds to the result set of a SELECT and is NULL for
** other statements.
**
** NameContexts can be nested.  When resolving names, the inner-most 
** context is searched first.  If no match is found, the next outer
** context is checked.  If there is still no match, the next context
** is checked.  This process continues until either a match is found
** or all contexts are check.  When a match is found, the nRef member of
** the context containing the match is incremented. 
**
** Each subquery gets a new NameContext.  The pNext field points to the
** NameContext in the parent query.  Thus the process of scanning the
** NameContext list corresponds to searching through successively outer
** subqueries looking for a match.
*/
struct NameContext {
  Parse *pParse;       /* The parser */
  SrcList *pSrcList;   /* One or more tables used to resolve names */
  ExprList *pEList;    /* Optional list of named expressions */
  int nRef;            /* Number of names resolved by this context */
  int nErr;            /* Number of errors encountered while resolving names */
  u8 allowAgg;         /* Aggregate functions allowed here */
  u8 hasAgg;           /* True if aggregates are seen */
  u8 isCheck;          /* True if resolving names in a CHECK constraint */
  int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
  AggInfo *pAggInfo;   /* Information about aggregates at this level */
  NameContext *pNext;  /* Next outer name context.  NULL for outermost */
};

/*
** An instance of the following structure contains all information
** needed to generate code for a single SELECT statement.
**
** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
** If there is a LIMIT clause, the parser sets nLimit to the value of the
** limit and nOffset to the value of the offset (or 0 if there is not
** offset).  But later on, nLimit and nOffset become the memory locations
** in the VDBE that record the limit and offset counters.
**
** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
** These addresses must be stored so that we can go back and fill in
** the P3_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
** the number of columns in P2 can be computed at the same time
** as the OP_OpenEphm instruction is coded because not
** enough information about the compound query is known at that point.
** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
** sequences for the ORDER BY clause.
*/
struct Select {
  ExprList *pEList;      /* The fields of the result */
  u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  u8 isDistinct;         /* True if the DISTINCT keyword is present */
  u8 isResolved;         /* True once vtk_sqlite3SelectResolve() has run. */
  u8 isAgg;              /* True if this is an aggregate query */
  u8 usesEphm;           /* True if uses an OpenEphemeral opcode */
  u8 disallowOrderBy;    /* Do not allow an ORDER BY to be attached if TRUE */
  char affinity;         /* MakeRecord with this affinity for SRT_Set */
  SrcList *pSrc;         /* The FROM clause */
  Expr *pWhere;          /* The WHERE clause */
  ExprList *pGroupBy;    /* The GROUP BY clause */
  Expr *pHaving;         /* The HAVING clause */
  ExprList *pOrderBy;    /* The ORDER BY clause */
  Select *pPrior;        /* Prior select in a compound select statement */
  Select *pRightmost;    /* Right-most select in a compound select statement */
  Expr *pLimit;          /* LIMIT expression. NULL means not used. */
  Expr *pOffset;         /* OFFSET expression. NULL means not used. */
  int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
  int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
};

/*
** The results of a select can be distributed in several ways.
*/
#define SRT_Union        1  /* Store result as keys in an index */
#define SRT_Except       2  /* Remove result from a UNION index */
#define SRT_Discard      3  /* Do not save the results anywhere */

/* The ORDER BY clause is ignored for all of the above */
#define IgnorableOrderby(X) (X<=SRT_Discard)

#define SRT_Callback     4  /* Invoke a callback with each row of result */
#define SRT_Mem          5  /* Store result in a memory cell */
#define SRT_Set          6  /* Store non-null results as keys in an index */
#define SRT_Table        7  /* Store result as data with an automatic rowid */
#define SRT_EphemTab     8  /* Create transient tab and store like SRT_Table */
#define SRT_Subroutine   9  /* Call a subroutine to handle results */
#define SRT_Exists      10  /* Store 1 if the result is not empty */

/*
** An SQL parser context.  A copy of this structure is passed through
** the parser and down into all the parser action routine in order to
** carry around information that is global to the entire parse.
**
** The structure is divided into two parts.  When the parser and code
** generate call themselves recursively, the first part of the structure
** is constant but the second part is reset at the beginning and end of
** each recursion.
**
** The nTableLock and aTableLock variables are only used if the shared-cache 
** feature is enabled (if vtk_sqlite3Tsd()->useSharedData is true). They are
** used to store the set of table-locks required by the statement being
** compiled. Function vtk_sqlite3TableLock() is used to add entries to the
** list.
*/
struct Parse {
  vtk_sqlite3 *db;         /* The main database structure */
  int rc;              /* Return code from execution */
  char *zErrMsg;       /* An error message */
  Vdbe *pVdbe;         /* An engine for executing database bytecode */
  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
  u8 nameClash;        /* A permanent table name clashes with temp table name */
  u8 checkSchema;      /* Causes schema cookie check after an error */
  u8 nested;           /* Number of nested calls to the parser/code generator */
  u8 parseError;       /* True after a parsing error.  Ticket #1794 */
  int nErr;            /* Number of errors seen */
  int nTab;            /* Number of previously allocated VDBE cursors */
  int nMem;            /* Number of memory cells used so far */
  int nSet;            /* Number of sets used so far */
  int ckOffset;        /* Stack offset to data used by CHECK constraints */
  u32 writeMask;       /* Start a write transaction on these databases */
  u32 cookieMask;      /* Bitmask of schema verified databases */
  int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
  int cookieValue[VTK_SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
#ifndef VTK_SQLITE_OMIT_SHARED_CACHE
  int nTableLock;        /* Number of locks in aTableLock */
  TableLock *aTableLock; /* Required table locks for shared-cache mode */
#endif

  /* Above is constant between recursions.  Below is reset before and after
  ** each recursion */

  int nVar;            /* Number of '?' variables seen in the SQL so far */
  int nVarExpr;        /* Number of used slots in apVarExpr[] */
  int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
  Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
  u8 explain;          /* True if the EXPLAIN flag is found on the query */
  Token sErrToken;     /* The token at which the error occurred */
  Token sNameToken;    /* Token with unqualified schema object name */
  Token sLastToken;    /* The last token parsed */
  const char *zSql;    /* All SQL text */
  const char *zTail;   /* All SQL text past the last semicolon parsed */
  Table *pNewTable;    /* A table being constructed by CREATE TABLE */
  Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
  TriggerStack *trigStack;  /* Trigger actions being coded */
  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
#ifndef VTK_SQLITE_OMIT_VIRTUALTABLE
  Token sArg;                /* Complete text of a module argument */
  u8 declareVtab;            /* True if inside vtk_sqlite3_declare_vtab() */
  Table *pVirtualLock;       /* Require virtual table lock on this table */
#endif
#if VTK_SQLITE_MAX_EXPR_DEPTH>0
  int nHeight;            /* Expression tree height of current sub-select */
#endif
};

#ifdef VTK_SQLITE_OMIT_VIRTUALTABLE
  #define IN_DECLARE_VTAB 0
#else
  #define IN_DECLARE_VTAB (pParse->declareVtab)
#endif

/*
** An instance of the following structure can be declared on a stack and used
** to save the Parse.zAuthContext value so that it can be restored later.
*/
struct AuthContext {
  const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
  Parse *pParse;              /* The Parse structure */
};

/*
** Bitfield flags for P2 value in OP_Insert and OP_Delete
*/
#define OPFLAG_NCHANGE   1    /* Set to update db->nChange */
#define OPFLAG_LASTROWID 2    /* Set to update db->lastRowid */
#define OPFLAG_ISUPDATE  4    /* This OP_Insert is an sql UPDATE */
#define OPFLAG_APPEND    8    /* This is likely to be an append */

/*
 * Each trigger present in the database schema is stored as an instance of
 * struct Trigger. 
 *
 * Pointers to instances of struct Trigger are stored in two ways.
 * 1. In the "trigHash" hash table (part of the vtk_sqlite3* that represents the 
 *    database). This allows Trigger structures to be retrieved by name.
 * 2. All triggers associated with a single table form a linked list, using the
 *    pNext member of struct Trigger. A pointer to the first element of the
 *    linked list is stored as the "pTrigger" member of the associated
 *    struct Table.
 *
 * The "step_list" member points to the first element of a linked list
 * containing the SQL statements specified as the trigger program.
 */
struct Trigger {
  char *name;             /* The name of the trigger                        */
  char *table;            /* The table or view to which the trigger applies */
  u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
  u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  Expr *pWhen;            /* The WHEN clause of the expresion (may be NULL) */
  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
                             the <column-list> is stored here */
  Token nameToken;        /* Token containing zName. Use during parsing only */
  Schema *pSchema;        /* Schema containing the trigger */
  Schema *pTabSchema;     /* Schema containing the table */
  TriggerStep *step_list; /* Link list of trigger program steps             */
  Trigger *pNext;         /* Next trigger associated with the table */
};

/*
** A trigger is either a BEFORE or an AFTER trigger.  The following constants
** determine which. 
**
** If there are multiple triggers, you might of some BEFORE and some AFTER.
** In that cases, the constants below can be ORed together.
*/
#define TRIGGER_BEFORE  1
#define TRIGGER_AFTER   2

/*
 * An instance of struct TriggerStep is used to store a single SQL statement
 * that is a part of a trigger-program. 
 *
 * Instances of struct TriggerStep are stored in a singly linked list (linked
 * using the "pNext" member) referenced by the "step_list" member of the 
 * associated struct Trigger instance. The first element of the linked list is
 * the first step of the trigger-program.
 * 
 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
 * "SELECT" statement. The meanings of the other members is determined by the 
 * value of "op" as follows:
 *
 * (op == TK_INSERT)
 * orconf    -> stores the ON CONFLICT algorithm
 * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
 *              this stores a pointer to the SELECT statement. Otherwise NULL.
 * target    -> A token holding the name of the table to insert into.
 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
 *              this stores values to be inserted. Otherwise NULL.
 * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
 *              statement, then this stores the column-names to be
 *              inserted into.
 *
 * (op == TK_DELETE)
 * target    -> A token holding the name of the table to delete from.
 * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
 *              Otherwise NULL.
 * 
 * (op == TK_UPDATE)
 * target    -> A token holding the name of the table to update rows of.
 * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
 *              Otherwise NULL.
 * pExprList -> A list of the columns to update and the expressions to update
 *              them to. See vtk_sqlite3Update() documentation of "pChanges"
 *              argument.
 * 
 */
struct TriggerStep {
  int op;              /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  int orconf;          /* OE_Rollback etc. */
  Trigger *pTrig;      /* The trigger that this step is a part of */

  Select *pSelect;     /* Valid for SELECT and sometimes 
                          INSERT steps (when pExprList == 0) */
  Token target;        /* Valid for DELETE, UPDATE, INSERT steps */
  Expr *pWhere;        /* Valid for DELETE, UPDATE steps */
  ExprList *pExprList; /* Valid for UPDATE statements and sometimes 
                           INSERT steps (when pSelect == 0)         */
  IdList *pIdList;     /* Valid for INSERT statements only */
  TriggerStep *pNext;  /* Next in the link-list */
  TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
};

/*
 * An instance of struct TriggerStack stores information required during code
 * generation of a single trigger program. While the trigger program is being
 * coded, its associated TriggerStack instance is pointed to by the
 * "pTriggerStack" member of the Parse structure.
 *
 * The pTab member points to the table that triggers are being coded on. The 
 * newIdx member contains the index of the vdbe cursor that points at the temp
 * table that stores the new.* references. If new.* references are not valid
 * for the trigger being coded (for example an ON DELETE trigger), then newIdx
 * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
 *
 * The ON CONFLICT policy to be used for the trigger program steps is stored 
 * as the orconf member. If this is OE_Default, then the ON CONFLICT clause 
 * specified for individual triggers steps is used.
 *
 * struct TriggerStack has a "pNext" member, to allow linked lists to be
 * constructed. When coding nested triggers (triggers fired by other triggers)
 * each nested trigger stores its parent trigger's TriggerStack as the "pNext" 
 * pointer. Once the nested trigger has been coded, the pNext value is restored
 * to the pTriggerStack member of the Parse stucture and coding of the parent
 * trigger continues.
 *
 * Before a nested trigger is coded, the linked list pointed to by the 
 * pTriggerStack is scanned to ensure that the trigger is not about to be coded
 * recursively. If this condition is detected, the nested trigger is not coded.
 */
struct TriggerStack {
  Table *pTab;         /* Table that triggers are currently being coded on */
  int newIdx;          /* Index of vdbe cursor to "new" temp table */
  int oldIdx;          /* Index of vdbe cursor to "old" temp table */
  int orconf;          /* Current orconf policy */
  int ignoreJump;      /* where to jump to for a RAISE(IGNORE) */
  Trigger *pTrigger;   /* The trigger currently being coded */
  TriggerStack *pNext; /* Next trigger down on the trigger stack */
};

/*
** The following structure contains information used by the vtk_sqliteFix...
** routines as they walk the parse tree to make database references
** explicit.  
*/
typedef struct DbFixer DbFixer;
struct DbFixer {
  Parse *pParse;      /* The parsing context.  Error messages written here */
  const char *zDb;    /* Make sure all objects are contained in this database */
  const char *zType;  /* Type of the container - used for error messages */
  const Token *pName; /* Name of the container - used for error messages */
};

/*
** A pointer to this structure is used to communicate information
** from vtk_sqlite3Init and OP_ParseSchema into the vtk_sqlite3InitCallback.
*/
typedef struct {
  vtk_sqlite3 *db;        /* The database being initialized */
  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
  char **pzErrMsg;    /* Error message stored here */
  int rc;             /* Result code stored here */
} InitData;

/*
 * This global flag is set for performance testing of triggers. When it is set
 * Vtk_Sqlite will perform the overhead of building new and old trigger references 
 * even when no triggers exist
 */
extern int vtk_sqlite3_always_code_trigger_setup;

/*
** A lookup table used by the VTK_SQLITE_READ_UTF8 macro.  The definition
** is in utf.c.
*/
extern const unsigned char vtk_sqlite3UtfTrans1[];

/*
** Macros for reading UTF8 characters.
**
** VTK_SQLITE_READ_UTF8(x,c) reads a single UTF8 value out of x and writes
** that value into c.  The type of x must be unsigned char*.  The type
** of c must be unsigned int.
**
** VTK_SQLITE_SKIP_UTF8(x) advances x forward by one character.  The type of
** x must be unsigned char*.
**
** Notes On Invalid UTF-8:
**
**  *  These macros never allow a 7-bit character (0x00 through 0x7f) to
**     be encoded as a multi-byte character.  Any multi-byte character that
**     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
**
**  *  These macros never allow a UTF16 surrogate value to be encoded.
**     If a multi-byte character attempts to encode a value between
**     0xd800 and 0xe000 then it is rendered as 0xfffd.
**
**  *  Bytes in the range of 0x80 through 0xbf which occur as the first
**     byte of a character are interpreted as single-byte characters
**     and rendered as themselves even though they are technically
**     invalid characters.
**
**  *  These routines accept an infinite number of different UTF8 encodings
**     for unicode values 0x80 and greater.  They do not change over-length
**     encodings to 0xfffd as some systems recommend.
** 
*/
#define VTK_SQLITE_READ_UTF8(zIn, c) {                     \
  c = *(zIn++);                                        \
  if( c>=0xc0 ){                                       \
    c = vtk_sqlite3UtfTrans1[c-0xc0];                      \
    while( (*zIn & 0xc0)==0x80 ){                      \
      c = (c<<6) + (0x3f & *(zIn++));                  \
    }                                                  \
    if( c<0x80                                         \
        || (c&0xFFFFF800)==0xD800                      \
        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }    \
  }                                                    \
}
#define VTK_SQLITE_SKIP_UTF8(zIn) {                        \
  if( (*(zIn++))>=0xc0 ){                              \
    while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
  }                                                    \
}




/*
** The VTK_SQLITE_CORRUPT_BKPT macro can be either a constant (for production
** builds) or a function call (for debugging).  If it is a function call,
** it allows the operator to set a breakpoint at the spot where database
** corruption is first detected.
*/
#ifdef VTK_SQLITE_DEBUG
VTK_SQLITE_PRIVATE   int vtk_sqlite3Corrupt(void);
# define VTK_SQLITE_CORRUPT_BKPT vtk_sqlite3Corrupt()
#else
# define VTK_SQLITE_CORRUPT_BKPT VTK_SQLITE_CORRUPT
#endif

/*
** Internal function prototypes
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3StrICmp(const char *, const char *);
VTK_SQLITE_PRIVATE int vtk_sqlite3StrNICmp(const char *, const char *, int);
VTK_SQLITE_PRIVATE int vtk_sqlite3IsNumber(const char*, int*, u8);

VTK_SQLITE_PRIVATE void *vtk_sqlite3Malloc(int,int);
VTK_SQLITE_PRIVATE void *vtk_sqlite3MallocRaw(int,int);
VTK_SQLITE_PRIVATE void *vtk_sqlite3Realloc(void*,int);
VTK_SQLITE_PRIVATE char *vtk_sqlite3StrDup(const char*);
VTK_SQLITE_PRIVATE char *vtk_sqlite3StrNDup(const char*, int);
# define vtk_sqlite3CheckMemory(a,b)
VTK_SQLITE_PRIVATE void *vtk_sqlite3ReallocOrFree(void*,int);
VTK_SQLITE_PRIVATE void vtk_sqlite3FreeX(void*);
VTK_SQLITE_PRIVATE void *vtk_sqlite3MallocX(int);
#ifdef VTK_SQLITE_ENABLE_MEMORY_MANAGEMENT
VTK_SQLITE_PRIVATE   int vtk_sqlite3AllocSize(void *);
#endif

VTK_SQLITE_PRIVATE char *vtk_sqlite3MPrintf(const char*, ...);
VTK_SQLITE_PRIVATE char *vtk_sqlite3VMPrintf(const char*, va_list);
#if defined(VTK_SQLITE_TEST) || defined(VTK_SQLITE_DEBUG)
VTK_SQLITE_PRIVATE   void vtk_sqlite3DebugPrintf(const char*, ...);
VTK_SQLITE_PRIVATE   void *vtk_sqlite3TextToPtr(const char*);
#endif
VTK_SQLITE_PRIVATE void vtk_sqlite3SetString(char **, ...);
VTK_SQLITE_PRIVATE void vtk_sqlite3ErrorMsg(Parse*, const char*, ...);
VTK_SQLITE_PRIVATE void vtk_sqlite3ErrorClear(Parse*);
VTK_SQLITE_PRIVATE void vtk_sqlite3Dequote(char*);
VTK_SQLITE_PRIVATE void vtk_sqlite3DequoteExpr(Expr*);
VTK_SQLITE_PRIVATE int vtk_sqlite3KeywordCode(const unsigned char*, int);
VTK_SQLITE_PRIVATE int vtk_sqlite3RunParser(Parse*, const char*, char **);
VTK_SQLITE_PRIVATE void vtk_sqlite3FinishCoding(Parse*);
VTK_SQLITE_PRIVATE Expr *vtk_sqlite3Expr(int, Expr*, Expr*, const Token*);
VTK_SQLITE_PRIVATE Expr *vtk_sqlite3ExprOrFree(int, Expr*, Expr*, const Token*);
VTK_SQLITE_PRIVATE Expr *vtk_sqlite3RegisterExpr(Parse*,Token*);
VTK_SQLITE_PRIVATE Expr *vtk_sqlite3ExprAnd(Expr*, Expr*);
VTK_SQLITE_PRIVATE void vtk_sqlite3ExprSpan(Expr*,Token*,Token*);
VTK_SQLITE_PRIVATE Expr *vtk_sqlite3ExprFunction(ExprList*, Token*);
VTK_SQLITE_PRIVATE void vtk_sqlite3ExprAssignVarNumber(Parse*, Expr*);
VTK_SQLITE_PRIVATE void vtk_sqlite3ExprDelete(Expr*);
VTK_SQLITE_PRIVATE ExprList *vtk_sqlite3ExprListAppend(ExprList*,Expr*,Token*);
VTK_SQLITE_PRIVATE void vtk_sqlite3ExprListDelete(ExprList*);
VTK_SQLITE_PRIVATE int vtk_sqlite3Init(vtk_sqlite3*, char**);
VTK_SQLITE_PRIVATE int vtk_sqlite3InitCallback(void*, int, char**, char**);
VTK_SQLITE_PRIVATE void vtk_sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
VTK_SQLITE_PRIVATE void vtk_sqlite3ResetInternalSchema(vtk_sqlite3*, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3BeginParse(Parse*,int);
VTK_SQLITE_PRIVATE void vtk_sqlite3CommitInternalChanges(vtk_sqlite3*);
VTK_SQLITE_PRIVATE Table *vtk_sqlite3ResultSetOfSelect(Parse*,char*,Select*);
VTK_SQLITE_PRIVATE void vtk_sqlite3OpenMasterTable(Parse *, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
VTK_SQLITE_PRIVATE void vtk_sqlite3AddColumn(Parse*,Token*);
VTK_SQLITE_PRIVATE void vtk_sqlite3AddNotNull(Parse*, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3AddCheckConstraint(Parse*, Expr*);
VTK_SQLITE_PRIVATE void vtk_sqlite3AddColumnType(Parse*,Token*);
VTK_SQLITE_PRIVATE void vtk_sqlite3AddDefaultValue(Parse*,Expr*);
VTK_SQLITE_PRIVATE void vtk_sqlite3AddCollateType(Parse*, const char*, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3EndTable(Parse*,Token*,Token*,Select*);

VTK_SQLITE_PRIVATE void vtk_sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);

#if !defined(VTK_SQLITE_OMIT_VIEW) || !defined(VTK_SQLITE_OMIT_VIRTUALTABLE)
VTK_SQLITE_PRIVATE   int vtk_sqlite3ViewGetColumnNames(Parse*,Table*);
#else
# define vtk_sqlite3ViewGetColumnNames(A,B) 0
#endif

VTK_SQLITE_PRIVATE void vtk_sqlite3DropTable(Parse*, SrcList*, int, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3DeleteTable(Table*);
VTK_SQLITE_PRIVATE void vtk_sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
VTK_SQLITE_PRIVATE void *vtk_sqlite3ArrayAllocate(void*,int,int,int*,int*,int*);
VTK_SQLITE_PRIVATE IdList *vtk_sqlite3IdListAppend(IdList*, Token*);
VTK_SQLITE_PRIVATE int vtk_sqlite3IdListIndex(IdList*,const char*);
VTK_SQLITE_PRIVATE SrcList *vtk_sqlite3SrcListAppend(SrcList*, Token*, Token*);
VTK_SQLITE_PRIVATE SrcList *vtk_sqlite3SrcListAppendFromTerm(SrcList*, Token*, Token*, Token*,
                                      Select*, Expr*, IdList*);
VTK_SQLITE_PRIVATE void vtk_sqlite3SrcListShiftJoinType(SrcList*);
VTK_SQLITE_PRIVATE void vtk_sqlite3SrcListAssignCursors(Parse*, SrcList*);
VTK_SQLITE_PRIVATE void vtk_sqlite3IdListDelete(IdList*);
VTK_SQLITE_PRIVATE void vtk_sqlite3SrcListDelete(SrcList*);
VTK_SQLITE_PRIVATE void vtk_sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
                        Token*, int, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3DropIndex(Parse*, SrcList*, int);
VTK_SQLITE_PRIVATE int vtk_sqlite3Select(Parse*, Select*, int, int, Select*, int, int*, char *aff);
VTK_SQLITE_PRIVATE Select *vtk_sqlite3SelectNew(ExprList*,SrcList*,Expr*,ExprList*,Expr*,ExprList*,
                        int,Expr*,Expr*);
VTK_SQLITE_PRIVATE void vtk_sqlite3SelectDelete(Select*);
VTK_SQLITE_PRIVATE Table *vtk_sqlite3SrcListLookup(Parse*, SrcList*);
VTK_SQLITE_PRIVATE int vtk_sqlite3IsReadOnly(Parse*, Table*, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
VTK_SQLITE_PRIVATE void vtk_sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
VTK_SQLITE_PRIVATE WhereInfo *vtk_sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**);
VTK_SQLITE_PRIVATE void vtk_sqlite3WhereEnd(WhereInfo*);
VTK_SQLITE_PRIVATE void vtk_sqlite3ExprCodeGetColumn(Vdbe*, Table*, int, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3ExprCode(Parse*, Expr*);
VTK_SQLITE_PRIVATE void vtk_sqlite3ExprCodeAndCache(Parse*, Expr*);
VTK_SQLITE_PRIVATE int vtk_sqlite3ExprCodeExprList(Parse*, ExprList*);
VTK_SQLITE_PRIVATE void vtk_sqlite3ExprIfTrue(Parse*, Expr*, int, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3ExprIfFalse(Parse*, Expr*, int, int);
VTK_SQLITE_PRIVATE Table *vtk_sqlite3FindTable(vtk_sqlite3*,const char*, const char*);
VTK_SQLITE_PRIVATE Table *vtk_sqlite3LocateTable(Parse*,const char*, const char*);
VTK_SQLITE_PRIVATE Index *vtk_sqlite3FindIndex(vtk_sqlite3*,const char*, const char*);
VTK_SQLITE_PRIVATE void vtk_sqlite3UnlinkAndDeleteTable(vtk_sqlite3*,int,const char*);
VTK_SQLITE_PRIVATE void vtk_sqlite3UnlinkAndDeleteIndex(vtk_sqlite3*,int,const char*);
VTK_SQLITE_PRIVATE void vtk_sqlite3Vacuum(Parse*);
VTK_SQLITE_PRIVATE int vtk_sqlite3RunVacuum(char**, vtk_sqlite3*);
VTK_SQLITE_PRIVATE char *vtk_sqlite3NameFromToken(Token*);
VTK_SQLITE_PRIVATE int vtk_sqlite3ExprCompare(Expr*, Expr*);
int vtk_sqliteFuncId(Token*);
VTK_SQLITE_PRIVATE int vtk_sqlite3ExprResolveNames(NameContext *, Expr *);
VTK_SQLITE_PRIVATE int vtk_sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
VTK_SQLITE_PRIVATE int vtk_sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
VTK_SQLITE_PRIVATE Vdbe *vtk_sqlite3GetVdbe(Parse*);
VTK_SQLITE_PRIVATE Expr *vtk_sqlite3CreateIdExpr(const char*);
VTK_SQLITE_PRIVATE void vtk_sqlite3Randomness(int, void*);
VTK_SQLITE_PRIVATE void vtk_sqlite3RollbackAll(vtk_sqlite3*);
VTK_SQLITE_PRIVATE void vtk_sqlite3CodeVerifySchema(Parse*, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3BeginTransaction(Parse*, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3CommitTransaction(Parse*);
VTK_SQLITE_PRIVATE void vtk_sqlite3RollbackTransaction(Parse*);
VTK_SQLITE_PRIVATE int vtk_sqlite3ExprIsConstant(Expr*);
VTK_SQLITE_PRIVATE int vtk_sqlite3ExprIsConstantNotJoin(Expr*);
VTK_SQLITE_PRIVATE int vtk_sqlite3ExprIsConstantOrFunction(Expr*);
VTK_SQLITE_PRIVATE int vtk_sqlite3ExprIsInteger(Expr*, int*);
VTK_SQLITE_PRIVATE int vtk_sqlite3IsRowid(const char*);
VTK_SQLITE_PRIVATE void vtk_sqlite3GenerateRowDelete(vtk_sqlite3*, Vdbe*, Table*, int, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3GenerateRowIndexDelete(Vdbe*, Table*, int, char*);
VTK_SQLITE_PRIVATE void vtk_sqlite3GenerateIndexKey(Vdbe*, Index*, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3GenerateConstraintChecks(Parse*,Table*,int,char*,int,int,int,int);
VTK_SQLITE_PRIVATE void vtk_sqlite3CompleteInsertion(Parse*, Table*, int, char*, int, int, int, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3BeginWriteOperation(Parse*, int, int);
VTK_SQLITE_PRIVATE Expr *vtk_sqlite3ExprDup(Expr*);
VTK_SQLITE_PRIVATE void vtk_sqlite3TokenCopy(Token*, Token*);
VTK_SQLITE_PRIVATE ExprList *vtk_sqlite3ExprListDup(ExprList*);
VTK_SQLITE_PRIVATE SrcList *vtk_sqlite3SrcListDup(SrcList*);
VTK_SQLITE_PRIVATE IdList *vtk_sqlite3IdListDup(IdList*);
VTK_SQLITE_PRIVATE Select *vtk_sqlite3SelectDup(Select*);
VTK_SQLITE_PRIVATE FuncDef *vtk_sqlite3FindFunction(vtk_sqlite3*,const char*,int,int,u8,int);
VTK_SQLITE_PRIVATE void vtk_sqlite3RegisterBuiltinFunctions(vtk_sqlite3*);
VTK_SQLITE_PRIVATE void vtk_sqlite3RegisterDateTimeFunctions(vtk_sqlite3*);
VTK_SQLITE_PRIVATE int vtk_sqlite3SafetyOn(vtk_sqlite3*);
VTK_SQLITE_PRIVATE int vtk_sqlite3SafetyOff(vtk_sqlite3*);
VTK_SQLITE_PRIVATE int vtk_sqlite3SafetyCheck(vtk_sqlite3*);
VTK_SQLITE_PRIVATE void vtk_sqlite3ChangeCookie(vtk_sqlite3*, Vdbe*, int);

#ifndef VTK_SQLITE_OMIT_TRIGGER
VTK_SQLITE_PRIVATE   void vtk_sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
                           Expr*,int, int);
VTK_SQLITE_PRIVATE   void vtk_sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
VTK_SQLITE_PRIVATE   void vtk_sqlite3DropTrigger(Parse*, SrcList*, int);
VTK_SQLITE_PRIVATE   void vtk_sqlite3DropTriggerPtr(Parse*, Trigger*);
VTK_SQLITE_PRIVATE   int vtk_sqlite3TriggersExist(Parse*, Table*, int, ExprList*);
VTK_SQLITE_PRIVATE   int vtk_sqlite3CodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int, 
                           int, int);
  void vtk_sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
VTK_SQLITE_PRIVATE   void vtk_sqlite3DeleteTriggerStep(TriggerStep*);
VTK_SQLITE_PRIVATE   TriggerStep *vtk_sqlite3TriggerSelectStep(Select*);
VTK_SQLITE_PRIVATE   TriggerStep *vtk_sqlite3TriggerInsertStep(Token*, IdList*, ExprList*,Select*,int);
VTK_SQLITE_PRIVATE   TriggerStep *vtk_sqlite3TriggerUpdateStep(Token*, ExprList*, Expr*, int);
VTK_SQLITE_PRIVATE   TriggerStep *vtk_sqlite3TriggerDeleteStep(Token*, Expr*);
VTK_SQLITE_PRIVATE   void vtk_sqlite3DeleteTrigger(Trigger*);
VTK_SQLITE_PRIVATE   void vtk_sqlite3UnlinkAndDeleteTrigger(vtk_sqlite3*,int,const char*);
#else
# define vtk_sqlite3TriggersExist(A,B,C,D,E,F) 0
# define vtk_sqlite3DeleteTrigger(A)
# define vtk_sqlite3DropTriggerPtr(A,B)
# define vtk_sqlite3UnlinkAndDeleteTrigger(A,B,C)
# define vtk_sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I) 0
#endif

VTK_SQLITE_PRIVATE int vtk_sqlite3JoinType(Parse*, Token*, Token*, Token*);
VTK_SQLITE_PRIVATE void vtk_sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3DeferForeignKey(Parse*, int);
#ifndef VTK_SQLITE_OMIT_AUTHORIZATION
VTK_SQLITE_PRIVATE   void vtk_sqlite3AuthRead(Parse*,Expr*,SrcList*);
VTK_SQLITE_PRIVATE   int vtk_sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
VTK_SQLITE_PRIVATE   void vtk_sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
VTK_SQLITE_PRIVATE   void vtk_sqlite3AuthContextPop(AuthContext*);
#else
# define vtk_sqlite3AuthRead(a,b,c)
# define vtk_sqlite3AuthCheck(a,b,c,d,e)    VTK_SQLITE_OK
# define vtk_sqlite3AuthContextPush(a,b,c)
# define vtk_sqlite3AuthContextPop(a)  ((void)(a))
#endif
VTK_SQLITE_PRIVATE void vtk_sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
VTK_SQLITE_PRIVATE void vtk_sqlite3Detach(Parse*, Expr*);
VTK_SQLITE_PRIVATE int vtk_sqlite3BtreeFactory(const vtk_sqlite3 *db, const char *zFilename,
                       int omitJournal, int nCache, Btree **ppBtree);
VTK_SQLITE_PRIVATE int vtk_sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
VTK_SQLITE_PRIVATE int vtk_sqlite3FixSrcList(DbFixer*, SrcList*);
VTK_SQLITE_PRIVATE int vtk_sqlite3FixSelect(DbFixer*, Select*);
VTK_SQLITE_PRIVATE int vtk_sqlite3FixExpr(DbFixer*, Expr*);
VTK_SQLITE_PRIVATE int vtk_sqlite3FixExprList(DbFixer*, ExprList*);
VTK_SQLITE_PRIVATE int vtk_sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
VTK_SQLITE_PRIVATE int vtk_sqlite3AtoF(const char *z, double*);
VTK_SQLITE_API char *vtk_sqlite3_snprintf(int,char*,const char*,...);
VTK_SQLITE_PRIVATE int vtk_sqlite3GetInt32(const char *, int*);
VTK_SQLITE_PRIVATE int vtk_sqlite3FitsIn64Bits(const char *);
VTK_SQLITE_PRIVATE int vtk_sqlite3Utf16ByteLen(const void *pData, int nChar);
VTK_SQLITE_PRIVATE int vtk_sqlite3Utf8CharLen(const char *pData, int nByte);
VTK_SQLITE_PRIVATE u32 vtk_sqlite3ReadUtf8(const unsigned char *);
VTK_SQLITE_PRIVATE int vtk_sqlite3PutVarint(unsigned char *, u64);
VTK_SQLITE_PRIVATE int vtk_sqlite3GetVarint(const unsigned char *, u64 *);
VTK_SQLITE_PRIVATE int vtk_sqlite3GetVarint32(const unsigned char *, u32 *);
VTK_SQLITE_PRIVATE int vtk_sqlite3VarintLen(u64 v);
VTK_SQLITE_PRIVATE void vtk_sqlite3IndexAffinityStr(Vdbe *, Index *);
VTK_SQLITE_PRIVATE void vtk_sqlite3TableAffinityStr(Vdbe *, Table *);
VTK_SQLITE_PRIVATE char vtk_sqlite3CompareAffinity(Expr *pExpr, char aff2);
VTK_SQLITE_PRIVATE int vtk_sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
VTK_SQLITE_PRIVATE char vtk_sqlite3ExprAffinity(Expr *pExpr);
VTK_SQLITE_PRIVATE int vtk_sqlite3Atoi64(const char*, i64*);
VTK_SQLITE_PRIVATE void vtk_sqlite3Error(vtk_sqlite3*, int, const char*,...);
VTK_SQLITE_PRIVATE void *vtk_sqlite3HexToBlob(const char *z);
VTK_SQLITE_PRIVATE int vtk_sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
VTK_SQLITE_PRIVATE const char *vtk_sqlite3ErrStr(int);
VTK_SQLITE_PRIVATE int vtk_sqlite3ReadSchema(Parse *pParse);
VTK_SQLITE_PRIVATE CollSeq *vtk_sqlite3FindCollSeq(vtk_sqlite3*,u8 enc, const char *,int,int);
VTK_SQLITE_PRIVATE CollSeq *vtk_sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName);
VTK_SQLITE_PRIVATE CollSeq *vtk_sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
VTK_SQLITE_PRIVATE Expr *vtk_sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
VTK_SQLITE_PRIVATE int vtk_sqlite3CheckCollSeq(Parse *, CollSeq *);
VTK_SQLITE_PRIVATE int vtk_sqlite3CheckObjectName(Parse *, const char *);
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeSetChanges(vtk_sqlite3 *, int);
/* This function is never referenced or defined */
/* VTK_SQLITE_PRIVATE void vtk_sqlite3Utf16Substr(vtk_sqlite3_context *,int,vtk_sqlite3_value **); */

VTK_SQLITE_PRIVATE const void *vtk_sqlite3ValueText(vtk_sqlite3_value*, u8);
VTK_SQLITE_PRIVATE int vtk_sqlite3ValueBytes(vtk_sqlite3_value*, u8);
VTK_SQLITE_PRIVATE void vtk_sqlite3ValueSetStr(vtk_sqlite3_value*, int, const void *,u8, void(*)(void*));
VTK_SQLITE_PRIVATE void vtk_sqlite3ValueFree(vtk_sqlite3_value*);
VTK_SQLITE_PRIVATE vtk_sqlite3_value *vtk_sqlite3ValueNew(void);
VTK_SQLITE_PRIVATE char *vtk_sqlite3Utf16to8(const void*, int);
VTK_SQLITE_PRIVATE int vtk_sqlite3ValueFromExpr(Expr *, u8, u8, vtk_sqlite3_value **);
VTK_SQLITE_PRIVATE void vtk_sqlite3ValueApplyAffinity(vtk_sqlite3_value *, u8, u8);
extern const unsigned char vtk_sqlite3UpperToLower[];
VTK_SQLITE_PRIVATE void vtk_sqlite3RootPageMoved(Db*, int, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3Reindex(Parse*, Token*, Token*);
VTK_SQLITE_PRIVATE void vtk_sqlite3AlterFunctions(vtk_sqlite3*);
VTK_SQLITE_PRIVATE void vtk_sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
VTK_SQLITE_PRIVATE int vtk_sqlite3GetToken(const unsigned char *, int *);
VTK_SQLITE_PRIVATE void vtk_sqlite3NestedParse(Parse*, const char*, ...);
VTK_SQLITE_PRIVATE void vtk_sqlite3ExpirePreparedStatements(vtk_sqlite3*);
VTK_SQLITE_PRIVATE void vtk_sqlite3CodeSubselect(Parse *, Expr *);
VTK_SQLITE_PRIVATE int vtk_sqlite3SelectResolve(Parse *, Select *, NameContext *);
VTK_SQLITE_PRIVATE void vtk_sqlite3ColumnDefault(Vdbe *, Table *, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3AlterFinishAddColumn(Parse *, Token *);
VTK_SQLITE_PRIVATE void vtk_sqlite3AlterBeginAddColumn(Parse *, SrcList *);
VTK_SQLITE_PRIVATE CollSeq *vtk_sqlite3GetCollSeq(vtk_sqlite3*, CollSeq *, const char *, int);
VTK_SQLITE_PRIVATE char vtk_sqlite3AffinityType(const Token*);
VTK_SQLITE_PRIVATE void vtk_sqlite3Analyze(Parse*, Token*, Token*);
VTK_SQLITE_PRIVATE int vtk_sqlite3InvokeBusyHandler(BusyHandler*);
VTK_SQLITE_PRIVATE int vtk_sqlite3FindDb(vtk_sqlite3*, Token*);
VTK_SQLITE_PRIVATE int vtk_sqlite3AnalysisLoad(vtk_sqlite3*,int iDB);
VTK_SQLITE_PRIVATE void vtk_sqlite3DefaultRowEst(Index*);
VTK_SQLITE_PRIVATE void vtk_sqlite3RegisterLikeFunctions(vtk_sqlite3*, int);
VTK_SQLITE_PRIVATE int vtk_sqlite3IsLikeFunction(vtk_sqlite3*,Expr*,int*,char*);
VTK_SQLITE_PRIVATE ThreadData *vtk_sqlite3ThreadData(void);
VTK_SQLITE_PRIVATE const ThreadData *vtk_sqlite3ThreadDataReadOnly(void);
VTK_SQLITE_PRIVATE void vtk_sqlite3ReleaseThreadData(void);
VTK_SQLITE_PRIVATE void vtk_sqlite3AttachFunctions(vtk_sqlite3 *);
VTK_SQLITE_PRIVATE void vtk_sqlite3MinimumFileFormat(Parse*, int, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3SchemaFree(void *);
VTK_SQLITE_PRIVATE Schema *vtk_sqlite3SchemaGet(Btree *);
VTK_SQLITE_PRIVATE int vtk_sqlite3SchemaToIndex(vtk_sqlite3 *db, Schema *);
VTK_SQLITE_PRIVATE KeyInfo *vtk_sqlite3IndexKeyinfo(Parse *, Index *);
VTK_SQLITE_PRIVATE int vtk_sqlite3CreateFunc(vtk_sqlite3 *, const char *, int, int, void *, 
  void (*)(vtk_sqlite3_context*,int,vtk_sqlite3_value **),
  void (*)(vtk_sqlite3_context*,int,vtk_sqlite3_value **), void (*)(vtk_sqlite3_context*));
VTK_SQLITE_PRIVATE int vtk_sqlite3ApiExit(vtk_sqlite3 *db, int);
VTK_SQLITE_PRIVATE void vtk_sqlite3FailedMalloc(void);
VTK_SQLITE_PRIVATE void vtk_sqlite3AbortOtherActiveVdbes(vtk_sqlite3 *, Vdbe *);
VTK_SQLITE_PRIVATE int vtk_sqlite3OpenTempDatabase(Parse *);

#ifndef VTK_SQLITE_OMIT_LOAD_EXTENSION
VTK_SQLITE_PRIVATE   void vtk_sqlite3CloseExtensions(vtk_sqlite3*);
VTK_SQLITE_PRIVATE   int vtk_sqlite3AutoLoadExtensions(vtk_sqlite3*);
#else
# define vtk_sqlite3CloseExtensions(X)
# define vtk_sqlite3AutoLoadExtensions(X)  VTK_SQLITE_OK
#endif

#ifndef VTK_SQLITE_OMIT_SHARED_CACHE
VTK_SQLITE_PRIVATE   void vtk_sqlite3TableLock(Parse *, int, int, u8, const char *);
#else
  #define vtk_sqlite3TableLock(v,w,x,y,z)
#endif

#ifdef VTK_SQLITE_TEST
VTK_SQLITE_PRIVATE   int vtk_sqlite3Utf8To8(unsigned char*);
#endif

#ifdef VTK_SQLITE_MEMDEBUG
VTK_SQLITE_PRIVATE   void vtk_sqlite3MallocDisallow(void);
VTK_SQLITE_PRIVATE   void vtk_sqlite3MallocAllow(void);
VTK_SQLITE_PRIVATE   int vtk_sqlite3TestMallocFail(void);
#else
  #define vtk_sqlite3TestMallocFail() 0
  #define vtk_sqlite3MallocDisallow()
  #define vtk_sqlite3MallocAllow()
#endif

#ifdef VTK_SQLITE_ENABLE_MEMORY_MANAGEMENT
VTK_SQLITE_PRIVATE   void *vtk_sqlite3ThreadSafeMalloc(int);
VTK_SQLITE_PRIVATE   void vtk_sqlite3ThreadSafeFree(void *);
#else
  #define vtk_sqlite3ThreadSafeMalloc vtk_sqlite3MallocX
  #define vtk_sqlite3ThreadSafeFree vtk_sqlite3FreeX
#endif

#ifdef VTK_SQLITE_OMIT_VIRTUALTABLE
#  define vtk_sqlite3VtabClear(X)
#  define vtk_sqlite3VtabSync(X,Y) (Y)
#  define vtk_sqlite3VtabRollback(X)
#  define vtk_sqlite3VtabCommit(X)
#else
VTK_SQLITE_PRIVATE    void vtk_sqlite3VtabClear(Table*);
VTK_SQLITE_PRIVATE    int vtk_sqlite3VtabSync(vtk_sqlite3 *db, int rc);
VTK_SQLITE_PRIVATE    int vtk_sqlite3VtabRollback(vtk_sqlite3 *db);
VTK_SQLITE_PRIVATE    int vtk_sqlite3VtabCommit(vtk_sqlite3 *db);
#endif
VTK_SQLITE_PRIVATE void vtk_sqlite3VtabLock(vtk_sqlite3_vtab*);
VTK_SQLITE_PRIVATE void vtk_sqlite3VtabUnlock(vtk_sqlite3*, vtk_sqlite3_vtab*);
VTK_SQLITE_PRIVATE void vtk_sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
VTK_SQLITE_PRIVATE void vtk_sqlite3VtabFinishParse(Parse*, Token*);
VTK_SQLITE_PRIVATE void vtk_sqlite3VtabArgInit(Parse*);
VTK_SQLITE_PRIVATE void vtk_sqlite3VtabArgExtend(Parse*, Token*);
VTK_SQLITE_PRIVATE int vtk_sqlite3VtabCallCreate(vtk_sqlite3*, int, const char *, char **);
VTK_SQLITE_PRIVATE int vtk_sqlite3VtabCallConnect(Parse*, Table*);
VTK_SQLITE_PRIVATE int vtk_sqlite3VtabCallDestroy(vtk_sqlite3*, int, const char *);
VTK_SQLITE_PRIVATE int vtk_sqlite3VtabBegin(vtk_sqlite3 *, vtk_sqlite3_vtab *);
VTK_SQLITE_PRIVATE FuncDef *vtk_sqlite3VtabOverloadFunction(FuncDef*, int nArg, Expr*);
VTK_SQLITE_PRIVATE void vtk_sqlite3InvalidFunction(vtk_sqlite3_context*,int,vtk_sqlite3_value**);
VTK_SQLITE_PRIVATE int vtk_sqlite3Reprepare(Vdbe*);
VTK_SQLITE_PRIVATE void vtk_sqlite3ExprListCheckLength(Parse*, ExprList*, int, const char*);
CollSeq* vtk_sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);

#if VTK_SQLITE_MAX_EXPR_DEPTH>0
VTK_SQLITE_PRIVATE   void vtk_sqlite3ExprSetHeight(Expr *);
VTK_SQLITE_PRIVATE   int vtk_sqlite3SelectExprHeight(Select *);
#else
  #define vtk_sqlite3ExprSetHeight(x)
#endif

/* this function is never referenced or defined */
/* VTK_SQLITE_PRIVATE u32 vtk_sqlite3Get2byte(const u8*); */
VTK_SQLITE_PRIVATE u32 vtk_sqlite3Get4byte(const u8*);
/* this function is never referenced or defined */
/* VTK_SQLITE_PRIVATE void vtk_sqlite3Put2byte(u8*, u32); */
VTK_SQLITE_PRIVATE void vtk_sqlite3Put4byte(u8*, u32);

#ifdef VTK_SQLITE_SSE
#include "sseInt.h"
#endif

#ifdef VTK_SQLITE_DEBUG
VTK_SQLITE_PRIVATE   void vtk_sqlite3ParserTrace(FILE*, char *);
#endif

/*
** If the VTK_SQLITE_ENABLE IOTRACE exists then the global variable
** vtk_sqlite3_io_trace is a pointer to a printf-like routine used to
** print I/O tracing messages. 
*/
#ifdef VTK_SQLITE_ENABLE_IOTRACE
# define IOTRACE(A)  if( vtk_sqlite3_io_trace ){ vtk_sqlite3_io_trace A; }
VTK_SQLITE_PRIVATE   void vtk_sqlite3VdbeIOTraceSql(Vdbe*);
#else
# define IOTRACE(A)
# define vtk_sqlite3VdbeIOTraceSql(X)
#endif
extern void (*vtk_sqlite3_io_trace)(const char*,...);

#endif

/************** End of vtk_sqliteInt.h *******************************************/
/************** Continuing where we left off in date.c ***********************/
#include <ctype.h>
#include <time.h>

#ifndef VTK_SQLITE_OMIT_DATETIME_FUNCS

/*
** A structure for holding a single date and time.
*/
typedef struct DateTime DateTime;
struct DateTime {
  double rJD;      /* The julian day number */
  int Y, M, D;     /* Year, month, and day */
  int h, m;        /* Hour and minutes */
  int tz;          /* Timezone offset in minutes */
  double s;        /* Seconds */
  char validYMD;   /* True if Y,M,D are valid */
  char validHMS;   /* True if h,m,s are valid */
  char validJD;    /* True if rJD is valid */
  char validTZ;    /* True if tz is valid */
};


/*
** Convert zDate into one or more integers.  Additional arguments
** come in groups of 5 as follows:
**
**       N       number of digits in the integer
**       min     minimum allowed value of the integer
**       max     maximum allowed value of the integer
**       nextC   first character after the integer
**       pVal    where to write the integers value.
**
** Conversions continue until one with nextC==0 is encountered.
** The function returns the number of successful conversions.
*/
static int getDigits(const char *zDate, ...){
  va_list ap;
  int val;
  int N;
  int min;
  int max;
  int nextC;
  int *pVal;
  int cnt = 0;
  va_start(ap, zDate);
  do{
    N = va_arg(ap, int);
    min = va_arg(ap, int);
    max = va_arg(ap, int);
    nextC = va_arg(ap, int);
    pVal = va_arg(ap, int*);
    val = 0;
    while( N-- ){
      if( !isdigit(*(u8*)zDate) ){
        goto end_getDigits;
      }
      val = val*10 + *zDate - '0';
      zDate++;
    }
    if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
      goto end_getDigits;
    }
    *pVal = val;
    zDate++;
    cnt++;
  }while( nextC );
end_getDigits:
  va_end(ap);
  return cnt;
}

/*
** Read text from z[] and convert into a floating point number.  Return
** the number of digits converted.
*/
#define getValue vtk_sqlite3AtoF

/*
** Parse a timezone extension on the end of a date-time.
** The extension is of the form:
**
**        (+/-)HH:MM
**
** If the parse is successful, write the number of minutes
** of change in *pnMin and return 0.  If a parser error occurs,
** return 0.
**
** A missing specifier is not considered an error.
*/
static int parseTimezone(const char *zDate, DateTime *p){
  int sgn = 0;
  int nHr, nMn;
  while( isspace(*(u8*)zDate) ){ zDate++; }
  p->tz = 0;
  if( *zDate=='-' ){
    sgn = -1;
  }else if( *zDate=='+' ){
    sgn = +1;
  }else{
    return *zDate!=0;
  }
  zDate++;
  if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
    return 1;
  }
  zDate += 5;
  p->tz = sgn*(nMn + nHr*60);
  while( isspace(*(u8*)zDate) ){ zDate++; }
  return *zDate!=0;
}

/*
** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
** The HH, MM, and SS must each be exactly 2 digits.  The
** fractional seconds FFFF can be one or more digits.
**
** Return 1 if there is a parsing error and 0 on success.
*/
static int parseHhMmSs(const char *zDate, DateTime *p){
  int h, m, s;
  double ms = 0.0;
  if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
    return 1;
  }
  zDate += 5;
  if( *zDate==':' ){
    zDate++;
    if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
      return 1;
    }
    zDate += 2;
    if( *zDate=='.' && isdigit((u8)zDate[1]) ){
      double rScale = 1.0;
      zDate++;
      while( isdigit(*(u8*)zDate) ){
        ms = ms*10.0 + *zDate - '0';
        rScale *= 10.0;
        zDate++;
      }
      ms /= rScale;
    }
  }else{
    s = 0;
  }
  p->validJD = 0;
  p->validHMS = 1;
  p->h = h;
  p->m = m;
  p->s = s + ms;
  if( parseTimezone(zDate, p) ) return 1;
  p->validTZ = (char)(p->tz!=0);
  return 0;
}

/*
** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
** that the YYYY-MM-DD is according to the Gregorian calendar.
**
** Reference:  Meeus page 61
*/
static void computeJD(DateTime *p){
  int Y, M, D, A, B, X1, X2;

  if( p->validJD ) return;
  if( p->validYMD ){
    Y = p->Y;
    M = p->M;
    D = p->D;
  }else{
    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
    M = 1;
    D = 1;
  }
  if( M<=2 ){
    Y--;
    M += 12;
  }
  A = Y/100;
  B = 2 - A + (A/4);
  X1 = (int)(365.25*(Y+4716));
  X2 = (int)(30.6001*(M+1));
  p->rJD = X1 + X2 + D + B - 1524.5;
  p->validJD = 1;
  if( p->validHMS ){
    p->rJD += (p->h*3600.0 + p->m*60.0 + p->s)/86400.0;
    if( p->validTZ ){
      p->rJD -= p->tz*60/86400.0;
      p->validYMD = 0;
      p->validHMS = 0;
      p->validTZ = 0;
    }
  }
}

/*
** Parse dates of the form
**
**     YYYY-MM-DD HH:MM:SS.FFF
**     YYYY-MM-DD HH:MM:SS
**     YYYY-MM-DD HH:MM
**     YYYY-MM-DD
**
** Write the result into the DateTime structure and return 0
** on success and 1 if the input string is not a well-formed
** date.
*/
static int parseYyyyMmDd(const char *zDate, DateTime *p){
  int Y, M, D, neg;

  if( zDate[0]=='-' ){
    zDate++;
    neg = 1;
  }else{
    neg = 0;
  }
  if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
    return 1;
  }
  zDate += 10;
  while( isspace(*(u8*)zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  if( parseHhMmSs(zDate, p)==0 ){
    /* We got the time */
  }else if( *zDate==0 ){
    p->validHMS = 0;
  }else{
    return 1;
  }
  p->validJD = 0;
  p->validYMD = 1;
  p->Y = neg ? -Y : Y;
  p->M = M;
  p->D = D;
  if( p->validTZ ){
    computeJD(p);
  }
  return 0;
}

/*
** Attempt to parse the given string into a Julian Day Number.  Return
** the number of errors.
**
** The following are acceptable forms for the input string:
**
**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
**      DDDD.DD 
**      now
**
** In the first form, the +/-HH:MM is always optional.  The fractional
** seconds extension (the ".FFF") is optional.  The seconds portion
** (":SS.FFF") is option.  The year and date can be omitted as long
** as there is a time string.  The time string can be omitted as long
** as there is a year and date.
*/
static int parseDateOrTime(const char *zDate, DateTime *p){
  memset(p, 0, sizeof(*p));
  if( parseYyyyMmDd(zDate,p)==0 ){
    return 0;
  }else if( parseHhMmSs(zDate, p)==0 ){
    return 0;
  }else if( vtk_sqlite3StrICmp(zDate,"now")==0){
    double r;
    vtk_sqlite3OsCurrentTime(&r);
    p->rJD = r;
    p->validJD = 1;
    return 0;
  }else if( vtk_sqlite3IsNumber(zDate, 0, VTK_SQLITE_UTF8) ){
    getValue(zDate, &p->rJD);
    p->validJD = 1;
    return 0;
  }
  return 1;
}

/*
** Compute the Year, Month, and Day from the julian day number.
*/
static void computeYMD(DateTime *p){
  int Z, A, B, C, D, E, X1;
  if( p->validYMD ) return;
  if( !p->validJD ){
    p->Y = 2000;
    p->M = 1;
    p->D = 1;
  }else{
    Z = (int)(p->rJD + 0.5);
    A = (int)((Z - 1867216.25)/36524.25);
    A = Z + 1 + A - (A/4);
    B = A + 1524;
    C = (int)((B - 122.1)/365.25);
    D = (int)(365.25*C);
    E = (int)((B-D)/30.6001);
    X1 = (int)(30.6001*E);
    p->D = B - D - X1;
    p->M = E<14 ? E-1 : E-13;
    p->Y = p->M>2 ? C - 4716 : C - 4715;
  }
  p->validYMD = 1;
}

/*
** Compute the Hour, Minute, and Seconds from the julian day number.
*/
static void computeHMS(DateTime *p){
  int Z, s;
  if( p->validHMS ) return;
  computeJD(p);
  Z = (int)(p->rJD + 0.5);
  s = (int)((p->rJD + 0.5 - Z)*86400000.0 + 0.5);
  p->s = 0.001*s;
  s = (int) p->s;
  p->s -= s;
  p->h = s/3600;
  s -= p->h*3600;
  p->m = s/60;
  p->s += s - p->m*60;
  p->validHMS = 1;
}

/*
** Compute both YMD and HMS
*/
static void computeYMD_HMS(DateTime *p){
  computeYMD(p);
  computeHMS(p);
}

/*
** Clear the YMD and HMS and the TZ
*/
static void clearYMD_HMS_TZ(DateTime *p){
  p->validYMD = 0;
  p->validHMS = 0;
  p->validTZ = 0;
}

/*
** Compute the difference (in days) between localtime and UTC (a.k.a. GMT)
** for the time value p where p is in UTC.
*/
static double localtimeOffset(DateTime *p){
  DateTime x, y;
  time_t t;
  x = *p;
  computeYMD_HMS(&x);
  if( x.Y<1971 || x.Y>=2038 ){
    x.Y = 2000;
    x.M = 1;
    x.D = 1;
    x.h = 0;
    x.m = 0;
    x.s = 0.0;
  } else {
    int s = (int)(x.s + 0.5);
    x.s = s;
  }
  x.tz = 0;
  x.validJD = 0;
  computeJD(&x);
  t = (int)((x.rJD-2440587.5)*86400.0 + 0.5);
#ifdef HAVE_LOCALTIME_R
  {
    struct tm sLocal;
    localtime_r(&t, &sLocal);
    y.Y = sLocal.tm_year + 1900;
    y.M = sLocal.tm_mon + 1;
    y.D = sLocal.tm_mday;
    y.h = sLocal.tm_hour;
    y.m = sLocal.tm_min;
    y.s = sLocal.tm_sec;
  }
#else
  {
    struct tm *pTm;
    vtk_sqlite3OsEnterMutex();
    pTm = localtime(&t);
    y.Y = pTm->tm_year + 1900;
    y.M = pTm->tm_mon + 1;
    y.D = pTm->tm_mday;
    y.h = pTm->tm_hour;
    y.m = pTm->tm_min;
    y.s = pTm->tm_sec;
    vtk_sqlite3OsLeaveMutex();
  }
#endif
  y.validYMD = 1;
  y.validHMS = 1;
  y.validJD = 0;
  y.validTZ = 0;
  computeJD(&y);
  return y.rJD - x.rJD;
}

/*
** Process a modifier to a date-time stamp.  The modifiers are
** as follows:
**
**     NNN days
**     NNN hours
**     NNN minutes
**     NNN.NNNN seconds
**     NNN months
**     NNN years
**     start of month
**     start of year
**     start of week
**     start of day
**     weekday N
**     unixepoch
**     localtime
**     utc
**
** Return 0 on success and 1 if there is any kind of error.
*/
static int parseModifier(const char *zMod, DateTime *p){
  int rc = 1;
  int n;
  double r;
  char *z, zBuf[30];
  z = zBuf;
  for(n=0; n<(int)(sizeof(zBuf)-1) && zMod[n]; n++){
    z[n] = (char)(tolower(zMod[n]));
  }
  z[n] = 0;
  switch( z[0] ){
    case 'l': {
      /*    localtime
      **
      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
      ** show local time.
      */
      if( strcmp(z, "localtime")==0 ){
        computeJD(p);
        p->rJD += localtimeOffset(p);
        clearYMD_HMS_TZ(p);
        rc = 0;
      }
      break;
    }
    case 'u': {
      /*
      **    unixepoch
      **
      ** Treat the current value of p->rJD as the number of
      ** seconds since 1970.  Convert to a real julian day number.
      */
      if( strcmp(z, "unixepoch")==0 && p->validJD ){
        p->rJD = p->rJD/86400.0 + 2440587.5;
        clearYMD_HMS_TZ(p);
        rc = 0;
      }else if( strcmp(z, "utc")==0 ){
        double c1;
        computeJD(p);
        c1 = localtimeOffset(p);
        p->rJD -= c1;
        clearYMD_HMS_TZ(p);
        p->rJD += c1 - localtimeOffset(p);
        rc = 0;
      }
      break;
    }
    case 'w': {
      /*
      **    weekday N
      **
      ** Move the date to the same time on the next occurrence of
      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
      ** date is already on the appropriate weekday, this is a no-op.
      */
      if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
                 && (n=(int)r)==r && n>=0 && r<7 ){
        int Z;
        computeYMD_HMS(p);
        p->validTZ = 0;
        p->validJD = 0;
        computeJD(p);
        Z = (int)(p->rJD + 1.5);
        Z %= 7;
        if( Z>n ) Z -= 7;
        p->rJD += n - Z;
        clearYMD_HMS_TZ(p);
        rc = 0;
      }
      break;
    }
    case 's': {
      /*
      **    start of TTTTT
      **
      ** Move the date backwards to the beginning of the current day,
      ** or month or year.
      */
      if( strncmp(z, "start of ", 9)!=0 ) break;
      z += 9;
      computeYMD(p);
      p->validHMS = 1;
      p->h = p->m = 0;
      p->s = 0.0;
      p->validTZ = 0;
      p->validJD = 0;
      if( strcmp(z,"month")==0 ){
        p->D = 1;
        rc = 0;
      }else if( strcmp(z,"year")==0 ){
        computeYMD(p);
        p->M = 1;
        p->D = 1;
        rc = 0;
      }else if( strcmp(z,"day")==0 ){
        rc = 0;
      }
      break;
    }
    case '+':
    case '-':
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9': {
      n = getValue(z, &r);
      assert( n>=1 );
      if( z[n]==':' ){
        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
        ** specified number of hours, minutes, seconds, and fractional seconds
        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
        ** omitted.
        */
        const char *z2 = z;
        DateTime tx;
        int day;
        if( !isdigit(*(u8*)z2) ) z2++;
        memset(&tx, 0, sizeof(tx));
        if( parseHhMmSs(z2, &tx) ) break;
        computeJD(&tx);
        tx.rJD -= 0.5;
        day = (int)tx.rJD;
        tx.rJD -= day;
        if( z[0]=='-' ) tx.rJD = -tx.rJD;
        computeJD(p);
        clearYMD_HMS_TZ(p);
        p->rJD += tx.rJD;
        rc = 0;
        break;
      }
      z += n;
      while( isspace(*(u8*)z) ) z++;
      n = strlen(z);
      if( n>10 || n<3 ) break;
      if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
      computeJD(p);
      rc = 0;
      if( n==3 && strcmp(z,"day")==0 ){
        p->rJD += r;
      }else if( n==4 && strcmp(z,"hour")==0 ){
        p->rJD += r/24.0;
      }else if( n==6 && strcmp(z,"minute")==0 ){
        p->rJD += r/(24.0*60.0);
      }else if( n==6 && strcmp(z,"second")==0 ){
        p->rJD += r/(24.0*60.0*60.0);
      }else if( n==5 && strcmp(z,"month")==0 ){
        int x, y;
        computeYMD_HMS(p);
        p->M += (int)r;
        x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
        p->Y += x;
        p->M -= x*12;
        p->validJD = 0;
        computeJD(p);
        y = (int)r;
        if( y!=r ){
          p->rJD += (r - y)*30.0;
        }
      }else if( n==4 && strcmp(z,"year")==0 ){
        computeYMD_HMS(p);
        p->Y += (int)r;
        p->validJD = 0;
        computeJD(p);
      }else{
        rc = 1;
      }
      clearYMD_HMS_TZ(p);
      break;
    }
    default: {
      break;
    }
  }
  return rc;
}

/*
** Process time function arguments.  argv[0] is a date-time stamp.
** argv[1] and following are modifiers.  Parse them all and write
** the resulting time into the DateTime structure p.  Return 0
** on success and 1 if there are any errors.
*/
static int isDate(int argc, vtk_sqlite3_value **argv, DateTime *p){
  int i;
  const unsigned char *z;
  if( argc==0 ) return 1;
  if( (z = vtk_sqlite3_value_text(argv[0]))==0 || parseDateOrTime((char*)z, p) ){
    return 1;
  }
  for(i=1; i<argc; i++){
    if( (z = vtk_sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
      return 1;
    }
  }
  return 0;
}


/*
** The following routines implement the various date and time functions
** of Vtk_Sqlite.
*/

/*
**    julianday( TIMESTRING, MOD, MOD, ...)
**
** Return the julian day number of the date specified in the arguments
*/
static void juliandayFunc(
  vtk_sqlite3_context *context,
  int argc,
  vtk_sqlite3_value **argv
){
  DateTime x;
  if( isDate(argc, argv, &x)==0 ){
    computeJD(&x);
    vtk_sqlite3_result_double(context, x.rJD);
  }
}

/*
**    datetime( TIMESTRING, MOD, MOD, ...)
**
** Return YYYY-MM-DD HH:MM:SS
*/
static void datetimeFunc(
  vtk_sqlite3_context *context,
  int argc,
  vtk_sqlite3_value **argv
){
  DateTime x;
  if( isDate(argc, argv, &x)==0 ){
    char zBuf[100];
    computeYMD_HMS(&x);
    vtk_sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
    vtk_sqlite3_result_text(context, zBuf, -1, VTK_SQLITE_TRANSIENT);
  }
}

/*
**    time( TIMESTRING, MOD, MOD, ...)
**
** Return HH:MM:SS
*/
static void timeFunc(
  vtk_sqlite3_context *context,
  int argc,
  vtk_sqlite3_value **argv
){
  DateTime x;
  if( isDate(argc, argv, &x)==0 ){
    char zBuf[100];
    computeHMS(&x);
    vtk_sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
    vtk_sqlite3_result_text(context, zBuf, -1, VTK_SQLITE_TRANSIENT);
  }
}

/*
**    date( TIMESTRING, MOD, MOD, ...)
**
** Return YYYY-MM-DD
*/
static void dateFunc(
  vtk_sqlite3_context *context,
  int argc,
  vtk_sqlite3_value **argv
){
  DateTime x;
  if( isDate(argc, argv, &x)==0 ){
    char zBuf[100];
    computeYMD(&x);
    vtk_sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
    vtk_sqlite3_result_text(context, zBuf, -1, VTK_SQLITE_TRANSIENT);
  }
}

/*
**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
**
** Return a string described by FORMAT.  Conversions as follows:
**
**   %d  day of month
**   %f  ** fractional seconds  SS.SSS
**   %H  hour 00-24
**   %j  day of year 000-366
**   %J  ** Julian day number
**   %m  month 01-12
**   %M  minute 00-59
**   %s  seconds since 1970-01-01
**   %S  seconds 00-59
**   %w  day of week 0-6  sunday==0
**   %W  week of year 00-53
**   %Y  year 0000-9999
**   %%  %
*/
static void strftimeFunc(
  vtk_sqlite3_context *context,
  int argc,
  vtk_sqlite3_value **argv
){
  DateTime x;
  u64 n;
  int i, j;
  char *z;
  const char *zFmt = (const char*)vtk_sqlite3_value_text(argv[0]);
  char zBuf[100];
  if( zFmt==0 || isDate(argc-1, argv+1, &x) ) return;
  for(i=0, n=1; zFmt[i]; i++, n++){
    if( zFmt[i]=='%' ){
      switch( zFmt[i+1] ){
        case 'd':
        case 'H':
        case 'm':
        case 'M':
        case 'S':
        case 'W':
          n++;
          /* fall thru */
        case 'w':
        case '%':
          break;
        case 'f':
          n += 8;
          break;
        case 'j':
          n += 3;
          break;
        case 'Y':
          n += 8;
          break;
        case 's':
        case 'J':
          n += 50;
          break;
        default:
          return;  /* ERROR.  return a NULL */
      }
      i++;
    }
  }
  if( n<sizeof(zBuf) ){
    z = zBuf;
  }else if( n>VTK_SQLITE_MAX_LENGTH ){
    vtk_sqlite3_result_error_toobig(context);
    return;
  }else{
    z = (char *) vtk_sqliteMalloc( (int)n );
    if( z==0 ) return;
  }
  computeJD(&x);
  computeYMD_HMS(&x);
  for(i=j=0; zFmt[i]; i++){
    if( zFmt[i]!='%' ){
      z[j++] = zFmt[i];
    }else{
      i++;
      switch( zFmt[i] ){
        case 'd':  vtk_sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
        case 'f': {
          double s = x.s;
          if( s>59.999 ) s = 59.999;
          vtk_sqlite3_snprintf(7, &z[j],"%06.3f", s);
          j += strlen(&z[j]);
          break;
        }
        case 'H':  vtk_sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
        case 'W': /* Fall thru */
        case 'j': {
          int nDay;             /* Number of days since 1st day of year */
          DateTime y = x;
          y.validJD = 0;
          y.M = 1;
          y.D = 1;
          computeJD(&y);
          nDay = (int)(x.rJD - y.rJD + 0.5);
          if( zFmt[i]=='W' ){
            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
            wd = ((int)(x.rJD+0.5)) % 7;
            vtk_sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
            j += 2;
          }else{
            vtk_sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
            j += 3;
          }
          break;
        }
        case 'J': {
          vtk_sqlite3_snprintf(20, &z[j],"%.16g",x.rJD);
          j+=strlen(&z[j]);
          break;
        }
        case 'm':  vtk_sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
        case 'M':  vtk_sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
        case 's': {
          vtk_sqlite3_snprintf(30,&z[j],"%d",
                           (int)((x.rJD-2440587.5)*86400.0 + 0.5));
          j += strlen(&z[j]);
          break;
        }
        case 'S':  vtk_sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
        case 'w':  z[j++] = (char)((((int)(x.rJD+1.5)) % 7)) + '0'; break;
        case 'Y':  vtk_sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=strlen(&z[j]);break;
        case '%':  z[j++] = '%'; break;
      }
    }
  }
  z[j] = 0;
  vtk_sqlite3_result_text(context, z, -1, VTK_SQLITE_TRANSIENT);
  if( z!=zBuf ){
    vtk_sqliteFree(z);
  }
}

/*
** current_time()
**
** This function returns the same value as time('now').
*/
static void ctimeFunc(
  vtk_sqlite3_context *context,
  int argc,
  vtk_sqlite3_value ** argv
){
  vtk_sqlite3_value *pVal = vtk_sqlite3ValueNew();
  (void)argc; (void)argv; /* use arguments */
  if( pVal ){
    vtk_sqlite3ValueSetStr(pVal, -1, "now", VTK_SQLITE_UTF8, VTK_SQLITE_STATIC);
    timeFunc(context, 1, &pVal);
    vtk_sqlite3ValueFree(pVal);
  }
}

/*
** current_date()
**
** This function returns the same value as date('now').
*/
static void cdateFunc(
  vtk_sqlite3_context *context,
  int argc,
  vtk_sqlite3_value **argv
){
  vtk_sqlite3_value *pVal = vtk_sqlite3ValueNew();
  (void)argc; (void)argv; /* use arguments */
  if( pVal ){
    vtk_sqlite3ValueSetStr(pVal, -1, "now", VTK_SQLITE_UTF8, VTK_SQLITE_STATIC);
    dateFunc(context, 1, &pVal);
    vtk_sqlite3ValueFree(pVal);
  }
}

/*
** current_timestamp()
**
** This function returns the same value as datetime('now').
*/
static void ctimestampFunc(
  vtk_sqlite3_context *context,
  int argc,
  vtk_sqlite3_value **argv
){
  vtk_sqlite3_value *pVal = vtk_sqlite3ValueNew();
  (void)argc; (void)argv; /* use arguments */
  if( pVal ){
    vtk_sqlite3ValueSetStr(pVal, -1, "now", VTK_SQLITE_UTF8, VTK_SQLITE_STATIC);
    datetimeFunc(context, 1, &pVal);
    vtk_sqlite3ValueFree(pVal);
  }
}
#endif /* !defined(VTK_SQLITE_OMIT_DATETIME_FUNCS) */

#ifdef VTK_SQLITE_OMIT_DATETIME_FUNCS
/*
** If the library is compiled to omit the full-scale date and time
** handling (to get a smaller binary), the following minimal version
** of the functions current_time(), current_date() and current_timestamp()
** are included instead. This is to support column declarations that
** include "DEFAULT CURRENT_TIME" etc.
**
** This function uses the C-library functions time(), gmtime()
** and strftime(). The format string to pass to strftime() is supplied
** as the user-data for the function.
*/
static void currentTimeFunc(
  vtk_sqlite3_context *context,
  int argc,
  vtk_sqlite3_value **argv
){
  time_t t;
  char *zFormat = (char *)vtk_sqlite3_user_data(context);
  char zBuf[20];

  time(&t);
#ifdef VTK_SQLITE_TEST
  {
    extern int vtk_sqlite3_current_time;  /* See os_XXX.c */
    if( vtk_sqlite3_current_time ){
      t = vtk_sqlite3_current_time;
    }
  }
#endif

#ifdef HAVE_GMTIME_R
  {
    struct tm sNow;
    gmtime_r(&t, &sNow);
    strftime(zBuf, 20, zFormat, &sNow);
  }
#else
  {
    struct tm *pTm;
    vtk_sqlite3OsEnterMutex();
    pTm = gmtime(&t);
    strftime(zBuf, 20, zFormat, pTm);
    vtk_sqlite3OsLeaveMutex();
  }
#endif

  vtk_sqlite3_result_text(context, zBuf, -1, VTK_SQLITE_TRANSIENT);
}
#endif

/*
** This function registered all of the above C functions as SQL
** functions.  This should be the only routine in this file with
** external linkage.
*/
VTK_SQLITE_PRIVATE void vtk_sqlite3RegisterDateTimeFunctions(vtk_sqlite3 *db){
#ifndef VTK_SQLITE_OMIT_DATETIME_FUNCS
  static const struct {
     char *zName;
     int nArg;
     void (*xFunc)(vtk_sqlite3_context*,int,vtk_sqlite3_value**);
  } aFuncs[] = {
    { "julianday", -1, juliandayFunc   },
    { "date",      -1, dateFunc        },
    { "time",      -1, timeFunc        },
    { "datetime",  -1, datetimeFunc    },
    { "strftime",  -1, strftimeFunc    },
    { "current_time",       0, ctimeFunc      },
    { "current_timestamp",  0, ctimestampFunc },
    { "current_date",       0, cdateFunc      },
  };
  int i;

  for(i=0; i<(int)(sizeof(aFuncs)/sizeof(aFuncs[0])); i++){
    vtk_sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
        VTK_SQLITE_UTF8, 0, aFuncs[i].xFunc, 0, 0);
  }
#else
  static const struct {
     char *zName;
     char *zFormat;
  } aFuncs[] = {
    { "current_time", "%H:%M:%S" },
    { "current_date", "%Y-%m-%d" },
    { "current_timestamp", "%Y-%m-%d %H:%M:%S" }
  };
  int i;

  for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
    vtk_sqlite3CreateFunc(db, aFuncs[i].zName, 0, VTK_SQLITE_UTF8, 
        aFuncs[i].zFormat, currentTimeFunc, 0, 0);
  }
#endif
}

/************** End of date.c ************************************************/
/************** Begin file os.c **********************************************/
/*
** 2005 November 29
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains OS interface code that is common to all
** architectures.
*/
#define _VTK_SQLITE_OS_C_ 1
#undef _VTK_SQLITE_OS_C_

/*
** The following routines are convenience wrappers around methods
** of the OsFile object.  This is mostly just syntactic sugar.  All
** of this would be completely automatic if Vtk_Sqlite were coded using
** C++ instead of plain old C.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3OsClose(OsFile **pId){
  OsFile *id;
  if( pId!=0 && (id = *pId)!=0 ){
    return id->pMethod->xClose(pId);
  }else{
    return VTK_SQLITE_OK;
  }
}
VTK_SQLITE_PRIVATE int vtk_sqlite3OsOpenDirectory(OsFile *id, const char *zName){
  return id->pMethod->xOpenDirectory(id, zName);
}
VTK_SQLITE_PRIVATE int vtk_sqlite3OsRead(OsFile *id, void *pBuf, int amt){
  return id->pMethod->xRead(id, pBuf, amt);
}
VTK_SQLITE_PRIVATE int vtk_sqlite3OsWrite(OsFile *id, const void *pBuf, int amt){
  return id->pMethod->xWrite(id, pBuf, amt);
}
VTK_SQLITE_PRIVATE int vtk_sqlite3OsSeek(OsFile *id, i64 offset){
  return id->pMethod->xSeek(id, offset);
}
VTK_SQLITE_PRIVATE int vtk_sqlite3OsTruncate(OsFile *id, i64 size){
  return id->pMethod->xTruncate(id, size);
}
VTK_SQLITE_PRIVATE int vtk_sqlite3OsSync(OsFile *id, int fullsync){
  return id->pMethod->xSync(id, fullsync);
}
VTK_SQLITE_PRIVATE void vtk_sqlite3OsSetFullSync(OsFile *id, int value){
  id->pMethod->xSetFullSync(id, value);
}
VTK_SQLITE_PRIVATE int vtk_sqlite3OsFileSize(OsFile *id, i64 *pSize){
  return id->pMethod->xFileSize(id, pSize);
}
VTK_SQLITE_PRIVATE int vtk_sqlite3OsLock(OsFile *id, int lockType){
  return id->pMethod->xLock(id, lockType);
}
VTK_SQLITE_PRIVATE int vtk_sqlite3OsUnlock(OsFile *id, int lockType){
  return id->pMethod->xUnlock(id, lockType);
}
VTK_SQLITE_PRIVATE int vtk_sqlite3OsCheckReservedLock(OsFile *id){
  return id->pMethod->xCheckReservedLock(id);
}
VTK_SQLITE_PRIVATE int vtk_sqlite3OsSectorSize(OsFile *id){
  int (*xSectorSize)(OsFile*) = id->pMethod->xSectorSize;
  return xSectorSize ? xSectorSize(id) : VTK_SQLITE_DEFAULT_SECTOR_SIZE;
}

#if defined(VTK_SQLITE_TEST) || defined(VTK_SQLITE_DEBUG)
  /* These methods are currently only used for testing and debugging. */
  int vtk_sqlite3OsFileHandle(OsFile *id){
    return id->pMethod->xFileHandle(id);
  }
  int vtk_sqlite3OsLockState(OsFile *id){
    return id->pMethod->xLockState(id);
  }
#endif

#ifdef VTK_SQLITE_ENABLE_REDEF_IO
/*
** A function to return a pointer to the virtual function table.
** This routine really does not accomplish very much since the
** virtual function table is a global variable and anybody who
** can call this function can just as easily access the variable
** for themselves.  Nevertheless, we include this routine for
** backwards compatibility with an earlier redefinable I/O
** interface design.
*/
struct vtk_sqlite3OsVtbl *vtk_sqlite3_os_switch(void){
  return &vtk_sqlite3Os;
}
#endif

/************** End of os.c **************************************************/
/************** Begin file malloc.c ******************************************/
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Memory allocation functions used throughout vtk_sqlite.
**
**
** $Id: vtk_sqlite3.c,v 1.15 2007/09/20 18:33:36 king Exp $
*/

/*
** MALLOC WRAPPER ARCHITECTURE
**
** The vtk_sqlite code accesses dynamic memory allocation/deallocation by invoking
** the following six APIs (which may be implemented as macros).
**
**     vtk_sqlite3Malloc()
**     vtk_sqlite3MallocRaw()
**     vtk_sqlite3Realloc()
**     vtk_sqlite3ReallocOrFree()
**     vtk_sqlite3Free()
**     vtk_sqlite3AllocSize()
**
** The function vtk_sqlite3FreeX performs the same task as vtk_sqlite3Free and is
** guaranteed to be a real function. The same holds for vtk_sqlite3MallocX
**
** The above APIs are implemented in terms of the functions provided in the
** operating-system interface. The OS interface is never accessed directly
** by code outside of this file.
**
**     vtk_sqlite3OsMalloc()
**     vtk_sqlite3OsRealloc()
**     vtk_sqlite3OsFree()
**     vtk_sqlite3OsAllocationSize()
**
** Functions vtk_sqlite3MallocRaw() and vtk_sqlite3Realloc() may invoke 
** vtk_sqlite3_release_memory() if a call to vtk_sqlite3OsMalloc() or
** vtk_sqlite3OsRealloc() fails (or if the soft-heap-limit for the thread is
** exceeded). Function vtk_sqlite3Malloc() usually invokes
** vtk_sqlite3MallocRaw().
**
** MALLOC TEST WRAPPER ARCHITECTURE
**
** The test wrapper provides extra test facilities to ensure the library 
** does not leak memory and handles the failure of the underlying OS level
** allocation system correctly. It is only present if the library is 
** compiled with the VTK_SQLITE_MEMDEBUG macro set.
**
**     * Guardposts to detect overwrites.
**     * Ability to cause a specific Malloc() or Realloc() to fail.
**     * Audit outstanding memory allocations (i.e check for leaks).
*/

#define MAX(x,y) ((x)>(y)?(x):(y))

#if defined(VTK_SQLITE_ENABLE_MEMORY_MANAGEMENT) && !defined(VTK_SQLITE_OMIT_DISKIO)
/*
** Set the soft heap-size limit for the current thread. Passing a negative
** value indicates no limit.
*/
void vtk_sqlite3_soft_heap_limit(int n){
  ThreadData *pTd = vtk_sqlite3ThreadData();
  if( pTd ){
    pTd->nSoftHeapLimit = n;
  }
  vtk_sqlite3ReleaseThreadData();
}

/*
** Release memory held by Vtk_Sqlite instances created by the current thread.
*/
int vtk_sqlite3_release_memory(int n){
  return vtk_sqlite3PagerReleaseMemory(n);
}
#else
/* If VTK_SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined, then define a version
** of vtk_sqlite3_release_memory() to be used by other code in this file.
** This is done for no better reason than to reduce the number of 
** pre-processor #ifndef statements.
*/
#define vtk_sqlite3_release_memory(x) 0    /* 0 == no memory freed */
#endif

#ifdef VTK_SQLITE_MEMDEBUG
/*--------------------------------------------------------------------------
** Begin code for memory allocation system test layer.
**
** Memory debugging is turned on by defining the VTK_SQLITE_MEMDEBUG macro.
**
** VTK_SQLITE_MEMDEBUG==1    -> Fence-posting only (thread safe) 
** VTK_SQLITE_MEMDEBUG==2    -> Fence-posting + linked list of allocations (not ts)
** VTK_SQLITE_MEMDEBUG==3    -> Above + backtraces (not thread safe, req. glibc)
*/

/* Figure out whether or not to store backtrace() information for each malloc.
** The backtrace() function is only used if VTK_SQLITE_MEMDEBUG is set to 2 or 
** greater and glibc is in use. If we don't want to use backtrace(), then just
** define it as an empty macro and set the amount of space reserved to 0.
*/
#if defined(__GLIBC__) && VTK_SQLITE_MEMDEBUG>2
  extern int backtrace(void **, int);
  #define TESTALLOC_STACKSIZE 128
  #define TESTALLOC_STACKFRAMES ((TESTALLOC_STACKSIZE-8)/sizeof(void*))
#else
  #define backtrace(x, y)
  #define TESTALLOC_STACKSIZE 0
  #define TESTALLOC_STACKFRAMES 0
#endif

/*
** Number of 32-bit guard words.  This should probably be a multiple of
** 2 since on 64-bit machines we want the value returned by vtk_sqliteMalloc()
** to be 8-byte aligned.
*/
#ifndef TESTALLOC_NGUARD
# define TESTALLOC_NGUARD 2
#endif

/*
** Size reserved for storing file-name along with each malloc()ed blob.
*/
#define TESTALLOC_FILESIZE 64

/*
** Size reserved for storing the user string. Each time a Malloc() or Realloc()
** call succeeds, up to TESTALLOC_USERSIZE bytes of the string pointed to by
** vtk_sqlite3_malloc_id are stored along with the other test system metadata.
*/
#define TESTALLOC_USERSIZE 64
const char *vtk_sqlite3_malloc_id = 0;

/*
** Blocks used by the test layer have the following format:
**
**        <sizeof(void *) pNext pointer>
**        <sizeof(void *) pPrev pointer>
**        <TESTALLOC_NGUARD 32-bit guard words>
**            <The application level allocation>
**        <TESTALLOC_NGUARD 32-bit guard words>
**        <32-bit line number>
**        <TESTALLOC_FILESIZE bytes containing null-terminated file name>
**        <TESTALLOC_STACKSIZE bytes of backtrace() output>
*/ 

#define TESTALLOC_OFFSET_GUARD1(p)    (sizeof(void *) * 2)
#define TESTALLOC_OFFSET_DATA(p) ( \
  TESTALLOC_OFFSET_GUARD1(p) + sizeof(u32) * TESTALLOC_NGUARD \
)
#define TESTALLOC_OFFSET_GUARD2(p) ( \
  TESTALLOC_OFFSET_DATA(p) + vtk_sqlite3OsAllocationSize(p) - TESTALLOC_OVERHEAD \
)
#define TESTALLOC_OFFSET_LINENUMBER(p) ( \
  TESTALLOC_OFFSET_GUARD2(p) + sizeof(u32) * TESTALLOC_NGUARD \
)
#define TESTALLOC_OFFSET_FILENAME(p) ( \
  TESTALLOC_OFFSET_LINENUMBER(p) + sizeof(u32) \
)
#define TESTALLOC_OFFSET_USER(p) ( \
  TESTALLOC_OFFSET_FILENAME(p) + TESTALLOC_FILESIZE \
)
#define TESTALLOC_OFFSET_STACK(p) ( \
  TESTALLOC_OFFSET_USER(p) + TESTALLOC_USERSIZE + 8 - \
  (TESTALLOC_OFFSET_USER(p) % 8) \
)

#define TESTALLOC_OVERHEAD ( \
  sizeof(void *)*2 +                   /* pPrev and pNext pointers */   \
  TESTALLOC_NGUARD*sizeof(u32)*2 +              /* Guard words */       \
  sizeof(u32) + TESTALLOC_FILESIZE +   /* File and line number */       \
  TESTALLOC_USERSIZE +                 /* User string */                \
  TESTALLOC_STACKSIZE                  /* backtrace() stack */          \
)


/*
** For keeping track of the number of mallocs and frees.   This
** is used to check for memory leaks.  The iMallocFail and iMallocReset
** values are used to simulate malloc() failures during testing in 
** order to verify that the library correctly handles an out-of-memory
** condition.
*/
int vtk_sqlite3_nMalloc;         /* Number of vtk_sqliteMalloc() calls */
int vtk_sqlite3_nFree;           /* Number of vtk_sqliteFree() calls */
int vtk_sqlite3_memUsed;         /* TODO Total memory obtained from malloc */
int vtk_sqlite3_memMax;          /* TODO Mem usage high-water mark */
int vtk_sqlite3_iMallocFail;     /* Fail vtk_sqliteMalloc() after this many calls */
int vtk_sqlite3_iMallocReset = -1; /* When iMallocFail reaches 0, set to this */

void *vtk_sqlite3_pFirst = 0;         /* Pointer to linked list of allocations */
int vtk_sqlite3_nMaxAlloc = 0;        /* High water mark of ThreadData.nAlloc */
int vtk_sqlite3_mallocDisallowed = 0; /* assert() in vtk_sqlite3Malloc() if set */
int vtk_sqlite3_isFail = 0;           /* True if all malloc calls should fail */
const char *vtk_sqlite3_zFile = 0;    /* Filename to associate debug info with */
int vtk_sqlite3_iLine = 0;            /* Line number for debug info */
int vtk_sqlite3_mallocfail_trace = 0; /* Print a msg on malloc fail if true */

/*
** Check for a simulated memory allocation failure.  Return true if
** the failure should be simulated.  Return false to proceed as normal.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3TestMallocFail(){
  if( vtk_sqlite3_isFail ){
    return 1;
  }
  if( vtk_sqlite3_iMallocFail>=0 ){
    vtk_sqlite3_iMallocFail--;
    if( vtk_sqlite3_iMallocFail==0 ){
      vtk_sqlite3_iMallocFail = vtk_sqlite3_iMallocReset;
      vtk_sqlite3_isFail = 1;
      if( vtk_sqlite3_mallocfail_trace ){
         vtk_sqlite3DebugPrintf("###_malloc_fails_###\n");
      }
      return 1;
    }
  }
  return 0;
}

/*
** The argument is a pointer returned by vtk_sqlite3OsMalloc() or xRealloc().
** assert() that the first and last (TESTALLOC_NGUARD*4) bytes are set to the
** values set by the applyGuards() function.
*/
static void checkGuards(u32 *p)
{
  int i;
  char *zAlloc = (char *)p;
  char *z;

  /* First set of guard words */
  z = &zAlloc[TESTALLOC_OFFSET_GUARD1(p)];
  for(i=0; i<TESTALLOC_NGUARD; i++){
    assert(((u32 *)z)[i]==0xdead1122);
  }

  /* Second set of guard words */
  z = &zAlloc[TESTALLOC_OFFSET_GUARD2(p)];
  for(i=0; i<TESTALLOC_NGUARD; i++){
    u32 guard = 0;
    memcpy(&guard, &z[i*sizeof(u32)], sizeof(u32));
    assert(guard==0xdead3344);
  }
}

/*
** The argument is a pointer returned by vtk_sqlite3OsMalloc() or Realloc(). The
** first and last (TESTALLOC_NGUARD*4) bytes are set to known values for use as 
** guard-posts.
*/
static void applyGuards(u32 *p)
{
  int i;
  char *z;
  char *zAlloc = (char *)p;

  /* First set of guard words */
  z = &zAlloc[TESTALLOC_OFFSET_GUARD1(p)];
  for(i=0; i<TESTALLOC_NGUARD; i++){
    ((u32 *)z)[i] = 0xdead1122;
  }

  /* Second set of guard words */
  z = &zAlloc[TESTALLOC_OFFSET_GUARD2(p)];
  for(i=0; i<TESTALLOC_NGUARD; i++){
    static const int guard = 0xdead3344;
    memcpy(&z[i*sizeof(u32)], &guard, sizeof(u32));
  }

  /* Line number */
  z = &((char *)z)[TESTALLOC_NGUARD*sizeof(u32)];             /* Guard words */
  z = &zAlloc[TESTALLOC_OFFSET_LINENUMBER(p)];
  memcpy(z, &vtk_sqlite3_iLine, sizeof(u32));

  /* File name */
  z = &zAlloc[TESTALLOC_OFFSET_FILENAME(p)];
  strncpy(z, vtk_sqlite3_zFile, TESTALLOC_FILESIZE);
  z[TESTALLOC_FILESIZE - 1] = '\0';

  /* User string */
  z = &zAlloc[TESTALLOC_OFFSET_USER(p)];
  z[0] = 0;
  if( vtk_sqlite3_malloc_id ){
    strncpy(z, vtk_sqlite3_malloc_id, TESTALLOC_USERSIZE);
    z[TESTALLOC_USERSIZE-1] = 0;
  }

  /* backtrace() stack */
  z = &zAlloc[TESTALLOC_OFFSET_STACK(p)];
  backtrace((void **)z, TESTALLOC_STACKFRAMES);

  /* Sanity check to make sure checkGuards() is working */
  checkGuards(p);
}

/*
** The argument is a malloc()ed pointer as returned by the test-wrapper.
** Return a pointer to the Os level allocation.
*/
static void *getOsPointer(void *p)
{
  char *z = (char *)p;
  return (void *)(&z[-1 * TESTALLOC_OFFSET_DATA(p)]);
}


#if VTK_SQLITE_MEMDEBUG>1
/*
** The argument points to an Os level allocation. Link it into the threads list
** of allocations.
*/
static void linkAlloc(void *p){
  void **pp = (void **)p;
  pp[0] = 0;
  pp[1] = vtk_sqlite3_pFirst;
  if( vtk_sqlite3_pFirst ){
    ((void **)vtk_sqlite3_pFirst)[0] = p;
  }
  vtk_sqlite3_pFirst = p;
}

/*
** The argument points to an Os level allocation. Unlinke it from the threads
** list of allocations.
*/
static void unlinkAlloc(void *p)
{
  void **pp = (void **)p;
  if( p==vtk_sqlite3_pFirst ){
    assert(!pp[0]);
    assert(!pp[1] || ((void **)(pp[1]))[0]==p);
    vtk_sqlite3_pFirst = pp[1];
    if( vtk_sqlite3_pFirst ){
      ((void **)vtk_sqlite3_pFirst)[0] = 0;
    }
  }else{
    void **pprev = pp[0];
    void **pnext = pp[1];
    assert(pprev);
    assert(pprev[1]==p);
    pprev[1] = (void *)pnext;
    if( pnext ){
      assert(pnext[0]==p);
      pnext[0] = (void *)pprev;
    }
  }
}

/*
** Pointer p is a pointer to an OS level allocation that has just been
** realloc()ed. Set the list pointers that point to this entry to it's new
** location.
*/
static void relinkAlloc(void *p)
{
  void **pp = (void **)p;
  if( pp[0] ){
    ((void **)(pp[0]))[1] = p;
  }else{
    vtk_sqlite3_pFirst = p;
  }
  if( pp[1] ){
    ((void **)(pp[1]))[0] = p;
  }
}
#else
#define linkAlloc(x)
#define relinkAlloc(x)
#define unlinkAlloc(x)
#endif

/*
** This function sets the result of the Tcl interpreter passed as an argument
** to a list containing an entry for each currently outstanding call made to 
** vtk_sqliteMalloc and friends by the current thread. Each list entry is itself a
** list, consisting of the following (in order):
**
**     * The number of bytes allocated
**     * The __FILE__ macro at the time of the vtk_sqliteMalloc() call.
**     * The __LINE__ macro ...
**     * The value of the vtk_sqlite3_malloc_id variable ...
**     * The output of backtrace() (if available) ...
**
** Todo: We could have a version of this function that outputs to stdout, 
** to debug memory leaks when Tcl is not available.
*/
#if defined(TCLSH) && defined(VTK_SQLITE_DEBUG) && VTK_SQLITE_MEMDEBUG>1
VTK_SQLITE_PRIVATE int vtk_sqlite3OutstandingMallocs(Tcl_Interp *interp){
  void *p;
  Tcl_Obj *pRes = Tcl_NewObj();
  Tcl_IncrRefCount(pRes);


  for(p=vtk_sqlite3_pFirst; p; p=((void **)p)[1]){
    Tcl_Obj *pEntry = Tcl_NewObj();
    Tcl_Obj *pStack = Tcl_NewObj();
    char *z;
    u32 iLine;
    int nBytes = vtk_sqlite3OsAllocationSize(p) - TESTALLOC_OVERHEAD;
    char *zAlloc = (char *)p;
    int i;

    Tcl_ListObjAppendElement(0, pEntry, Tcl_NewIntObj(nBytes));

    z = &zAlloc[TESTALLOC_OFFSET_FILENAME(p)];
    Tcl_ListObjAppendElement(0, pEntry, Tcl_NewStringObj(z, -1));

    z = &zAlloc[TESTALLOC_OFFSET_LINENUMBER(p)];
    memcpy(&iLine, z, sizeof(u32));
    Tcl_ListObjAppendElement(0, pEntry, Tcl_NewIntObj(iLine));

    z = &zAlloc[TESTALLOC_OFFSET_USER(p)];
    Tcl_ListObjAppendElement(0, pEntry, Tcl_NewStringObj(z, -1));

    z = &zAlloc[TESTALLOC_OFFSET_STACK(p)];
    for(i=0; i<TESTALLOC_STACKFRAMES; i++){
      char zHex[128];
      vtk_sqlite3_snprintf(sizeof(zHex), zHex, "%p", ((void **)z)[i]);
      Tcl_ListObjAppendElement(0, pStack, Tcl_NewStringObj(zHex, -1));
    }

    Tcl_ListObjAppendElement(0, pEntry, pStack);
    Tcl_ListObjAppendElement(0, pRes, pEntry);
  }

  Tcl_ResetResult(interp);
  Tcl_SetObjResult(interp, pRes);
  Tcl_DecrRefCount(pRes);
  return TCL_OK;
}
#endif

/*
** This is the test layer's wrapper around vtk_sqlite3OsMalloc().
*/
static void * OSMALLOC(int n){
  vtk_sqlite3OsEnterMutex();
#ifdef VTK_SQLITE_ENABLE_MEMORY_MANAGEMENT
  vtk_sqlite3_nMaxAlloc = 
      MAX(vtk_sqlite3_nMaxAlloc, vtk_sqlite3ThreadDataReadOnly()->nAlloc);
#endif
  assert( !vtk_sqlite3_mallocDisallowed );
  if( !vtk_sqlite3TestMallocFail() ){
    u32 *p;
    p = (u32 *)vtk_sqlite3OsMalloc(n + TESTALLOC_OVERHEAD);
    assert(p);
    vtk_sqlite3_nMalloc++;
    applyGuards(p);
    linkAlloc(p);
    vtk_sqlite3OsLeaveMutex();
    return (void *)(&p[TESTALLOC_NGUARD + 2*sizeof(void *)/sizeof(u32)]);
  }
  vtk_sqlite3OsLeaveMutex();
  return 0;
}

static int OSSIZEOF(void *p){
  if( p ){
    u32 *pOs = (u32 *)getOsPointer(p);
    return vtk_sqlite3OsAllocationSize(pOs) - TESTALLOC_OVERHEAD;
  }
  return 0;
}

/*
** This is the test layer's wrapper around vtk_sqlite3OsFree(). The argument is a
** pointer to the space allocated for the application to use.
*/
static void OSFREE(void *pFree){
  u32 *p;         /* Pointer to the OS-layer allocation */
  vtk_sqlite3OsEnterMutex();
  p = (u32 *)getOsPointer(pFree);
  checkGuards(p);
  unlinkAlloc(p);
  memset(pFree, 0x55, OSSIZEOF(pFree));
  vtk_sqlite3OsFree(p);
  vtk_sqlite3_nFree++;
  vtk_sqlite3OsLeaveMutex();
}

/*
** This is the test layer's wrapper around vtk_sqlite3OsRealloc().
*/
static void * OSREALLOC(void *pRealloc, int n){
#ifdef VTK_SQLITE_ENABLE_MEMORY_MANAGEMENT
  vtk_sqlite3_nMaxAlloc = 
      MAX(vtk_sqlite3_nMaxAlloc, vtk_sqlite3ThreadDataReadOnly()->nAlloc);
#endif
  assert( !vtk_sqlite3_mallocDisallowed );
  if( !vtk_sqlite3TestMallocFail() ){
    u32 *p = (u32 *)getOsPointer(pRealloc);
    checkGuards(p);
    p = vtk_sqlite3OsRealloc(p, n + TESTALLOC_OVERHEAD);
    applyGuards(p);
    relinkAlloc(p);
    return (void *)(&p[TESTALLOC_NGUARD + 2*sizeof(void *)/sizeof(u32)]);
  }
  return 0;
}

static void OSMALLOC_FAILED(){
  vtk_sqlite3_isFail = 0;
}

#else
/* Define macros to call the vtk_sqlite3OsXXX interface directly if 
** the VTK_SQLITE_MEMDEBUG macro is not defined.
*/
#define OSMALLOC(x)        vtk_sqlite3OsMalloc(x)
#define OSREALLOC(x,y)     vtk_sqlite3OsRealloc(x,y)
#define OSFREE(x)          vtk_sqlite3OsFree(x)
#define OSSIZEOF(x)        vtk_sqlite3OsAllocationSize(x)
#define OSMALLOC_FAILED()

#endif  /* VTK_SQLITE_MEMDEBUG */
/*
** End code for memory allocation system test layer.
**--------------------------------------------------------------------------*/

/*
** This routine is called when we are about to allocate n additional bytes
** of memory.  If the new allocation will put is over the soft allocation
** limit, then invoke vtk_sqlite3_release_memory() to try to release some
** memory before continuing with the allocation.
**
** This routine also makes sure that the thread-specific-data (TSD) has
** be allocated.  If it has not and can not be allocated, then return
** false.  The updateMemoryUsedCount() routine below will deallocate
** the TSD if it ought to be.
**
** If VTK_SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined, this routine is
** a no-op
*/ 
#ifdef VTK_SQLITE_ENABLE_MEMORY_MANAGEMENT
static int enforceSoftLimit(int n){
  ThreadData *pTsd = vtk_sqlite3ThreadData();
  if( pTsd==0 ){
    return 0;
  }
  assert( pTsd->nAlloc>=0 );
  if( n>0 && pTsd->nSoftHeapLimit>0 ){
    while( pTsd->nAlloc+n>pTsd->nSoftHeapLimit && vtk_sqlite3_release_memory(n) ){}
  }
  return 1;
}
#else
# define enforceSoftLimit(X)  1
#endif

/*
** Update the count of total outstanding memory that is held in
** thread-specific-data (TSD).  If after this update the TSD is
** no longer being used, then deallocate it.
**
** If VTK_SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined, this routine is
** a no-op
*/
#ifdef VTK_SQLITE_ENABLE_MEMORY_MANAGEMENT
static void updateMemoryUsedCount(int n){
  ThreadData *pTsd = vtk_sqlite3ThreadData();
  if( pTsd ){
    pTsd->nAlloc += n;
    assert( pTsd->nAlloc>=0 );
    if( pTsd->nAlloc==0 && pTsd->nSoftHeapLimit==0 ){
      vtk_sqlite3ReleaseThreadData();
    }
  }
}
#else
#define updateMemoryUsedCount(x)  /* no-op */
#endif

/*
** Allocate and return N bytes of uninitialised memory by calling
** vtk_sqlite3OsMalloc(). If the Malloc() call fails, attempt to free memory 
** by calling vtk_sqlite3_release_memory().
*/
VTK_SQLITE_PRIVATE void *vtk_sqlite3MallocRaw(int n, int doMemManage){
  void *p = 0;
  if( n>0 && !vtk_sqlite3MallocFailed() && (!doMemManage || enforceSoftLimit(n)) ){
    while( (p = OSMALLOC(n))==0 && vtk_sqlite3_release_memory(n) ){}
    if( !p ){
      vtk_sqlite3FailedMalloc();
      OSMALLOC_FAILED();
    }else if( doMemManage ){
      updateMemoryUsedCount(OSSIZEOF(p));
    }
  }
  return p;
}

/*
** Resize the allocation at p to n bytes by calling vtk_sqlite3OsRealloc(). The
** pointer to the new allocation is returned.  If the Realloc() call fails,
** attempt to free memory by calling vtk_sqlite3_release_memory().
*/
VTK_SQLITE_PRIVATE void *vtk_sqlite3Realloc(void *p, int n){
  if( vtk_sqlite3MallocFailed() ){
    return 0;
  }

  if( !p ){
    return vtk_sqlite3Malloc(n, 1);
  }else{
    void *np = 0;
#ifdef VTK_SQLITE_ENABLE_MEMORY_MANAGEMENT
    int origSize = OSSIZEOF(p);
#endif
    if( enforceSoftLimit(n - origSize) ){
      while( (np = OSREALLOC(p, n))==0 && vtk_sqlite3_release_memory(n) ){}
      if( !np ){
        vtk_sqlite3FailedMalloc();
        OSMALLOC_FAILED();
      }else{
        updateMemoryUsedCount(OSSIZEOF(np) - origSize);
      }
    }
    return np;
  }
}

/*
** Free the memory pointed to by p. p must be either a NULL pointer or a 
** value returned by a previous call to vtk_sqlite3Malloc() or vtk_sqlite3Realloc().
*/
VTK_SQLITE_PRIVATE void vtk_sqlite3FreeX(void *p){
  if( p ){
    updateMemoryUsedCount(0 - OSSIZEOF(p));
    OSFREE(p);
  }
}

/*
** A version of vtk_sqliteMalloc() that is always a function, not a macro.
** Currently, this is used only to alloc to allocate the parser engine.
*/
VTK_SQLITE_PRIVATE void *vtk_sqlite3MallocX(int n){
  return vtk_sqliteMalloc(n);
}

/*
** vtk_sqlite3Malloc
** vtk_sqlite3ReallocOrFree
**
** These two are implemented as wrappers around vtk_sqlite3MallocRaw(), 
** vtk_sqlite3Realloc() and vtk_sqlite3Free().
*/ 
VTK_SQLITE_PRIVATE void *vtk_sqlite3Malloc(int n, int doMemManage){
  void *p = vtk_sqlite3MallocRaw(n, doMemManage);
  if( p ){
    memset(p, 0, n);
  }
  return p;
}
VTK_SQLITE_PRIVATE void *vtk_sqlite3ReallocOrFree(void *p, int n){
  void *pNew;
  pNew = vtk_sqlite3Realloc(p, n);
  if( !pNew ){
    vtk_sqlite3FreeX(p);
  }
  return pNew;
}

/*
** vtk_sqlite3ThreadSafeMalloc() and vtk_sqlite3ThreadSafeFree() are used in those
** rare scenarios where vtk_sqlite may allocate memory in one thread and free
** it in another. They are exactly the same as vtk_sqlite3Malloc() and 
** vtk_sqlite3Free() except that:
**
**   * The allocated memory is not included in any calculations with 
**     respect to the soft-heap-limit, and
**
**   * vtk_sqlite3ThreadSafeMalloc() must be matched with ThreadSafeFree(),
**     not vtk_sqlite3Free(). Calling vtk_sqlite3Free() on memory obtained from
**     ThreadSafeMalloc() will cause an error somewhere down the line.
*/
#ifdef VTK_SQLITE_ENABLE_MEMORY_MANAGEMENT
VTK_SQLITE_PRIVATE void *vtk_sqlite3ThreadSafeMalloc(int n){
  (void)ENTER_MALLOC;
  return vtk_sqlite3Malloc(n, 0);
}
VTK_SQLITE_PRIVATE void vtk_sqlite3ThreadSafeFree(void *p){
  (void)ENTER_MALLOC;
  if( p ){
    OSFREE(p);
  }
}
#endif


/*
** Return the number of bytes allocated at location p. p must be either 
** a NULL pointer (in which case 0 is returned) or a pointer returned by 
** vtk_sqlite3Malloc(), vtk_sqlite3Realloc() or vtk_sqlite3ReallocOrFree().
**
** The number of bytes allocated does not include any overhead inserted by 
** any malloc() wrapper functions that may be called. So the value returned
** is the number of bytes that were available to Vtk_Sqlite using pointer p, 
** regardless of how much memory was actually allocated.
*/
#ifdef VTK_SQLITE_ENABLE_MEMORY_MANAGEMENT
VTK_SQLITE_PRIVATE int vtk_sqlite3AllocSize(void *p){
  return OSSIZEOF(p);
}
#endif

/*
** Make a copy of a string in memory obtained from vtk_sqliteMalloc(). These 
** functions call vtk_sqlite3MallocRaw() directly instead of vtk_sqliteMalloc(). This
** is because when memory debugging is turned on, these two functions are 
** called via macros that record the current file and line number in the
** ThreadData structure.
*/
VTK_SQLITE_PRIVATE char *vtk_sqlite3StrDup(const char *z){
  char *zNew;
  int n;
  if( z==0 ) return 0;
  n = strlen(z)+1;
  zNew = vtk_sqlite3MallocRaw(n, 1);
  if( zNew ) memcpy(zNew, z, n);
  return zNew;
}
VTK_SQLITE_PRIVATE char *vtk_sqlite3StrNDup(const char *z, int n){
  char *zNew;
  if( z==0 ) return 0;
  zNew = vtk_sqlite3MallocRaw(n+1, 1);
  if( zNew ){
    memcpy(zNew, z, n);
    zNew[n] = 0;
  }
  return zNew;
}

/*
** Create a string from the 2nd and subsequent arguments (up to the
** first NULL argument), store the string in memory obtained from
** vtk_sqliteMalloc() and make the pointer indicated by the 1st argument
** point to that string.  The 1st argument must either be NULL or 
** point to memory obtained from vtk_sqliteMalloc().
*/
VTK_SQLITE_PRIVATE void vtk_sqlite3SetString(char **pz, ...){
  va_list ap;
  int nByte;
  const char *z;
  char *zResult;

  assert( pz!=0 );
  nByte = 1;
  va_start(ap, pz);
  while( (z = va_arg(ap, const char*))!=0 ){
    nByte += strlen(z);
  }
  va_end(ap);
  vtk_sqliteFree(*pz);
  *pz = zResult = vtk_sqliteMallocRaw( nByte );
  if( zResult==0 ){
    return;
  }
  *zResult = 0;
  va_start(ap, pz);
  while( (z = va_arg(ap, const char*))!=0 ){
    int n = strlen(z);
    memcpy(zResult, z, n);
    zResult += n;
  }
  zResult[0] = 0;
  va_end(ap);
}


/*
** This function must be called before exiting any API function (i.e. 
** returning control to the user) that has called vtk_sqlite3Malloc or
** vtk_sqlite3Realloc.
**
** The returned value is normally a copy of the second argument to this
** function. However, if a malloc() failure has occured since the previous
** invocation VTK_SQLITE_NOMEM is returned instead. 
**
** If the first argument, db, is not NULL and a malloc() error has occured,
** then the connection error-code (the value returned by vtk_sqlite3_errcode())
** is set to VTK_SQLITE_NOMEM.
*/
int vtk_sqlite3_mallocHasFailed = 0;
VTK_SQLITE_PRIVATE int vtk_sqlite3ApiExit(vtk_sqlite3* db, int rc){
  if( vtk_sqlite3MallocFailed() ){
    vtk_sqlite3_mallocHasFailed = 0;
    vtk_sqlite3OsLeaveMutex();
    vtk_sqlite3Error(db, VTK_SQLITE_NOMEM, 0);
    rc = VTK_SQLITE_NOMEM;
  }
  return rc & (db ? db->errMask : 0xff);
}

/* 
** Set the "malloc has failed" condition to true for this thread.
*/
VTK_SQLITE_PRIVATE void vtk_sqlite3FailedMalloc(){
  if( !vtk_sqlite3MallocFailed() ){
    vtk_sqlite3OsEnterMutex();
    assert( vtk_sqlite3_mallocHasFailed==0 );
    vtk_sqlite3_mallocHasFailed = 1;
  }
}

#ifdef VTK_SQLITE_MEMDEBUG
/*
** This function sets a flag in the thread-specific-data structure that will
** cause an assert to fail if vtk_sqliteMalloc() or vtk_sqliteRealloc() is called.
*/
VTK_SQLITE_PRIVATE void vtk_sqlite3MallocDisallow(){
  assert( vtk_sqlite3_mallocDisallowed>=0 );
  vtk_sqlite3_mallocDisallowed++;
}

/*
** This function clears the flag set in the thread-specific-data structure set
** by vtk_sqlite3MallocDisallow().
*/
VTK_SQLITE_PRIVATE void vtk_sqlite3MallocAllow(){
  assert( vtk_sqlite3_mallocDisallowed>0 );
  vtk_sqlite3_mallocDisallowed--;
}
#endif

/************** End of malloc.c **********************************************/
/************** Begin file printf.c ******************************************/
/*
** The "printf" code that follows dates from the 1980's.  It is in
** the public domain.  The original comments are included here for
** completeness.  They are very out-of-date but might be useful as
** an historical reference.  Most of the "enhancements" have been backed
** out so that the functionality is now the same as standard printf().
**
**************************************************************************
**
** The following modules is an enhanced replacement for the "printf" subroutines
** found in the standard C library.  The following enhancements are
** supported:
**
**      +  Additional functions.  The standard set of "printf" functions
**         includes printf, fprintf, sprintf, vprintf, vfprintf, and
**         vsprintf.  This module adds the following:
**
**           *  snprintf -- Works like sprintf, but has an extra argument
**                          which is the size of the buffer written to.
**
**           *  mprintf --  Similar to sprintf.  Writes output to memory
**                          obtained from malloc.
**
**           *  xprintf --  Calls a function to dispose of output.
**
**           *  nprintf --  No output, but returns the number of characters
**                          that would have been output by printf.
**
**           *  A v- version (ex: vsnprintf) of every function is also
**              supplied.
**
**      +  A few extensions to the formatting notation are supported:
**
**           *  The "=" flag (similar to "-") causes the output to be
**              be centered in the appropriately sized field.
**
**           *  The %b field outputs an integer in binary notation.
**
**           *  The %c field now accepts a precision.  The character output
**              is repeated by the number of times the precision specifies.
**
**           *  The %' field works like %c, but takes as its character the
**              next character of the format string, instead of the next
**              argument.  For example,  printf("%.78'-")  prints 78 minus
**              signs, the same as  printf("%.78c",'-').
**
**      +  When compiled using GCC on a SPARC, this version of printf is
**         faster than the library printf for SUN OS 4.1.
**
**      +  All functions are fully reentrant.
**
*/
#include <math.h>

/*
** Conversion types fall into various categories as defined by the
** following enumeration.
*/
#define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
#define etFLOAT       2 /* Floating point.  %f */
#define etEXP         3 /* Exponentional notation. %e and %E */
#define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
#define etSIZE        5 /* Return number of characters processed so far. %n */
#define etSTRING      6 /* Strings. %s */
#define etDYNSTRING   7 /* Dynamically allocated strings. %z */
#define etPERCENT     8 /* Percent symbol. %% */
#define etCHARX       9 /* Characters. %c */
/* The rest are extensions, not normally found in printf() */
#define etCHARLIT    10 /* Literal characters.  %' */
#define etSQLESCAPE  11 /* Strings with '\'' doubled.  %q */
#define etSQLESCAPE2 12 /* Strings with '\'' doubled and enclosed in '',
                          NULL pointers replaced by SQL NULL.  %Q */
#define etTOKEN      13 /* a pointer to a Token structure */
#define etSRCLIST    14 /* a pointer to a SrcList */
#define etPOINTER    15 /* The %p conversion */
#define etSQLESCAPE3 16 /* %w -> Strings with '\"' doubled */


/*
** An "etByte" is an 8-bit unsigned value.
*/
typedef unsigned char etByte;

/*
** Each builtin conversion character (ex: the 'd' in "%d") is described
** by an instance of the following structure
*/
typedef struct et_info {   /* Information about each format field */
  char fmttype;            /* The format field code letter */
  etByte base;             /* The base for radix conversion */
  etByte flags;            /* One or more of FLAG_ constants below */
  etByte type;             /* Conversion paradigm */
  etByte charset;          /* Offset into aDigits[] of the digits string */
  etByte prefix;           /* Offset into aPrefix[] of the prefix string */
} et_info;

/*
** Allowed values for et_info.flags
*/
#define FLAG_SIGNED  1     /* True if the value to convert is signed */
#define FLAG_INTERN  2     /* True if for internal use only */
#define FLAG_STRING  4     /* Allow infinity precision */


/*
** The following table is searched linearly, so it is good to put the
** most frequently used conversion types first.
*/
static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
static const char aPrefix[] = "-x0\000X0";
static const et_info fmtinfo[] = {
  {  'd', 10, 1, etRADIX,      0,  0 },
  {  's',  0, 4, etSTRING,     0,  0 },
  {  'g',  0, 1, etGENERIC,    30, 0 },
  {  'z',  0, 6, etDYNSTRING,  0,  0 },
  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
  {  'c',  0, 0, etCHARX,      0,  0 },
  {  'o',  8, 0, etRADIX,      0,  2 },
  {  'u', 10, 0, etRADIX,      0,  0 },
  {  'x', 16, 0, etRADIX,      16, 1 },
  {  'X', 16, 0, etRADIX,      0,  4 },
#ifndef VTK_SQLITE_OMIT_FLOATING_POINT
  {  'f',  0, 1, etFLOAT,      0,  0 },
  {  'e',  0, 1, etEXP,        30, 0 },
  {  'E',  0, 1, etEXP,        14, 0 },
  {  'G',  0, 1, etGENERIC,    14, 0 },
#endif
  {  'i', 10, 1, etRADIX,      0,  0 },
  {  'n',  0, 0, etSIZE,       0,  0 },
  {  '%',  0, 0, etPERCENT,    0,  0 },
  {  'p', 16, 0, etPOINTER,    0,  1 },
  {  'T',  0, 2, etTOKEN,      0,  0 },
  {  'S',  0, 2, etSRCLIST,    0,  0 },
};
#define etNINFO  (sizeof(fmtinfo)/sizeof(fmtinfo[0]))

/*
** If VTK_SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
** conversions will work.
*/
#ifndef VTK_SQLITE_OMIT_FLOATING_POINT
/*
** "*val" is a double such that 0.1 <= *val < 10.0
** Return the ascii code for the leading digit of *val, then
** multiply "*val" by 10.0 to renormalize.
**
** Example:
**     input:     *val = 3.14159
**     output:    *val = 1.4159    function return = '3'
**
** The counter *cnt is incremented each time.  After counter exceeds
** 16 (the number of significant digits in a 64-bit float) '0' is
** always returned.
*/
static int et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  int digit;
  LONGDOUBLE_TYPE d;
  if( (*cnt)++ >= 16 ) return '0';
  digit = (int)*val;
  d = digit;
  digit += '0';
  *val = (*val - d)*10.0;
  return digit;
}
#endif /* VTK_SQLITE_OMIT_FLOATING_POINT */

/*
** On machines with a small stack size, you can redefine the
** VTK_SQLITE_PRINT_BUF_SIZE to be less than 350.  But beware - for
** smaller values some %f conversions may go into an infinite loop.
*/
#ifndef VTK_SQLITE_PRINT_BUF_SIZE
# define VTK_SQLITE_PRINT_BUF_SIZE 350
#endif
#define etBUFSIZE VTK_SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */

/*
** The root program.  All variations call this core.
**
** INPUTS:
**   func   This is a pointer to a function taking three arguments
**            1. A pointer to anything.  Same as the "arg" parameter.
**            2. A pointer to the list of characters to be output
**               (Note, this list is NOT null terminated.)
**            3. An integer number of characters to be output.
**               (Note: This number might be zero.)
**
**   arg    This is the pointer to anything which will be passed as the
**          first argument to "func".  Use it for whatever you like.
**
**   fmt    This is the format string, as in the usual print.
**
**   ap     This is a pointer to a list of arguments.  Same as in
**          vfprint.
**
** OUTPUTS:
**          The return value is the total number of characters sent to
**          the function "func".  Returns -1 on a error.
**
** Note that the order in which automatic variables are declared below
** seems to make a big difference in determining how fast this beast
** will run.
*/
static int vxprintf(
  void (*func)(void*,const char*,int),     /* Consumer of text */
  void *arg,                         /* First argument to the consumer */
  int useExtended,                   /* Allow extended %-conversions */
  const char *fmt,                   /* Format string */
  va_list ap                         /* arguments */
){
  int c;                     /* Next character in the format string */
  char *bufpt;               /* Pointer to the conversion buffer */
  int precision;             /* Precision of the current field */
  int length;                /* Length of the field */
  int idx;                   /* A general purpose loop counter */
  int count;                 /* Total number of characters output */
  int width;                 /* Width of the current field */
  etByte flag_leftjustify;   /* True if "-" flag is present */
  etByte flag_plussign;      /* True if "+" flag is present */
  etByte flag_blanksign;     /* True if " " flag is present */
  etByte flag_alternateform; /* True if "#" flag is present */
  etByte flag_altform2;      /* True if "!" flag is present */
  etByte flag_zeropad;       /* True if field width constant starts with zero */
  etByte flag_long;          /* True if "l" flag is present */
  etByte flag_longlong;      /* True if the "ll" flag is present */
  etByte done;               /* Loop termination flag */
  vtk_sqlite_uint64 longvalue;   /* Value for integer types */
  LONGDOUBLE_TYPE realvalue; /* Value for real types */
  const et_info *infop;      /* Pointer to the appropriate info structure */
  char buf[etBUFSIZE];       /* Conversion buffer */
  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
  etByte errorflag = 0;      /* True if an error is encountered */
  etByte xtype = 0;          /* Conversion paradigm */
  char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
  static const char spaces[] =
   "                                                                         ";
#define etSPACESIZE (sizeof(spaces)-1)
#ifndef VTK_SQLITE_OMIT_FLOATING_POINT
  int  exp, e2;              /* exponent of real numbers */
  double rounder;            /* Used for rounding floating point values */
  etByte flag_dp;            /* True if decimal point should be shown */
  etByte flag_rtz;           /* True if trailing zeros should be removed */
  etByte flag_exp;           /* True to force display of the exponent */
  int nsd;                   /* Number of significant digits returned */
#endif

  func(arg,"",0);
  count = length = 0;
  bufpt = 0;
  for(; (c=(*fmt))!=0; ++fmt){
    if( c!='%' ){
      int amt;
      bufpt = (char *)fmt;
      amt = 1;
      while( (c=(*++fmt))!='%' && c!=0 ) amt++;
      (*func)(arg,bufpt,amt);
      count += amt;
      if( c==0 ) break;
    }
    if( (c=(*++fmt))==0 ){
      errorflag = 1;
      (*func)(arg,"%",1);
      count++;
      break;
    }
    /* Find out what flags are present */
    flag_leftjustify = flag_plussign = flag_blanksign = 
     flag_alternateform = flag_altform2 = flag_zeropad = 0;
    done = 0;
    do{
      switch( c ){
        case '-':   flag_leftjustify = 1;     break;
        case '+':   flag_plussign = 1;        break;
        case ' ':   flag_blanksign = 1;       break;
        case '#':   flag_alternateform = 1;   break;
        case '!':   flag_altform2 = 1;        break;
        case '0':   flag_zeropad = 1;         break;
        default:    done = 1;                 break;
      }
    }while( !done && (c=(*++fmt))!=0 );
    /* Get the field width */
    width = 0;
    if( c=='*' ){
      width = va_arg(ap,int);
      if( width<0 ){
        flag_leftjustify = 1;
        width = -width;
      }
      c = *++fmt;
    }else{
      while( c>='0' && c<='9' ){
        width = width*10 + c - '0';
        c = *++fmt;
      }
    }
    if( width > etBUFSIZE-10 ){
      width = etBUFSIZE-10;
    }
    /* Get the precision */
    if( c=='.' ){
      precision = 0;
      c = *++fmt;
      if( c=='*' ){
        precision = va_arg(ap,int);
        if( precision<0 ) precision = -precision;
        c = *++fmt;
      }else{
        while( c>='0' && c<='9' ){
          precision = precision*10 + c - '0';
          c = *++fmt;
        }
      }
    }else{
      precision = -1;
    }
    /* Get the conversion type modifier */
    if( c=='l' ){
      flag_long = 1;
      c = *++fmt;
      if( c=='l' ){
        flag_longlong = 1;
        c = *++fmt;
      }else{
        flag_longlong = 0;
      }
    }else{
      flag_long = flag_longlong = 0;
    }
    /* Fetch the info entry for the field */
    infop = 0;
    for(idx=0; idx<(int)etNINFO; idx++){
      if( c==fmtinfo[idx].fmttype ){
        infop = &fmtinfo[idx];
        if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
          xtype = infop->type;
        }else{
          return -1;
        }
        break;
      }
    }
    zExtra = 0;
    if( infop==0 ){
      return -1;
    }


    /* Limit the precision to prevent overflowing buf[] during conversion */
    if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
      precision = etBUFSIZE-40;
    }

    /*
    ** At this point, variables are initialized as follows:
    **
    **   flag_alternateform          TRUE if a '#' is present.
    **   flag_altform2               TRUE if a '!' is present.
    **   flag_plussign               TRUE if a '+' is present.
    **   flag_leftjustify            TRUE if a '-' is present or if the
    **                               field width was negative.
    **   flag_zeropad                TRUE if the width began with 0.
    **   flag_long                   TRUE if the letter 'l' (ell) prefixed
    **                               the conversion character.
    **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
    **                               the conversion character.
    **   flag_blanksign              TRUE if a ' ' is present.
    **   width                       The specified field width.  This is
    **                               always non-negative.  Zero is the default.
    **   precision                   The specified precision.  The default
    **                               is -1.
    **   xtype                       The class of the conversion.
    **   infop                       Pointer to the appropriate info struct.
    */
    switch( xtype ){
      case etPOINTER:
        flag_longlong = sizeof(char*)==sizeof(i64);
        flag_long = sizeof(char*)==sizeof(long int);
        /* Fall through into the next case */
      case etRADIX:
        if( infop->flags & FLAG_SIGNED ){
          i64 v;
          if( flag_longlong )   v = va_arg(ap,i64);
          else if( flag_long )  v = va_arg(ap,long int);
          else                  v = va_arg(ap,int);
          if( v<0 ){
            longvalue = -v;
            prefix = '-';
          }else{
            longvalue = v;
            if( flag_plussign )        prefix = '+';
            else if( flag_blanksign )  prefix = ' ';
            else                       prefix = 0;
          }
        }else{
          if( flag_longlong )   longvalue = va_arg(ap,u64);
          else if( flag_long )  longvalue = va_arg(ap,unsigned long int);
          else                  longvalue = va_arg(ap,unsigned int);
          prefix = 0;
        }
        if( longvalue==0 ) flag_alternateform = 0;
        if( flag_zeropad && precision<width-(prefix!=0) ){
          precision = width-(prefix!=0);
        }
        bufpt = &buf[etBUFSIZE-1];
        {
          register const char *cset;      /* Use registers for speed */
          register int base;
          cset = &aDigits[infop->charset];
          base = infop->base;
          do{                                           /* Convert to ascii */
            *(--bufpt) = cset[(int)(longvalue%base)];
            longvalue = longvalue/base;
          }while( longvalue>0 );
        }
        length = &buf[etBUFSIZE-1]-bufpt;
        for(idx=precision-length; idx>0; idx--){
          *(--bufpt) = '0';                             /* Zero pad */
        }
        if( prefix ) *(--bufpt) = prefix;               /* Add sign */
        if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
          const char *pre;
          char x;
          pre = &aPrefix[infop->prefix];
          if( *bufpt!=pre[0] ){
            for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
          }
        }
        length = &buf[etBUFSIZE-1]-bufpt;
        break;
      case etFLOAT:
      case etEXP:
      case etGENERIC:
        realvalue = va_arg(ap,double);
#ifndef VTK_SQLITE_OMIT_FLOATING_POINT
        if( precision<0 ) precision = 6;         /* Set default precision */
        if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
        if( realvalue<0.0 ){
          realvalue = -realvalue;
          prefix = '-';
        }else{
          if( flag_plussign )          prefix = '+';
          else if( flag_blanksign )    prefix = ' ';
          else                         prefix = 0;
        }
        if( xtype==etGENERIC && precision>0 ) precision--;
#if 0
        /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
        for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
#else
        /* It makes more sense to use 0.5 */
        for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
#endif
        if( xtype==etFLOAT ) realvalue += rounder;
        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
        exp = 0;
        if( vtk_sqlite3_isnan(realvalue) ){
          bufpt = "NaN";
          length = 3;
          break;
        }
        if( realvalue>0.0 ){
          while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
          while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
          while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
          while( realvalue<1e-8 && exp>=-350 ){ realvalue *= 1e8; exp-=8; }
          while( realvalue<1.0 && exp>=-350 ){ realvalue *= 10.0; exp--; }
          if( exp>350 || exp<-350 ){
            if( prefix=='-' ){
              bufpt = "-Inf";
            }else if( prefix=='+' ){
              bufpt = "+Inf";
            }else{
              bufpt = "Inf";
            }
            length = strlen(bufpt);
            break;
          }
        }
        bufpt = buf;
        /*
        ** If the field type is etGENERIC, then convert to either etEXP
        ** or etFLOAT, as appropriate.
        */
        flag_exp = xtype==etEXP;
        if( xtype!=etFLOAT ){
          realvalue += rounder;
          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
        }
        if( xtype==etGENERIC ){
          flag_rtz = !flag_alternateform;
          if( exp<-4 || exp>precision ){
            xtype = etEXP;
          }else{
            precision = precision - exp;
            xtype = etFLOAT;
          }
        }else{
          flag_rtz = 0;
        }
        if( xtype==etEXP ){
          e2 = 0;
        }else{
          e2 = exp;
        }
        nsd = 0;
        flag_dp = (etByte)((precision>0) | flag_alternateform | flag_altform2);
        /* The sign in front of the number */
        if( prefix ){
          *(bufpt++) = prefix;
        }
        /* Digits prior to the decimal point */
        if( e2<0 ){
          *(bufpt++) = '0';
        }else{
          for(; e2>=0; e2--){
            *(bufpt++) = (char)(et_getdigit(&realvalue,&nsd));
          }
        }
        /* The decimal point */
        if( flag_dp ){
          *(bufpt++) = '.';
        }
        /* "0" digits after the decimal point but before the first
        ** significant digit of the number */
        for(e2++; e2<0 && precision>0; precision--, e2++){
          *(bufpt++) = '0';
        }
        /* Significant digits after the decimal point */
        while( (precision--)>0 ){
          *(bufpt++) = (char)(et_getdigit(&realvalue,&nsd));
        }
        /* Remove trailing zeros and the "." if no digits follow the "." */
        if( flag_rtz && flag_dp ){
          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
          assert( bufpt>buf );
          if( bufpt[-1]=='.' ){
            if( flag_altform2 ){
              *(bufpt++) = '0';
            }else{
              *(--bufpt) = 0;
            }
          }
        }
        /* Add the "eNNN" suffix */
        if( flag_exp || (xtype==etEXP && exp) ){
          *(bufpt++) = aDigits[infop->charset];
          if( exp<0 ){
            *(bufpt++) = '-'; exp = -exp;
          }else{
            *(bufpt++) = '+';
          }
          if( exp>=100 ){
            *(bufpt++) = (char)((exp/100)+'0');                /* 100's digit */
            exp %= 100;
          }
          *(bufpt++) = (char)(exp/10+'0');                     /* 10's digit */
          *(bufpt++) = (char)(exp%10+'0');                     /* 1's digit */
        }
        *bufpt = 0;

        /* The converted number is in buf[] and zero terminated. Output it.
        ** Note that the number is in the usual order, not reversed as with
        ** integer conversions. */
        length = bufpt-buf;
        bufpt = buf;

        /* Special case:  Add leading zeros if the flag_zeropad flag is
        ** set and we are not left justified */
        if( flag_zeropad && !flag_leftjustify && length < width){
          int i;
          int nPad = width - length;
          for(i=width; i>=nPad; i--){
            bufpt[i] = bufpt[i-nPad];
          }
          i = prefix!=0;
          while( nPad-- ) bufpt[i++] = '0';
          length = width;
        }
#endif
        break;
      case etSIZE:
        *(va_arg(ap,int*)) = count;
        length = width = 0;
        break;
      case etPERCENT:
        buf[0] = '%';
        bufpt = buf;
        length = 1;
        break;
      case etCHARLIT:
      case etCHARX:
        c = buf[0] = (char)(xtype==etCHARX ? va_arg(ap,int) : *++fmt);
        if( precision>=0 ){
          for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
          length = precision;
        }else{
          length =1;
        }
        bufpt = buf;
        break;
      case etSTRING:
      case etDYNSTRING:
        bufpt = va_arg(ap,char*);
        if( bufpt==0 ){
          bufpt = "";
        }else if( xtype==etDYNSTRING ){
          zExtra = bufpt;
        }
        length = strlen(bufpt);
        if( precision>=0 && precision<length ) length = precision;
        break;
      case etSQLESCAPE:
      case etSQLESCAPE2:
      case etSQLESCAPE3: {
        int i, j, n, ch, isnull;
        int needQuote;
        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
        char *escarg = va_arg(ap,char*);
        isnull = escarg==0;
        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
        for(i=n=0; (ch=escarg[i])!=0; i++){
          if( ch==q )  n++;
        }
        needQuote = !isnull && xtype==etSQLESCAPE2;
        n += i + 1 + needQuote*2;
        if( n>etBUFSIZE ){
          bufpt = zExtra = vtk_sqliteMalloc( n );
          if( bufpt==0 ) return -1;
        }else{
          bufpt = buf;
        }
        j = 0;
        if( needQuote ) bufpt[j++] = q;
        for(i=0; (ch=escarg[i])!=0; i++){
          bufpt[j++] = (char)ch;
          if( ch==q ) bufpt[j++] = (char)ch;
        }
        if( needQuote ) bufpt[j++] = q;
        bufpt[j] = 0;
        length = j;
        /* The precision is ignored on %q and %Q */
        /* if( precision>=0 && precision<length ) length = precision; */
        break;
      }
      case etTOKEN: {
        Token *pToken = va_arg(ap, Token*);
        if( pToken && pToken->z ){
          (*func)(arg, (char*)pToken->z, pToken->n);
        }
        length = width = 0;
        break;
      }
      case etSRCLIST: {
        SrcList *pSrc = va_arg(ap, SrcList*);
        int k = va_arg(ap, int);
        struct SrcList_item *pItem = &pSrc->a[k];
        assert( k>=0 && k<pSrc->nSrc );
        if( pItem->zDatabase && pItem->zDatabase[0] ){
          (*func)(arg, pItem->zDatabase, strlen(pItem->zDatabase));
          (*func)(arg, ".", 1);
        }
        (*func)(arg, pItem->zName, strlen(pItem->zName));
        length = width = 0;
        break;
      }
    }/* End switch over the format type */
    /*
    ** The text of the conversion is pointed to by "bufpt" and is
    ** "length" characters long.  The field width is "width".  Do
    ** the output.
    */
    if( !flag_leftjustify ){
      register int nspace;
      nspace = width-length;
      if( nspace>0 ){
        count += nspace;
        while( nspace>=(int)etSPACESIZE ){
          (*func)(arg,spaces,etSPACESIZE);
          nspace -= etSPACESIZE;
        }
        if( nspace>0 ) (*func)(arg,spaces,nspace);
      }
    }
    if( length>0 ){
      (*func)(arg,bufpt,length);
      count += length;
    }
    if( flag_leftjustify ){
      register int nspace;
      nspace = width-length;
      if( nspace>0 ){
        count += nspace;
        while( nspace>=(int)etSPACESIZE ){
          (*func)(arg,spaces,etSPACESIZE);
          nspace -= etSPACESIZE;
        }
        if( nspace>0 ) (*func)(arg,spaces,nspace);
      }
    }
    if( zExtra ){
      vtk_sqliteFree(zExtra);
    }
  }/* End for loop over the format string */
  return errorflag ? -1 : count;
} /* End of function */


/* This structure is used to store state information about the
** write to memory that is currently in progress.
*/
struct sgMprintf {
  char *zBase;     /* A base allocation */
  char *zText;     /* The string collected so far */
  int  nChar;      /* Length of the string so far */
  int  nTotal;     /* Output size if unconstrained */
  int  nAlloc;     /* Amount of space allocated in zText */
  void *(*xRealloc)(void*,int);  /* Function used to realloc memory */
};

/* 
** This function implements the callback from vxprintf. 
**
** This routine add nNewChar characters of text in zNewText to
** the sgMprintf structure pointed to by "arg".
*/
static void mout(void *arg, const char *zNewText, int nNewChar){
  struct sgMprintf *pM = (struct sgMprintf*)arg;
  pM->nTotal += nNewChar;
  if( pM->nChar + nNewChar + 1 > pM->nAlloc ){
    if( pM->xRealloc==0 ){
      nNewChar =  pM->nAlloc - pM->nChar - 1;
    }else{
      int nAlloc = pM->nChar + nNewChar*2 + 1;
      if( pM->zText==pM->zBase ){
        pM->zText = pM->xRealloc(0, nAlloc);
        if( pM->zText && pM->nChar ){
          memcpy(pM->zText, pM->zBase, pM->nChar);
        }
      }else{
        char *zNew;
        zNew = pM->xRealloc(pM->zText, nAlloc);
        if( zNew ){
          pM->zText = zNew;
        }else{
          return;
        }
      }
      pM->nAlloc = nAlloc;
    }
  }
  if( pM->zText ){
    if( nNewChar>0 ){
      memcpy(&pM->zText[pM->nChar], zNewText, nNewChar);
      pM->nChar += nNewChar;
    }
    pM->zText[pM->nChar] = 0;
  }
}

/*
** This routine is a wrapper around xprintf() that invokes mout() as
** the consumer.  
*/
static char *base_vprintf(
  void *(*xRealloc)(void*,int),   /* Routine to realloc memory. May be NULL */
  int useInternal,                /* Use internal %-conversions if true */
  char *zInitBuf,                 /* Initially write here, before mallocing */
  int nInitBuf,                   /* Size of zInitBuf[] */
  const char *zFormat,            /* format string */
  va_list ap                      /* arguments */
){
  struct sgMprintf sM;
  sM.zBase = sM.zText = zInitBuf;
  sM.nChar = sM.nTotal = 0;
  sM.nAlloc = nInitBuf;
  sM.xRealloc = xRealloc;
  vxprintf(mout, &sM, useInternal, zFormat, ap);
  if( xRealloc ){
    if( sM.zText==sM.zBase ){
      sM.zText = xRealloc(0, sM.nChar+1);
      if( sM.zText ){
        memcpy(sM.zText, sM.zBase, sM.nChar+1);
      }
    }else if( sM.nAlloc>sM.nChar+10 ){
      char *zNew = xRealloc(sM.zText, sM.nChar+1);
      if( zNew ){
        sM.zText = zNew;
      }
    }
  }
  return sM.zText;
}

/*
** Realloc that is a real function, not a macro.
*/
static void *printf_realloc(void *old, int size){
  return vtk_sqliteRealloc(old,size);
}

/*
** Print into memory obtained from vtk_sqliteMalloc().  Use the internal
** %-conversion extensions.
*/
VTK_SQLITE_PRIVATE char *vtk_sqlite3VMPrintf(const char *zFormat, va_list ap){
  char zBase[VTK_SQLITE_PRINT_BUF_SIZE];
  return base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap);
}

/*
** Print into memory obtained from vtk_sqliteMalloc().  Use the internal
** %-conversion extensions.
*/
VTK_SQLITE_PRIVATE char *vtk_sqlite3MPrintf(const char *zFormat, ...){
  va_list ap;
  char *z;
  char zBase[VTK_SQLITE_PRINT_BUF_SIZE];
  va_start(ap, zFormat);
  z = base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap);
  va_end(ap);
  return z;
}

/*
** Print into memory obtained from vtk_sqlite3_malloc().  Omit the internal
** %-conversion extensions.
*/
VTK_SQLITE_API char *vtk_sqlite3_vmprintf(const char *zFormat, va_list ap){
  char zBase[VTK_SQLITE_PRINT_BUF_SIZE];
  return base_vprintf(vtk_sqlite3_realloc, 0, zBase, sizeof(zBase), zFormat, ap);
}

/*
** Print into memory obtained from vtk_sqlite3_malloc()().  Omit the internal
** %-conversion extensions.
*/
VTK_SQLITE_API char *vtk_sqlite3_mprintf(const char *zFormat, ...){
  va_list ap;
  char *z;
  va_start(ap, zFormat);
  z = vtk_sqlite3_vmprintf(zFormat, ap);
  va_end(ap);
  return z;
}

/*
** vtk_sqlite3_snprintf() works like snprintf() except that it ignores the
** current locale settings.  This is important for Vtk_Sqlite because we
** are not able to use a "," as the decimal point in place of "." as
** specified by some locales.
*/
VTK_SQLITE_API char *vtk_sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  char *z;
  va_list ap;

  if( n<=0 ){
    return zBuf;
  }
  zBuf[0] = 0;
  va_start(ap,zFormat);
  z = base_vprintf(0, 0, zBuf, n, zFormat, ap);
  va_end(ap);
  return z;
}

#if defined(VTK_SQLITE_TEST) || defined(VTK_SQLITE_DEBUG) || defined(VTK_SQLITE_MEMDEBUG)
/*
** A version of printf() that understands %lld.  Used for debugging.
** The printf() built into some versions of windows does not understand %lld
** and segfaults if you give it a long long int.
*/
VTK_SQLITE_PRIVATE void vtk_sqlite3DebugPrintf(const char *zFormat, ...){
  extern int getpid(void);
  va_list ap;
  char zBuf[500];
  va_start(ap, zFormat);
  base_vprintf(0, 0, zBuf, sizeof(zBuf), zFormat, ap);
  va_end(ap);
  fprintf(stdout,"%s", zBuf);
  fflush(stdout);
}
#endif

/************** End of printf.c **********************************************/
/************** Begin file random.c ******************************************/
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code to implement a pseudo-random number
** generator (PRNG) for Vtk_Sqlite.
**
** Random numbers are used by some of the database backends in order
** to generate random integer keys for tables or random filenames.
**
** $Id: vtk_sqlite3.c,v 1.15 2007/09/20 18:33:36 king Exp $
*/


/*
** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
** must be held while executing this routine.
**
** Why not just use a library random generator like lrand48() for this?
** Because the OP_NewRowid opcode in the VDBE depends on having a very
** good source of random numbers.  The lrand48() library function may
** well be good enough.  But maybe not.  Or maybe lrand48() has some
** subtle problems on some systems that could cause problems.  It is hard
** to know.  To minimize the risk of problems due to bad lrand48()
** implementations, Vtk_Sqlite uses this random number generator based
** on RC4, which we know works very well.
**
** (Later):  Actually, OP_NewRowid does not depend on a good source of
** randomness any more.  But we will leave this code in all the same.
*/
static int randomByte(void){
  unsigned char t;

  /* All threads share a single random number generator.
  ** This structure is the current state of the generator.
  */
  static struct {
    unsigned char isInit;          /* True if initialized */
    unsigned char i, j;            /* State variables */
    unsigned char s[256];          /* State variables */
  } prng;

  /* Initialize the state of the random number generator once,
  ** the first time this routine is called.  The seed value does
  ** not need to contain a lot of randomness since we are not
  ** trying to do secure encryption or anything like that...
  **
  ** Nothing in this file or anywhere else in Vtk_Sqlite does any kind of
  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
  ** number generator) not as an encryption device.
  */
  if( !prng.isInit ){
    int i;
    char k[256];
    prng.j = 0;
    prng.i = 0;
    vtk_sqlite3OsRandomSeed(k);
    for(i=0; i<256; i++){
      prng.s[i] = (unsigned char)i;
    }
    for(i=0; i<256; i++){
      prng.j += prng.s[i] + k[i];
      t = prng.s[prng.j];
      prng.s[prng.j] = prng.s[i];
      prng.s[i] = t;
    }
    prng.isInit = 1;
  }

  /* Generate and return single random byte
  */
  prng.i++;
  t = prng.s[prng.i];
  prng.j = prng.j + t;
  prng.s[prng.i] = prng.s[prng.j];
  prng.s[prng.j] = t;
  t = t + (prng.s[prng.i]);
  return prng.s[t];
}

/*
** Return N random bytes.
*/
VTK_SQLITE_PRIVATE void vtk_sqlite3Randomness(int N, void *pBuf){
  unsigned char *zBuf = pBuf;
  vtk_sqlite3OsEnterMutex();
  while( N-- ){
    *(zBuf++) = (unsigned char)(randomByte());
  }
  vtk_sqlite3OsLeaveMutex();
}

/************** End of random.c **********************************************/
/************** Begin file utf.c *********************************************/
/*
** 2004 April 13
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains routines used to translate between UTF-8, 
** UTF-16, UTF-16BE, and UTF-16LE.
**
** $Id: vtk_sqlite3.c,v 1.15 2007/09/20 18:33:36 king Exp $
**
** Notes on UTF-8:
**
**   Byte-0    Byte-1    Byte-2    Byte-3    Value
**  0xxxxxxx                                 00000000 00000000 0xxxxxxx
**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
**
**
** Notes on UTF-16:  (with wwww+1==uuuuu)
**
**      Word-0               Word-1          Value
**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
**
**
** BOM or Byte Order Mark:
**     0xff 0xfe   little-endian utf-16 follows
**     0xfe 0xff   big-endian utf-16 follows
**
*/
/************** Include vdbeInt.h in the middle of utf.c *********************/
/************** Begin file vdbeInt.h *****************************************/
/*
** 2003 September 6
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This is the header file for information that is private to the
** VDBE.  This information used to all be at the top of the single
** source code file "vdbe.c".  When that file became too big (over
** 6000 lines long) it was split up into several smaller files and
** this header information was factored out.
*/
#ifndef _VDBEINT_H_
#define _VDBEINT_H_

/*
** intToKey() and keyToInt() used to transform the rowid.  But with
** the latest versions of the design they are no-ops.
*/
#define keyToInt(X)   (X)
#define intToKey(X)   (X)

/*
** The makefile scans the vdbe.c source file and creates the following
** array of string constants which are the names of all VDBE opcodes.  This
** array is defined in a separate source code file named opcode.c which is
** automatically generated by the makefile.
*/
extern const char *const vtk_sqlite3OpcodeNames[];

/*
** SQL is translated into a sequence of instructions to be
** executed by a virtual machine.  Each instruction is an instance
** of the following structure.
*/
typedef struct VdbeOp Op;

/*
** Boolean values
*/
typedef unsigned char Bool;

/*
** A cursor is a pointer into a single BTree within a database file.
** The cursor can seek to a BTree entry with a particular key, or
** loop over all entries of the Btree.  You can also insert new BTree
** entries or retrieve the key or data from the entry that the cursor
** is currently pointing to.
** 
** Every cursor that the virtual machine has open is represented by an
** instance of the following structure.
**
** If the Cursor.isTriggerRow flag is set it means that this cursor is
** really a single row that represents the NEW or OLD pseudo-table of
** a row trigger.  The data for the row is stored in Cursor.pData and
** the rowid is in Cursor.iKey.
*/
struct Cursor {
  BtCursor *pCursor;    /* The cursor structure of the backend */
  int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
  i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
  i64 nextRowid;        /* Next rowid returned by OP_NewRowid */
  Bool zeroed;          /* True if zeroed out and ready for reuse */
  Bool rowidIsValid;    /* True if lastRowid is valid */
  Bool atFirst;         /* True if pointing to first entry */
  Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
  Bool nullRow;         /* True if pointing to a row with no data */
  Bool nextRowidValid;  /* True if the nextRowid field is valid */
  Bool pseudoTable;     /* This is a NEW or OLD pseudo-tables of a trigger */
  Bool deferredMoveto;  /* A call to vtk_sqlite3BtreeMoveto() is needed */
  Bool isTable;         /* True if a table requiring integer keys */
  Bool isIndex;         /* True if an index containing keys only - no data */
  u8 bogusIncrKey;      /* Something for pIncrKey to point to if pKeyInfo==0 */
  i64 movetoTarget;     /* Argument to the deferred vtk_sqlite3BtreeMoveto() */
  Btree *pBt;           /* Separate file holding temporary table */
  int nData;            /* Number of bytes in pData */
  char *pData;          /* Data for a NEW or OLD pseudo-table */
  i64 iKey;             /* Key for the NEW or OLD pseudo-table row */
  u8 *pIncrKey;         /* Pointer to pKeyInfo->incrKey */
  KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
  int nField;           /* Number of fields in the header */
  i64 seqCount;         /* Sequence counter */
  vtk_sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
  const vtk_sqlite3_module *pModule;     /* Module for cursor pVtabCursor */

  /* Cached information about the header for the data record that the
  ** cursor is currently pointing to.  Only valid if cacheValid is true.
  ** aRow might point to (ephemeral) data for the current row, or it might
  ** be NULL.
  */
  int cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
  int payloadSize;      /* Total number of bytes in the record */
  u32 *aType;           /* Type values for all entries in the record */
  u32 *aOffset;         /* Cached offsets to the start of each columns data */
  u8 *aRow;             /* Data for the current row, if all on one page */
};
typedef struct Cursor Cursor;

/*
** Number of bytes of string storage space available to each stack
** layer without having to malloc.  NBFS is short for Number of Bytes
** For Strings.
*/
#define NBFS 32

/*
** A value for Cursor.cacheValid that means the cache is always invalid.
*/
#define CACHE_STALE 0

/*
** Internally, the vdbe manipulates nearly all SQL values as Mem
** structures. Each Mem struct may cache multiple representations (string,
** integer etc.) of the same value.  A value (and therefore Mem structure)
** has the following properties:
**
** Each value has a manifest type. The manifest type of the value stored
** in a Mem struct is returned by the MemType(Mem*) macro. The type is
** one of VTK_SQLITE_NULL, VTK_SQLITE_INTEGER, VTK_SQLITE_REAL, VTK_SQLITE_TEXT or
** VTK_SQLITE_BLOB.
*/
struct Mem {
  union {
    i64 i;              /* Integer value. Or FuncDef* when flags==MEM_Agg */
    FuncDef *pDef;      /* Used only when flags==MEM_Agg */
  } u;
  double r;           /* Real value */
  char *z;            /* String or BLOB value */
  int n;              /* Number of characters in string value, including '\0' */
  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  u8  type;           /* One of VTK_SQLITE_NULL, VTK_SQLITE_TEXT, VTK_SQLITE_INTEGER, etc */
  u8  enc;            /* VTK_SQLITE_UTF8, VTK_SQLITE_UTF16BE, VTK_SQLITE_UTF16LE */
  void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
  char zShort[NBFS];  /* Space for short strings */
};
typedef struct Mem Mem;

/* One or more of the following flags are set to indicate the validOK
** representations of the value stored in the Mem struct.
**
** If the MEM_Null flag is set, then the value is an SQL NULL value.
** No other flags may be set in this case.
**
** If the MEM_Str flag is set then Mem.z points at a string representation.
** Usually this is encoded in the same unicode encoding as the main
** database (see below for exceptions). If the MEM_Term flag is also
** set, then the string is nul terminated. The MEM_Int and MEM_Real 
** flags may coexist with the MEM_Str flag.
**
** Multiple of these values can appear in Mem.flags.  But only one
** at a time can appear in Mem.type.
*/
#define MEM_Null      0x0001   /* Value is NULL */
#define MEM_Str       0x0002   /* Value is a string */
#define MEM_Int       0x0004   /* Value is an integer */
#define MEM_Real      0x0008   /* Value is a real number */
#define MEM_Blob      0x0010   /* Value is a BLOB */

/* Whenever Mem contains a valid string or blob representation, one of
** the following flags must be set to determine the memory management
** policy for Mem.z.  The MEM_Term flag tells us whether or not the
** string is \000 or \u0000 terminated
*/
#define MEM_Term      0x0020   /* String rep is nul terminated */
#define MEM_Dyn       0x0040   /* Need to call vtk_sqliteFree() on Mem.z */
#define MEM_Static    0x0080   /* Mem.z points to a static string */
#define MEM_Ephem     0x0100   /* Mem.z points to an ephemeral string */
#define MEM_Short     0x0200   /* Mem.z points to Mem.zShort */
#define MEM_Agg       0x0400   /* Mem.z points to an agg function context */
#define MEM_Zero      0x0800   /* Mem.i contains count of 0s appended to blob */

#ifdef VTK_SQLITE_OMIT_INCRBLOB
  #undef MEM_Zero
  #define MEM_Zero 0x0000
#endif


/* A VdbeFunc is just a FuncDef (defined in vtk_sqliteInt.h) that contains
** additional information about auxiliary information bound to arguments
** of the function.  This is used to implement the vtk_sqlite3_get_auxdata()
** and vtk_sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
** that can be associated with a constant argument to a function.  This
** allows functions such as "regexp" to compile their constant regular
** expression argument once and reused the compiled code for multiple
** invocations.
*/
struct VdbeFunc {
  FuncDef *pFunc;               /* The definition of the function */
  int nAux;                     /* Number of entries allocated for apAux[] */
  struct AuxData {
    void *pAux;                   /* Aux data for the i-th argument */
    void (*xDelete)(void *);      /* Destructor for the aux data */
  } apAux[1];                   /* One slot for each function argument */
};
typedef struct VdbeFunc VdbeFunc;

/*
** The "context" argument for a installable function.  A pointer to an
** instance of this structure is the first argument to the routines used
** implement the SQL functions.
**
** There is a typedef for this structure in vtk_sqlite.h.  So all routines,
** even the public interface to Vtk_Sqlite, can use a pointer to this structure.
** But this file is the only place where the internal details of this
** structure are known.
**
** This structure is defined inside of vdbeInt.h because it uses substructures
** (Mem) which are only defined there.
*/
struct vtk_sqlite3_context {
  FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
  VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
  Mem s;                /* The return value is stored here */
  Mem *pMem;            /* Memory cell used to store aggregate context */
  u8 isError;           /* Set to true for an error */
  CollSeq *pColl;       /* Collating sequence */
};

/*
** A Set structure is used for quick testing to see if a value
** is part of a small set.  Sets are used to implement code like
** this:
**            x.y IN ('hi','hoo','hum')
*/
typedef struct Set Set;
struct Set {
  Hash hash;             /* A set is just a hash table */
  HashElem *prev;        /* Previously accessed hash elemen */
};

/*
** A FifoPage structure holds a single page of valves.  Pages are arranged
** in a list.
*/
typedef struct FifoPage FifoPage;
struct FifoPage {
  int nSlot;         /* Number of entries aSlot[] */
  int iWrite;        /* Push the next value into this entry in aSlot[] */
  int iRead;         /* Read the next value from this entry in aSlot[] */
  FifoPage *pNext;   /* Next page in the fifo */
  i64 aSlot[1];      /* One or more slots for rowid values */
};

/*
** The Fifo structure is typedef-ed in vdbeInt.h.  But the implementation
** of that structure is private to this file.
**
** The Fifo structure describes the entire fifo.  
*/
typedef struct Fifo Fifo;
struct Fifo {
  int nEntry;         /* Total number of entries */
  FifoPage *pFirst;   /* First page on the list */
  FifoPage *pLast;    /* Last page on the list */
};

/*
** A Context stores the last insert rowid, the last statement change count,
** and the current statement change count (i.e. changes since last statement).
** The current keylist is also stored in the context.
** Elements of Context structure type make up the ContextStack, which is
** updated by the ContextPush and ContextPop opcodes (used by triggers).
** The context is pushed before executing a trigger a popped when the
** trigger finishes.
*/
typedef struct Context Context;
struct Context {
  i64 lastRowid;    /* Last insert rowid (vtk_sqlite3.lastRowid) */
  int nChange;      /* Statement changes (Vdbe.nChanges)     */
  Fifo sFifo;       /* Records that will participate in a DELETE or UPDATE */
};

/*
** An instance of the virtual machine.  This structure contains the complete
** state of the virtual machine.
**
** The "vtk_sqlite3_stmt" structure pointer that is returned by vtk_sqlite3_compile()
** is really a pointer to an instance of this structure.
**
** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
** any virtual table method invocations made by the vdbe program. It is
** set to 2 for xDestroy method calls and 1 for all other methods. This
** variable is used for two purposes: to allow xDestroy methods to execute
** "DROP TABLE" statements and to prevent some nasty side effects of
** malloc failure when Vtk_Sqlite is invoked recursively by a virtual table 
** method function.
*/
struct Vdbe {
  vtk_sqlite3 *db;        /* The whole database */
  Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  int nOp;            /* Number of instructions in the program */
  int nOpAlloc;       /* Number of slots allocated for aOp[] */
  Op *aOp;            /* Space to hold the virtual machine's program */
  int nLabel;         /* Number of labels used */
  int nLabelAlloc;    /* Number of slots allocated in aLabel[] */
  int *aLabel;        /* Space to hold the labels */
  Mem *aStack;        /* The operand stack, except string values */
  Mem *pTos;          /* Top entry in the operand stack */
  Mem **apArg;        /* Arguments to currently executing user function */
  Mem *aColName;      /* Column names to return */
  int nCursor;        /* Number of slots in apCsr[] */
  Cursor **apCsr;     /* One element of this array for each open cursor */
  int nVar;           /* Number of entries in aVar[] */
  Mem *aVar;          /* Values for the OP_Variable opcode. */
  char **azVar;       /* Name of variables */
  int okVar;          /* True if azVar[] has been initialized */
  int magic;              /* Magic number for sanity checking */
  int nMem;               /* Number of memory locations currently allocated */
  Mem *aMem;              /* The memory locations */
  int nCallback;          /* Number of callbacks invoked so far */
  int cacheCtr;           /* Cursor row cache generation counter */
  Fifo sFifo;             /* A list of ROWIDs */
  int contextStackTop;    /* Index of top element in the context stack */
  int contextStackDepth;  /* The size of the "context" stack */
  Context *contextStack;  /* Stack used by opcodes ContextPush & ContextPop*/
  int pc;                 /* The program counter */
  int rc;                 /* Value to return */
  unsigned uniqueCnt;     /* Used by OP_MakeRecord when P2!=0 */
  int errorAction;        /* Recovery action to do in case of an error */
  int inTempTrans;        /* True if temp database is transactioned */
  int returnStack[100];   /* Return address stack for OP_Gosub & OP_Return */
  int returnDepth;        /* Next unused element in returnStack[] */
  int nResColumn;         /* Number of columns in one row of the result set */
  char **azResColumn;     /* Values for one row of result */ 
  int popStack;           /* Pop the stack this much on entry to VdbeExec() */
  char *zErrMsg;          /* Error message written here */
  u8 resOnStack;          /* True if there are result values on the stack */
  u8 explain;             /* True if EXPLAIN present on SQL command */
  u8 changeCntOn;         /* True to update the change-counter */
  u8 aborted;             /* True if ROLLBACK in another VM causes an abort */
  u8 expired;             /* True if the VM needs to be recompiled */
  u8 minWriteFileFormat;  /* Minimum file format for writable database files */
  u8 inVtabMethod;        /* See comments above */
  int nChange;            /* Number of db changes made since last reset */
  i64 startTime;          /* Time when query started - used for profiling */
  int nSql;             /* Number of bytes in zSql */
  char *zSql;           /* Text of the SQL statement that generated this */
#ifdef VTK_SQLITE_DEBUG
  FILE *trace;        /* Write an execution trace here, if not NULL */
#endif
  int openedStatement;  /* True if this VM has opened a statement journal */
#ifdef VTK_SQLITE_SSE
  int fetchId;          /* Statement number used by vtk_sqlite3_fetch_statement */
  int lru;              /* Counter used for LRU cache replacement */
#endif
};

/*
** The following are allowed values for Vdbe.magic
*/
#define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
#define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
#define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
#define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */

/*
** Function prototypes
*/
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeFreeCursor(Vdbe *, Cursor*);
void vtk_sqliteVdbePopStack(Vdbe*,int);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeCursorMoveto(Cursor*);
#if defined(VTK_SQLITE_DEBUG) || defined(VDBE_PROFILE)
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbePrintOp(FILE*, int, Op*);
#endif
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeSerialTypeLen(u32);
VTK_SQLITE_PRIVATE u32 vtk_sqlite3VdbeSerialType(Mem*, int);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeDeleteAuxData(VdbeFunc*, int);

int vtk_sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeIdxKeyCompare(Cursor*, int , const unsigned char*, int*);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeIdxRowid(BtCursor *, i64 *);
VTK_SQLITE_PRIVATE int vtk_sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeRecordCompare(void*,int,const void*,int, const void*);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeIdxRowidLen(const u8*);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeExec(Vdbe*);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeList(Vdbe*);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeHalt(Vdbe*);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeChangeEncoding(Mem *, int);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeMemTooBig(Mem*);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeMemCopy(Mem*, const Mem*);
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeMemMove(Mem*, Mem*);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeMemNulTerminate(Mem*);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeMemSetInt64(Mem*, i64);
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeMemSetDouble(Mem*, double);
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeMemSetNull(Mem*);
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeMemSetZeroBlob(Mem*,int);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeMemMakeWriteable(Mem*);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeMemDynamicify(Mem*);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeMemStringify(Mem*, int);
VTK_SQLITE_PRIVATE i64 vtk_sqlite3VdbeIntValue(Mem*);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeMemIntegerify(Mem*);
VTK_SQLITE_PRIVATE double vtk_sqlite3VdbeRealValue(Mem*);
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeIntegerAffinity(Mem*);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeMemRealify(Mem*);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeMemNumerify(Mem*);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeMemRelease(Mem *p);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeMemFinalize(Mem*, FuncDef*);
#ifndef NDEBUG
VTK_SQLITE_PRIVATE   void vtk_sqlite3VdbeMemSanity(Mem*);
VTK_SQLITE_PRIVATE   int vtk_sqlite3VdbeOpcodeNoPush(u8);
#endif
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeMemTranslate(Mem*, u8);
#ifdef VTK_SQLITE_DEBUG
VTK_SQLITE_PRIVATE   void vtk_sqlite3VdbePrintSql(Vdbe*);
VTK_SQLITE_PRIVATE   void vtk_sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
#endif
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeMemHandleBom(Mem *pMem);
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeFifoInit(Fifo*);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeFifoPush(Fifo*, i64);
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeFifoPop(Fifo*, i64*);
VTK_SQLITE_PRIVATE void vtk_sqlite3VdbeFifoClear(Fifo*);

#ifndef VTK_SQLITE_OMIT_INCRBLOB
VTK_SQLITE_PRIVATE   int vtk_sqlite3VdbeMemExpandBlob(Mem *);
#else
  #define vtk_sqlite3VdbeMemExpandBlob(x) VTK_SQLITE_OK
#endif

#endif /* !defined(_VDBEINT_H_) */

/************** End of vdbeInt.h *********************************************/
/************** Continuing where we left off in utf.c ************************/

/*
** The following constant value is used by the VTK_SQLITE_BIGENDIAN and
** VTK_SQLITE_LITTLEENDIAN macros.
*/
const int vtk_sqlite3one = 1;

/*
** This lookup table is used to help decode the first byte of
** a multi-byte UTF8 character.
*/
const unsigned char vtk_sqlite3UtfTrans1[] = {
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
};

#define WRITE_UTF8(zOut, c) {                                           \
  if( c<0x00080 ){                                                      \
    *zOut++ = (unsigned char)(c&0xFF);                                  \
  }                                                                     \
  else if( c<0x00800 ){                                                 \
    *zOut++ = (unsigned char)(0xC0 + ((c>>6)&0x1F));                    \
    *zOut++ = (unsigned char)(0x80 + (c & 0x3F));                       \
  }                                                                     \
  else if( c<0x10000 ){                                                 \
    *zOut++ = (unsigned char)(0xE0 + ((c>>12)&0x0F));                   \
    *zOut++ = (unsigned char)(0x80 + ((c>>6) & 0x3F));                  \
    *zOut++ = (unsigned char)(0x80 + (c & 0x3F));                       \
  }else{                                                                \
    *zOut++ = (unsigned char)(0xF0 + ((c>>18) & 0x07));                 \
    *zOut++ = (unsigned char)(0x80 + ((c>>12) & 0x3F));                 \
    *zOut++ = (unsigned char)(0x80 + ((c>>6) & 0x3F));                  \
    *zOut++ = (unsigned char)(0x80 + (c & 0x3F));                       \
  }                                                                     \
}

#define WRITE_UTF16LE(zOut, c) {                                               \
  if( c<=0xFFFF ){                                                             \
    *zOut++ = (unsigned char)(c&0x00FF);                                       \
    *zOut++ = (unsigned char)((c>>8)&0x00FF);                                  \
  }else{                                                                       \
    *zOut++ = (unsigned char)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
    *zOut++ = (unsigned char)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
    *zOut++ = (unsigned char)(c&0x00FF);                                       \
    *zOut++ = (unsigned char)(0x00DC + ((c>>8)&0x03));                         \
  }                                                                            \
}

#define WRITE_UTF16BE(zOut, c) {                                               \
  if( c<=0xFFFF ){                                                             \
    *zOut++ = (unsigned char)((c>>8)&0x00FF);                                  \
    *zOut++ = (unsigned char)(c&0x00FF);                                       \
  }else{                                                                       \
    *zOut++ = (unsigned char)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
    *zOut++ = (unsigned char)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
    *zOut++ = (unsigned char)(0x00DC + ((c>>8)&0x03));                         \
    *zOut++ = (unsigned char)(c&0x00FF);                                       \
  }                                                                            \
}

#define READ_UTF16LE(zIn, c){                                         \
  c = (*zIn++);                                                       \
  c += ((*zIn++)<<8);                                                 \
  if( c>=0xD800 && c<0xE000 ){                                       \
    int c2 = (*zIn++);                                                \
    c2 += ((*zIn++)<<8);                                              \
    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
    if( (c & 0xFFFF0000)==0 ) c = 0xFFFD;                             \
  }                                                                   \
}

#define READ_UTF16BE(zIn, c){                                         \
  c = ((*zIn++)<<8);                                                  \
  c += (*zIn++);                                                      \
  if( c>=0xD800 && c<0xE000 ){                                       \
    int c2 = ((*zIn++)<<8);                                           \
    c2 += (*zIn++);                                                   \
    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
    if( (c & 0xFFFF0000)==0 ) c = 0xFFFD;                             \
  }                                                                   \
}

/*
** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
** printed on stderr on the way into and out of vtk_sqlite3VdbeMemTranslate().
*/ 
/* #define TRANSLATE_TRACE 1 */

#ifndef VTK_SQLITE_OMIT_UTF16
/*
** This routine transforms the internal text encoding used by pMem to
** desiredEnc. It is an error if the string is already of the desired
** encoding, or if *pMem does not contain a string value.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  unsigned char zShort[NBFS]; /* Temporary short output buffer */
  int len;                    /* Maximum length of output string in bytes */
  unsigned char *zOut;                  /* Output buffer */
  unsigned char *zIn;                   /* Input iterator */
  unsigned char *zTerm;                 /* End of input */
  unsigned char *z;                     /* Output iterator */
  unsigned int c;

  assert( pMem->flags&MEM_Str );
  assert( pMem->enc!=desiredEnc );
  assert( pMem->enc!=0 );
  assert( pMem->n>=0 );

#if defined(TRANSLATE_TRACE) && defined(VTK_SQLITE_DEBUG)
  {
    char zBuf[100];
    vtk_sqlite3VdbeMemPrettyPrint(pMem, zBuf);
    fprintf(stderr, "INPUT:  %s\n", zBuf);
  }
#endif

  /* If the translation is between UTF-16 little and big endian, then 
  ** all that is required is to swap the byte order. This case is handled
  ** differently from the others.
  */
  if( pMem->enc!=VTK_SQLITE_UTF8 && desiredEnc!=VTK_SQLITE_UTF8 ){
    u8 temp;
    int rc;
    rc = vtk_sqlite3VdbeMemMakeWriteable(pMem);
    if( rc!=VTK_SQLITE_OK ){
      assert( rc==VTK_SQLITE_NOMEM );
      return VTK_SQLITE_NOMEM;
    }
    zIn = (u8*)pMem->z;
    zTerm = &zIn[pMem->n];
    while( zIn<zTerm ){
      temp = *zIn;
      *zIn = *(zIn+1);
      zIn++;
      *zIn++ = temp;
    }
    pMem->enc = desiredEnc;
    goto translate_out;
  }

  /* Set len to the maximum number of bytes required in the output buffer. */
  if( desiredEnc==VTK_SQLITE_UTF8 ){
    /* When converting from UTF-16, the maximum growth results from
    ** translating a 2-byte character to a 4-byte UTF-8 character.
    ** A single byte is required for the output string
    ** nul-terminator.
    */
    len = pMem->n * 2 + 1;
  }else{
    /* When converting from UTF-8 to UTF-16 the maximum growth is caused
    ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
    ** character. Two bytes are required in the output buffer for the
    ** nul-terminator.
    */
    len = pMem->n * 2 + 2;
  }

  /* Set zIn to point at the start of the input buffer and zTerm to point 1
  ** byte past the end.
  **
  ** Variable zOut is set to point at the output buffer. This may be space
  ** obtained from malloc(), or Mem.zShort, if it large enough and not in
  ** use, or the zShort array on the stack (see above).
  */
  zIn = (u8*)pMem->z;
  zTerm = &zIn[pMem->n];
  if( len>NBFS ){
    zOut = vtk_sqliteMallocRaw(len);
    if( !zOut ) return VTK_SQLITE_NOMEM;
  }else{
    zOut = zShort;
  }
  z = zOut;

  if( pMem->enc==VTK_SQLITE_UTF8 ){
    unsigned int iExtra = 0xD800;

    if( 0==(pMem->flags&MEM_Term) && zTerm>zIn && (zTerm[-1]&0x80) ){
      /* This UTF8 string is not nul-terminated, and the last byte is
      ** not a character in the ascii range (codpoints 0..127). This
      ** means the VTK_SQLITE_READ_UTF8() macro might read past the end
      ** of the allocated buffer.
      **
      ** There are four possibilities:
      **
      **   1. The last byte is the first byte of a non-ASCII character,
      **
      **   2. The final N bytes of the input string are continuation bytes
      **      and immediately preceding them is the first byte of a 
      **      non-ASCII character.
      **
      **   3. The final N bytes of the input string are continuation bytes
      **      and immediately preceding them is a byte that encodes a 
      **      character in the ASCII range.
      **
      **   4. The entire string consists of continuation characters.
      **
      ** Cases (3) and (4) require no special handling. The VTK_SQLITE_READ_UTF8()
      ** macro will not overread the buffer in these cases.
      */
      unsigned char *zExtra = &zTerm[-1];
      while( zExtra>zIn && (zExtra[0]&0xC0)==0x80 ){
        zExtra--;
      }

      if( (zExtra[0]&0xC0)==0xC0 ){
        /* Make a copy of the last character encoding in the input string.
        ** Then make sure it is nul-terminated and use VTK_SQLITE_READ_UTF8()
        ** to decode the codepoint. Store the codepoint in variable iExtra,
        ** it will be appended to the output string later.
        */
        unsigned char *zFree = 0;
        unsigned char zBuf[16];
        int nExtra = (pMem->n+zIn-zExtra);
        zTerm = zExtra;
        if( nExtra>15 ){
          zExtra = vtk_sqliteMallocRaw(nExtra+1);
          if( !zExtra ){
            return VTK_SQLITE_NOMEM;
          }
          zFree = zExtra;
        }else{
          zExtra = zBuf;
        }
        memcpy(zExtra, zTerm, nExtra);
        zExtra[nExtra] = '\0';
        VTK_SQLITE_READ_UTF8(zExtra, iExtra);
        vtk_sqliteFree(zFree);
      }
    }

    if( desiredEnc==VTK_SQLITE_UTF16LE ){
      /* UTF-8 -> UTF-16 Little-endian */
      while( zIn<zTerm ){
        VTK_SQLITE_READ_UTF8(zIn, c); 
        WRITE_UTF16LE(z, c);
      }
      if( iExtra!=0xD800 ){
        WRITE_UTF16LE(z, iExtra);
      }
    }else{
      assert( desiredEnc==VTK_SQLITE_UTF16BE );
      /* UTF-8 -> UTF-16 Big-endian */
      while( zIn<zTerm ){
        VTK_SQLITE_READ_UTF8(zIn, c); 
        WRITE_UTF16BE(z, c);
      }
      if( iExtra!=0xD800 ){
        WRITE_UTF16BE(z, iExtra);
      }
    }
    pMem->n = z - zOut;
    *z++ = 0;
  }else{
    assert( desiredEnc==VTK_SQLITE_UTF8 );
    if( pMem->enc==VTK_SQLITE_UTF16LE ){
      /* UTF-16 Little-endian -> UTF-8 */
      while( zIn<zTerm ){
        READ_UTF16LE(zIn, c); 
        WRITE_UTF8(z, c);
      }
    }else{
      /* UTF-16 Little-endian -> UTF-8 */
      while( zIn<zTerm ){
        READ_UTF16BE(zIn, c); 
        WRITE_UTF8(z, c);
      }
    }
    pMem->n = z - zOut;
  }
  *z = 0;
  assert( (pMem->n+(desiredEnc==VTK_SQLITE_UTF8?1:2))<=len );

  vtk_sqlite3VdbeMemRelease(pMem);
  pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short);
  pMem->enc = desiredEnc;
  if( zOut==zShort ){
    memcpy(pMem->zShort, zOut, len);
    zOut = (u8*)pMem->zShort;
    pMem->flags |= (MEM_Term|MEM_Short);
  }else{
    pMem->flags |= (MEM_Term|MEM_Dyn);
  }
  pMem->z = (char*)zOut;

translate_out:
#if defined(TRANSLATE_TRACE) && defined(VTK_SQLITE_DEBUG)
  {
    char zBuf[100];
    vtk_sqlite3VdbeMemPrettyPrint(pMem, zBuf);
    fprintf(stderr, "OUTPUT: %s\n", zBuf);
  }
#endif
  return VTK_SQLITE_OK;
}

/*
** This routine checks for a byte-order mark at the beginning of the 
** UTF-16 string stored in *pMem. If one is present, it is removed and
** the encoding of the Mem adjusted. This routine does not do any
** byte-swapping, it just sets Mem.enc appropriately.
**
** The allocation (static, dynamic etc.) and encoding of the Mem may be
** changed by this function.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3VdbeMemHandleBom(Mem *pMem){
  int rc = VTK_SQLITE_OK;
  u8 bom = 0;

  if( pMem->n<0 || pMem->n>1 ){
    u8 b1 = *(u8 *)pMem->z;
    u8 b2 = *(((u8 *)pMem->z) + 1);
    if( b1==0xFE && b2==0xFF ){
      bom = VTK_SQLITE_UTF16BE;
    }
    if( b1==0xFF && b2==0xFE ){
      bom = VTK_SQLITE_UTF16LE;
    }
  }
  
  if( bom ){
    /* This function is called as soon as a string is stored in a Mem*,
    ** from within vtk_sqlite3VdbeMemSetStr(). At that point it is not possible
    ** for the string to be stored in Mem.zShort, or for it to be stored
    ** in dynamic memory with no destructor.
    */
    assert( !(pMem->flags&MEM_Short) );
    assert( !(pMem->flags&MEM_Dyn) || pMem->xDel );
    if( pMem->flags & MEM_Dyn ){
      void (*xDel)(void*) = pMem->xDel;
      char *z = pMem->z;
      pMem->z = 0;
      pMem->xDel = 0;
      rc = vtk_sqlite3VdbeMemSetStr(pMem, &z[2], pMem->n-2, bom, VTK_SQLITE_TRANSIENT);
      xDel(z);
    }else{
      rc = vtk_sqlite3VdbeMemSetStr(pMem, &pMem->z[2], pMem->n-2, bom, 
          VTK_SQLITE_TRANSIENT);
    }
  }
  return rc;
}
#endif /* VTK_SQLITE_OMIT_UTF16 */

/*
** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
** return the number of unicode characters in pZ up to (but not including)
** the first 0x00 byte. If nByte is not less than zero, return the
** number of unicode characters in the first nByte of pZ (or up to 
** the first 0x00, whichever comes first).
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3Utf8CharLen(const char *zIn, int nByte){
  int r = 0;
  const u8 *z = (const u8*)zIn;
  const u8 *zTerm;
  if( nByte>=0 ){
    zTerm = &z[nByte];
  }else{
    zTerm = (const u8*)(-1);
  }
  assert( z<=zTerm );
  while( *z!=0 && z<zTerm ){
    VTK_SQLITE_SKIP_UTF8(z);
    r++;
  }
  return r;
}

#ifndef VTK_SQLITE_OMIT_UTF16
/*
** Convert a UTF-16 string in the native encoding into a UTF-8 string.
** Memory to hold the UTF-8 string is obtained from malloc and must be
** freed by the calling function.
**
** NULL is returned if there is an allocation error.
*/
VTK_SQLITE_PRIVATE char *vtk_sqlite3Utf16to8(const void *z, int nByte){
  Mem m;
  memset(&m, 0, sizeof(m));
  vtk_sqlite3VdbeMemSetStr(&m, z, nByte, VTK_SQLITE_UTF16NATIVE, VTK_SQLITE_STATIC);
  vtk_sqlite3VdbeChangeEncoding(&m, VTK_SQLITE_UTF8);
  assert( (m.flags & MEM_Term)!=0 || vtk_sqlite3MallocFailed() );
  assert( (m.flags & MEM_Str)!=0 || vtk_sqlite3MallocFailed() );
  return (m.flags & MEM_Dyn)!=0 ? m.z : vtk_sqliteStrDup(m.z);
}

/*
** pZ is a UTF-16 encoded unicode string. If nChar is less than zero,
** return the number of bytes up to (but not including), the first pair
** of consecutive 0x00 bytes in pZ. If nChar is not less than zero,
** then return the number of bytes in the first nChar unicode characters
** in pZ (or up until the first pair of 0x00 bytes, whichever comes first).
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3Utf16ByteLen(const void *zIn, int nChar){
  unsigned int c = 1;
  char const *z = zIn;
  int n = 0;
  if( VTK_SQLITE_UTF16NATIVE==VTK_SQLITE_UTF16BE ){
    /* Using an "if (VTK_SQLITE_UTF16NATIVE==VTK_SQLITE_UTF16BE)" construct here
    ** and in other parts of this file means that at one branch will
    ** not be covered by coverage testing on any single host. But coverage
    ** will be complete if the tests are run on both a little-endian and 
    ** big-endian host. Because both the UTF16NATIVE and VTK_SQLITE_UTF16BE
    ** macros are constant at compile time the compiler can determine
    ** which branch will be followed. It is therefore assumed that no runtime
    ** penalty is paid for this "if" statement.
    */
    while( c && ((nChar<0) || n<nChar) ){
      READ_UTF16BE(z, c);
      n++;
    }
  }else{
    while( c && ((nChar<0) || n<nChar) ){
      READ_UTF16LE(z, c);
      n++;
    }
  }
  return (z-(char const *)zIn)-((c==0)?2:0);
}

#if defined(VTK_SQLITE_TEST)
/*
** Translate UTF-8 to UTF-8.
**
** This has the effect of making sure that the string is well-formed
** UTF-8.  Miscoded characters are removed.
**
** The translation is done in-place (since it is impossible for the
** correct UTF-8 encoding to be longer than a malformed encoding).
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3Utf8To8(unsigned char *zIn){
  unsigned char *zOut = zIn;
  unsigned char *zStart = zIn;
  int c;

  while(1){
    VTK_SQLITE_READ_UTF8(zIn, c);
    if( c==0 ) break;
    if( c!=0xfffd ){
      WRITE_UTF8(zOut, c);
    }
  }
  *zOut = 0;
  return zOut - zStart;
}
#endif

#if defined(VTK_SQLITE_TEST)
/*
** This routine is called from the TCL test function "translate_selftest".
** It checks that the primitives for serializing and deserializing
** characters in each encoding are inverses of each other.
*/
VTK_SQLITE_PRIVATE void vtk_sqlite3UtfSelfTest(){
  unsigned int i, t;
  unsigned char zBuf[20];
  unsigned char *z;
  int n;
  unsigned int c;

  for(i=0; i<0x00110000; i++){
    z = zBuf;
    WRITE_UTF8(z, i);
    n = z-zBuf;
    z[0] = 0;
    z = zBuf;
    VTK_SQLITE_READ_UTF8(z, c);
    t = i;
    if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
    if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
    assert( c==t );
    assert( (z-zBuf)==n );
  }
  for(i=0; i<0x00110000; i++){
    if( i>=0xD800 && i<0xE000 ) continue;
    z = zBuf;
    WRITE_UTF16LE(z, i);
    n = z-zBuf;
    z[0] = 0;
    z = zBuf;
    READ_UTF16LE(z, c);
    assert( c==i );
    assert( (z-zBuf)==n );
  }
  for(i=0; i<0x00110000; i++){
    if( i>=0xD800 && i<0xE000 ) continue;
    z = zBuf;
    WRITE_UTF16BE(z, i);
    n = z-zBuf;
    z[0] = 0;
    z = zBuf;
    READ_UTF16BE(z, c);
    assert( c==i );
    assert( (z-zBuf)==n );
  }
}
#endif /* VTK_SQLITE_TEST */
#endif /* VTK_SQLITE_OMIT_UTF16 */

/************** End of utf.c *************************************************/
/************** Begin file util.c ********************************************/
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Utility functions used throughout vtk_sqlite.
**
** This file contains functions for allocating memory, comparing
** strings, and stuff like that.
**
** $Id: vtk_sqlite3.c,v 1.15 2007/09/20 18:33:36 king Exp $
*/


/*
** Set the most recent error code and error string for the vtk_sqlite
** handle "db". The error code is set to "err_code".
**
** If it is not NULL, string zFormat specifies the format of the
** error string in the style of the printf functions: The following
** format characters are allowed:
**
**      %s      Insert a string
**      %z      A string that should be freed after use
**      %d      Insert an integer
**      %T      Insert a token
**      %S      Insert the first element of a SrcList
**
** zFormat and any string tokens that follow it are assumed to be
** encoded in UTF-8.
**
** To clear the most recent error for vtk_sqlite handle "db", vtk_sqlite3Error
** should be called with err_code set to VTK_SQLITE_OK and zFormat set
** to NULL.
*/
VTK_SQLITE_PRIVATE void vtk_sqlite3Error(vtk_sqlite3 *db, int err_code, const char *zFormat, ...){
  if( db && (db->pErr || (db->pErr = vtk_sqlite3ValueNew())!=0) ){
    db->errCode = err_code;
    if( zFormat ){
      char *z;
      va_list ap;
      va_start(ap, zFormat);
      z = vtk_sqlite3VMPrintf(zFormat, ap);
      va_end(ap);
      vtk_sqlite3ValueSetStr(db->pErr, -1, z, VTK_SQLITE_UTF8, vtk_sqlite3FreeX);
    }else{
      vtk_sqlite3ValueSetStr(db->pErr, 0, 0, VTK_SQLITE_UTF8, VTK_SQLITE_STATIC);
    }
  }
}

/*
** Add an error message to pParse->zErrMsg and increment pParse->nErr.
** The following formatting characters are allowed:
**
**      %s      Insert a string
**      %z      A string that should be freed after use
**      %d      Insert an integer
**      %T      Insert a token
**      %S      Insert the first element of a SrcList
**
** This function should be used to report any error that occurs whilst
** compiling an SQL statement (i.e. within vtk_sqlite3_prepare()). The
** last thing the vtk_sqlite3_prepare() function does is copy the error
** stored by this function into the database handle using vtk_sqlite3Error().
** Function vtk_sqlite3Error() should be used during statement execution
** (vtk_sqlite3_step() etc.).
*/
VTK_SQLITE_PRIVATE void vtk_sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  va_list ap;
  pParse->nErr++;
  vtk_sqliteFree(pParse->zErrMsg);
  va_start(ap, zFormat);
  pParse->zErrMsg = vtk_sqlite3VMPrintf(zFormat, ap);
  va_end(ap);
  if( pParse->rc==VTK_SQLITE_OK ){
    pParse->rc = VTK_SQLITE_ERROR;
  }
}

/*
** Clear the error message in pParse, if any
*/
VTK_SQLITE_PRIVATE void vtk_sqlite3ErrorClear(Parse *pParse){
  vtk_sqliteFree(pParse->zErrMsg);
  pParse->zErrMsg = 0;
  pParse->nErr = 0;
}

/*
** Convert an SQL-style quoted string into a normal string by removing
** the quote characters.  The conversion is done in-place.  If the
** input does not begin with a quote character, then this routine
** is a no-op.
**
** 2002-Feb-14: This routine is extended to remove MS-Access style
** brackets from around identifers.  For example:  "[a-b-c]" becomes
** "a-b-c".
*/
VTK_SQLITE_PRIVATE void vtk_sqlite3Dequote(char *z){
  int quote;
  int i, j;
  if( z==0 ) return;
  quote = z[0];
  switch( quote ){
    case '\'':  break;
    case '"':   break;
    case '`':   break;                /* For MySQL compatibility */
    case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
    default:    return;
  }
  for(i=1, j=0; z[i]; i++){
    if( z[i]==quote ){
      if( z[i+1]==quote ){
        z[j++] = (char)(quote);
        i++;
      }else{
        z[j++] = 0;
        break;
      }
    }else{
      z[j++] = z[i];
    }
  }
}

/* An array to map all upper-case characters into their corresponding
** lower-case character. 
*/
const unsigned char vtk_sqlite3UpperToLower[] = {
#ifdef VTK_SQLITE_ASCII
      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
    252,253,254,255
#endif
#ifdef VTK_SQLITE_EBCDIC
      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
     96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
    112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
    144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
    160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
    224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
    239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
#endif
};
#define UpperToLower vtk_sqlite3UpperToLower

/*
** Some systems have stricmp().  Others have strcasecmp().  Because
** there is no consistency, we will define our own.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3StrICmp(const char *zLeft, const char *zRight){
  register unsigned char *a, *b;
  a = (unsigned char *)zLeft;
  b = (unsigned char *)zRight;
  while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  return UpperToLower[*a] - UpperToLower[*b];
}
VTK_SQLITE_PRIVATE int vtk_sqlite3StrNICmp(const char *zLeft, const char *zRight, int N){
  register unsigned char *a, *b;
  a = (unsigned char *)zLeft;
  b = (unsigned char *)zRight;
  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
}

/*
** Return TRUE if z is a pure numeric string.  Return FALSE if the
** string contains any character which is not part of a number. If
** the string is numeric and contains the '.' character, set *realnum
** to TRUE (otherwise FALSE).
**
** An empty string is considered non-numeric.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3IsNumber(const char *z, int *realnum, u8 enc){
  int incr = (enc==VTK_SQLITE_UTF8?1:2);
  if( enc==VTK_SQLITE_UTF16BE ) z++;
  if( *z=='-' || *z=='+' ) z += incr;
  if( !isdigit(*(u8*)z) ){
    return 0;
  }
  z += incr;
  if( realnum ) *realnum = 0;
  while( isdigit(*(u8*)z) ){ z += incr; }
  if( *z=='.' ){
    z += incr;
    if( !isdigit(*(u8*)z) ) return 0;
    while( isdigit(*(u8*)z) ){ z += incr; }
    if( realnum ) *realnum = 1;
  }
  if( *z=='e' || *z=='E' ){
    z += incr;
    if( *z=='+' || *z=='-' ) z += incr;
    if( !isdigit(*(u8*)z) ) return 0;
    while( isdigit(*(u8*)z) ){ z += incr; }
    if( realnum ) *realnum = 1;
  }
  return *z==0;
}

/*
** The string z[] is an ascii representation of a real number.
** Convert this string to a double.
**
** This routine assumes that z[] really is a valid number.  If it
** is not, the result is undefined.
**
** This routine is used instead of the library atof() function because
** the library atof() might want to use "," as the decimal point instead
** of "." depending on how locale is set.  But that would cause problems
** for SQL.  So this routine always uses "." regardless of locale.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3AtoF(const char *z, double *pResult){
#ifndef VTK_SQLITE_OMIT_FLOATING_POINT
  int sign = 1;
  const char *zBegin = z;
  LONGDOUBLE_TYPE v1 = 0.0;
  while( isspace(*(u8*)z) ) z++;
  if( *z=='-' ){
    sign = -1;
    z++;
  }else if( *z=='+' ){
    z++;
  }
  while( isdigit(*(u8*)z) ){
    v1 = v1*10.0 + (*z - '0');
    z++;
  }
  if( *z=='.' ){
    LONGDOUBLE_TYPE divisor = 1.0;
    z++;
    while( isdigit(*(u8*)z) ){
      v1 = v1*10.0 + (*z - '0');
      divisor *= 10.0;
      z++;
    }
    v1 /= divisor;
  }
  if( *z=='e' || *z=='E' ){
    int esign = 1;
    int eval = 0;
    LONGDOUBLE_TYPE scale = 1.0;
    z++;
    if( *z=='-' ){
      esign = -1;
      z++;
    }else if( *z=='+' ){
      z++;
    }
    while( isdigit(*(u8*)z) ){
      eval = eval*10 + *z - '0';
      z++;
    }
    while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
    while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
    while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
    while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
    if( esign<0 ){
      v1 /= scale;
    }else{
      v1 *= scale;
    }
  }
  *pResult = (double)(sign<0 ? -v1 : v1);
  return z - zBegin;
#else
  return vtk_sqlite3Atoi64(z, pResult);
#endif /* VTK_SQLITE_OMIT_FLOATING_POINT */
}

/*
** Compare the 19-character string zNum against the text representation
** value 2^63:  9223372036854775808.  Return negative, zero, or positive
** if zNum is less than, equal to, or greater than the string.
**
** Unlike memcmp() this routine is guaranteed to return the difference
** in the values of the last digit if the only difference is in the
** last digit.  So, for example,
**
**      compare2pow63("9223372036854775800")
**
** will return -8.
*/
static int compare2pow63(const char *zNum){
  int c;
  c = memcmp(zNum,"922337203685477580",18);
  if( c==0 ){
    c = zNum[18] - '8';
  }
  return c;
}


/*
** Return TRUE if zNum is a 64-bit signed integer and write
** the value of the integer into *pNum.  If zNum is not an integer
** or is an integer that is too large to be expressed with 64 bits,
** then return false.
**
** When this routine was originally written it dealt with only
** 32-bit numbers.  At that time, it was much faster than the
** atoi() library routine in RedHat 7.2.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3Atoi64(const char *zNum, i64 *pNum){
  i64 v = 0;
  int neg;
  int i, c;
  while( isspace(*(u8*)zNum) ) zNum++;
  if( *zNum=='-' ){
    neg = 1;
    zNum++;
  }else if( *zNum=='+' ){
    neg = 0;
    zNum++;
  }else{
    neg = 0;
  }
  while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
  for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
    v = v*10 + c - '0';
  }
  *pNum = neg ? -v : v;
  if( c!=0 || i==0 || i>19 ){
    /* zNum is empty or contains non-numeric text or is longer
    ** than 19 digits (thus guaranting that it is too large) */
    return 0;
  }else if( i<19 ){
    /* Less than 19 digits, so we know that it fits in 64 bits */
    return 1;
  }else{
    /* 19-digit numbers must be no larger than 9223372036854775807 if positive
    ** or 9223372036854775808 if negative.  Note that 9223372036854665808
    ** is 2^63. */
    return compare2pow63(zNum)<neg;
  }
}

/*
** The string zNum represents an integer.  There might be some other
** information following the integer too, but that part is ignored.
** If the integer that the prefix of zNum represents will fit in a
** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
**
** This routine returns FALSE for the string -9223372036854775808 even that
** that number will, in theory fit in a 64-bit integer.  Positive
** 9223373036854775808 will not fit in 64 bits.  So it seems safer to return
** false.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3FitsIn64Bits(const char *zNum){
  int i, c;
  int neg = 0;
  if( *zNum=='-' ){
    neg = 1;
    zNum++;
  }else if( *zNum=='+' ){
    zNum++;
  }
  while( *zNum=='0' ){
    zNum++;   /* Skip leading zeros.  Ticket #2454 */
  }
  for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
  if( i<19 ){
    /* Guaranteed to fit if less than 19 digits */
    return 1;
  }else if( i>19 ){
    /* Guaranteed to be too big if greater than 19 digits */
    return 0;
  }else{
    /* Compare against 2^63. */
    return compare2pow63(zNum)<neg;
  }
}

/*
** If zNum represents an integer that will fit in 32-bits, then set
** *pValue to that integer and return true.  Otherwise return false.
**
** Any non-numeric characters that following zNum are ignored.
** This is different from vtk_sqlite3Atoi64() which requires the
** input number to be zero-terminated.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3GetInt32(const char *zNum, int *pValue){
  vtk_sqlite_int64 v = 0;
  int i, c;
  int neg = 0;
  if( zNum[0]=='-' ){
    neg = 1;
    zNum++;
  }else if( zNum[0]=='+' ){
    zNum++;
  }
  while( zNum[0]=='0' ) zNum++;
  for(i=0; i<10 && (c = zNum[i] - '0')>=0 && c<=9; i++){
    v = v*10 + c;
  }
  if( i>9 ){
    return 0;
  }
  if( v-neg>2147483647 ){
    return 0;
  }
  if( neg ){
    v = -v;
  }
  *pValue = (int)v;
  return 1;
}

/*
** Check to make sure we have a valid db pointer.  This test is not
** foolproof but it does provide some measure of protection against
** misuse of the interface such as passing in db pointers that are
** NULL or which have been previously closed.  If this routine returns
** TRUE it means that the db pointer is invalid and should not be
** dereferenced for any reason.  The calling function should invoke
** VTK_SQLITE_MISUSE immediately.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3SafetyCheck(vtk_sqlite3 *db){
  int magic;
  if( db==0 ) return 1;
  magic = db->magic;
  if( magic!=(int)VTK_SQLITE_MAGIC_CLOSED &&
      magic!=(int)VTK_SQLITE_MAGIC_OPEN &&
      magic!=(int)VTK_SQLITE_MAGIC_BUSY ) return 1;
  return 0;
}

/*
** The variable-length integer encoding is as follows:
**
** KEY:
**         A = 0xxxxxxx    7 bits of data and one flag bit
**         B = 1xxxxxxx    7 bits of data and one flag bit
**         C = xxxxxxxx    8 bits of data
**
**  7 bits - A
** 14 bits - BA
** 21 bits - BBA
** 28 bits - BBBA
** 35 bits - BBBBA
** 42 bits - BBBBBA
** 49 bits - BBBBBBA
** 56 bits - BBBBBBBA
** 64 bits - BBBBBBBBC
*/

/*
** Write a 64-bit variable-length integer to memory starting at p[0].
** The length of data write will be between 1 and 9 bytes.  The number
** of bytes written is returned.
**
** A variable-length integer consists of the lower 7 bits of each byte
** for all bytes that have the 8th bit set and one byte with the 8th
** bit clear.  Except, if we get to the 9th byte, it stores the full
** 8 bits and is the last byte.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3PutVarint(unsigned char *p, u64 v){
  int i, j, n;
  u8 buf[10];
  if( v & (((u64)0xff000000)<<32) ){
    p[8] = (unsigned char) v;
    v >>= 8;
    for(i=7; i>=0; i--){
      p[i] = (unsigned char) ((v & 0x7f) | 0x80);
      v >>= 7;
    }
    return 9;
  }    
  n = 0;
  do{
    buf[n++] = (u8) ((v & 0x7f) | 0x80);
    v >>= 7;
  }while( v!=0 );
  buf[0] &= 0x7f;
  assert( n<=9 );
  for(i=0, j=n-1; j>=0; j--, i++){
    p[i] = buf[j];
  }
  return n;
}

/*
** Read a 64-bit variable-length integer from memory starting at p[0].
** Return the number of bytes read.  The value is stored in *v.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3GetVarint(const unsigned char *p, u64 *v){
  u32 x;
  u64 x64;
  int n;
  unsigned char c;
  if( ((c = p[0]) & 0x80)==0 ){
    *v = c;
    return 1;
  }
  x = c & 0x7f;
  if( ((c = p[1]) & 0x80)==0 ){
    *v = (x<<7) | c;
    return 2;
  }
  x = (x<<7) | (c&0x7f);
  if( ((c = p[2]) & 0x80)==0 ){
    *v = (x<<7) | c;
    return 3;
  }
  x = (x<<7) | (c&0x7f);
  if( ((c = p[3]) & 0x80)==0 ){
    *v = (x<<7) | c;
    return 4;
  }
  x64 = (x<<7) | (c&0x7f);
  n = 4;
  do{
    c = p[n++];
    if( n==9 ){
      x64 = (x64<<8) | c;
      break;
    }
    x64 = (x64<<7) | (c&0x7f);
  }while( (c & 0x80)!=0 );
  *v = x64;
  return n;
}

/*
** Read a 32-bit variable-length integer from memory starting at p[0].
** Return the number of bytes read.  The value is stored in *v.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3GetVarint32(const unsigned char *p, u32 *v){
  u32 x;
  int n;
  unsigned char c;
  if( ((signed char*)p)[0]>=0 ){
    *v = p[0];
    return 1;
  }
  x = p[0] & 0x7f;
  if( ((signed char*)p)[1]>=0 ){
    *v = (x<<7) | p[1];
    return 2;
  }
  x = (x<<7) | (p[1] & 0x7f);
  n = 2;
  do{
    x = (x<<7) | ((c = p[n++])&0x7f);
  }while( (c & 0x80)!=0 && n<9 );
  *v = x;
  return n;
}

/*
** Return the number of bytes that will be needed to store the given
** 64-bit integer.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3VarintLen(u64 v){
  int i = 0;
  do{
    i++;
    v >>= 7;
  }while( v!=0 && i<9 );
  return i;
}


/*
** Read or write a four-byte big-endian integer value.
*/
VTK_SQLITE_PRIVATE u32 vtk_sqlite3Get4byte(const u8 *p){
  return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
}
VTK_SQLITE_PRIVATE void vtk_sqlite3Put4byte(unsigned char *p, u32 v){
  p[0] = (unsigned char)(v>>24);
  p[1] = (unsigned char)(v>>16);
  p[2] = (unsigned char)(v>>8);
  p[3] = (unsigned char)(v);
}



#if !defined(VTK_SQLITE_OMIT_BLOB_LITERAL) || defined(VTK_SQLITE_HAS_CODEC) \
    || defined(VTK_SQLITE_TEST)
/*
** Translate a single byte of Hex into an integer.
*/
static int hexToInt(int h){
  if( h>='0' && h<='9' ){
    return h - '0';
  }else if( h>='a' && h<='f' ){
    return h - 'a' + 10;
  }else{
    assert( h>='A' && h<='F' );
    return h - 'A' + 10;
  }
}
#endif /* !VTK_SQLITE_OMIT_BLOB_LITERAL || VTK_SQLITE_HAS_CODEC || VTK_SQLITE_TEST */

#if !defined(VTK_SQLITE_OMIT_BLOB_LITERAL) || defined(VTK_SQLITE_HAS_CODEC)
/*
** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
** value.  Return a pointer to its binary value.  Space to hold the
** binary value has been obtained from malloc and must be freed by
** the calling routine.
*/
VTK_SQLITE_PRIVATE void *vtk_sqlite3HexToBlob(const char *z){
  char *zBlob;
  int i;
  int n = strlen(z);
  if( n%2 ) return 0;

  zBlob = (char *)vtk_sqliteMalloc(n/2);
  if( zBlob ){
    for(i=0; i<n; i+=2){
      zBlob[i/2] = (char)((hexToInt(z[i])<<4) | hexToInt(z[i+1]));
    }
  }
  return zBlob;
}
#endif /* !VTK_SQLITE_OMIT_BLOB_LITERAL || VTK_SQLITE_HAS_CODEC */


/*
** Change the vtk_sqlite.magic from VTK_SQLITE_MAGIC_OPEN to VTK_SQLITE_MAGIC_BUSY.
** Return an error (non-zero) if the magic was not VTK_SQLITE_MAGIC_OPEN
** when this routine is called.
**
** This routine is called when entering an Vtk_Sqlite API.  The VTK_SQLITE_MAGIC_OPEN
** value indicates that the database connection passed into the API is
** open and is not being used by another thread.  By changing the value
** to VTK_SQLITE_MAGIC_BUSY we indicate that the connection is in use.
** vtk_sqlite3SafetyOff() below will change the value back to VTK_SQLITE_MAGIC_OPEN
** when the API exits. 
**
** This routine is a attempt to detect if two threads use the
** same vtk_sqlite* pointer at the same time.  There is a race 
** condition so it is possible that the error is not detected.
** But usually the problem will be seen.  The result will be an
** error which can be used to debug the application that is
** using Vtk_Sqlite incorrectly.
**
** Ticket #202:  If db->magic is not a valid open value, take care not
** to modify the db structure at all.  It could be that db is a stale
** pointer.  In other words, it could be that there has been a prior
** call to vtk_sqlite3_close(db) and db has been deallocated.  And we do
** not want to write into deallocated memory.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3SafetyOn(vtk_sqlite3 *db){
  if( db->magic==(int)VTK_SQLITE_MAGIC_OPEN ){
    db->magic = VTK_SQLITE_MAGIC_BUSY;
    return 0;
  }else if( db->magic==(int)VTK_SQLITE_MAGIC_BUSY ){
    db->magic = VTK_SQLITE_MAGIC_ERROR;
    db->u1.isInterrupted = 1;
  }
  return 1;
}

/*
** Change the magic from VTK_SQLITE_MAGIC_BUSY to VTK_SQLITE_MAGIC_OPEN.
** Return an error (non-zero) if the magic was not VTK_SQLITE_MAGIC_BUSY
** when this routine is called.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3SafetyOff(vtk_sqlite3 *db){
  if( db->magic==(int)VTK_SQLITE_MAGIC_BUSY ){
    db->magic = VTK_SQLITE_MAGIC_OPEN;
    return 0;
  }else {
    db->magic = VTK_SQLITE_MAGIC_ERROR;
    db->u1.isInterrupted = 1;
    return 1;
  }
}

/*
** Return a pointer to the ThreadData associated with the calling thread.
*/
VTK_SQLITE_PRIVATE ThreadData *vtk_sqlite3ThreadData(){
  ThreadData *p = (ThreadData*)vtk_sqlite3OsThreadSpecificData(1);
  if( !p ){
    vtk_sqlite3FailedMalloc();
  }
  return p;
}

/*
** Return a pointer to the ThreadData associated with the calling thread.
** If no ThreadData has been allocated to this thread yet, return a pointer
** to a substitute ThreadData structure that is all zeros. 
*/
VTK_SQLITE_PRIVATE const ThreadData *vtk_sqlite3ThreadDataReadOnly(){
  static const ThreadData zeroData =  /* Initializer to silence warnings
                                      ** from broken compilers */
#if defined(VTK_SQLITE_ENABLE_MEMORY_MANAGEMENT)
#if defined(VTK_SQLITE_OMIT_SHARED_CACHE)
  {0, 0, 0, 0};
#else
  {0, 0, 0, 0, 0, 0};
#endif
#elif defined(VTK_SQLITE_OMIT_SHARED_CACHE)
  {0};
#else
  {0, 0, 0};
#endif
  const ThreadData *pTd = vtk_sqlite3OsThreadSpecificData(0);
  return pTd ? pTd : &zeroData;
}

/*
** Check to see if the ThreadData for this thread is all zero.  If it
** is, then deallocate it. 
*/
VTK_SQLITE_PRIVATE void vtk_sqlite3ReleaseThreadData(){
  vtk_sqlite3OsThreadSpecificData(-1);
}

/************** End of util.c ************************************************/
/************** Begin file hash.c ********************************************/
/*
** 2001 September 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This is the implementation of generic hash-tables
** used in Vtk_Sqlite.
**
** $Id: vtk_sqlite3.c,v 1.15 2007/09/20 18:33:36 king Exp $
*/

/* Turn bulk memory into a hash table object by initializing the
** fields of the Hash structure.
**
** "pNew" is a pointer to the hash table that is to be initialized.
** keyClass is one of the constants VTK_SQLITE_HASH_INT, VTK_SQLITE_HASH_POINTER,
** VTK_SQLITE_HASH_BINARY, or VTK_SQLITE_HASH_STRING.  The value of keyClass 
** determines what kind of key the hash table will use.  "copyKey" is
** true if the hash table should make its own private copy of keys and
** false if it should just use the supplied pointer.  CopyKey only makes
** sense for VTK_SQLITE_HASH_STRING and VTK_SQLITE_HASH_BINARY and is ignored
** for other key classes.
*/
VTK_SQLITE_PRIVATE void vtk_sqlite3HashInit(Hash *pNew, int keyClass, int copyKey){
  assert( pNew!=0 );
  assert( keyClass>=VTK_SQLITE_HASH_STRING && keyClass<=VTK_SQLITE_HASH_BINARY );
  pNew->keyClass = (char)(keyClass);
#if 0
  if( keyClass==VTK_SQLITE_HASH_POINTER || keyClass==VTK_SQLITE_HASH_INT ) copyKey = 0;
#endif
  pNew->copyKey = (char)(copyKey);
  pNew->first = 0;
  pNew->count = 0;
  pNew->htsize = 0;
  pNew->ht = 0;
  pNew->xMalloc = vtk_sqlite3MallocX;
  pNew->xFree = vtk_sqlite3FreeX;
}

/* Remove all entries from a hash table.  Reclaim all memory.
** Call this routine to delete a hash table or to reset a hash table
** to the empty state.
*/
VTK_SQLITE_PRIVATE void vtk_sqlite3HashClear(Hash *pH){
  HashElem *elem;         /* For looping over all elements of the table */

  assert( pH!=0 );
  elem = pH->first;
  pH->first = 0;
  if( pH->ht ) pH->xFree(pH->ht);
  pH->ht = 0;
  pH->htsize = 0;
  while( elem ){
    HashElem *next_elem = elem->next;
    if( pH->copyKey && elem->pKey ){
      pH->xFree(elem->pKey);
    }
    pH->xFree(elem);
    elem = next_elem;
  }
  pH->count = 0;
}

#if 0 /* NOT USED */
/*
** Hash and comparison functions when the mode is VTK_SQLITE_HASH_INT
*/
static int intHash(const void *pKey, int nKey){
  return nKey ^ (nKey<<8) ^ (nKey>>8);
}
static int intCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  return n2 - n1;
}
#endif

#if 0 /* NOT USED */
/*
** Hash and comparison functions when the mode is VTK_SQLITE_HASH_POINTER
*/
static int ptrHash(const void *pKey, int nKey){
  uptr x = Addr(pKey);
  return x ^ (x<<8) ^ (x>>8);
}
static int ptrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  if( pKey1==pKey2 ) return 0;
  if( pKey1<pKey2 ) return -1;
  return 1;
}
#endif

/*
** Hash and comparison functions when the mode is VTK_SQLITE_HASH_STRING
*/
static int strHash(const void *pKey, int nKey){
  const char *z = (const char *)pKey;
  int h = 0;
  if( nKey<=0 ) nKey = strlen(z);
  while( nKey > 0  ){
    h = (h<<3) ^ h ^ vtk_sqlite3UpperToLower[(unsigned char)*z++];
    nKey--;
  }
  return h & 0x7fffffff;
}
static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  if( n1!=n2 ) return 1;
  return vtk_sqlite3StrNICmp((const char*)pKey1,(const char*)pKey2,n1);
}

/*
** Hash and comparison functions when the mode is VTK_SQLITE_HASH_BINARY
*/
static int binHash(const void *pKey, int nKey){
  int h = 0;
  const char *z = (const char *)pKey;
  while( nKey-- > 0 ){
    h = (h<<3) ^ h ^ *(z++);
  }
  return h & 0x7fffffff;
}
static int binCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  if( n1!=n2 ) return 1;
  return memcmp(pKey1,pKey2,n1);
}

/*
** Return a pointer to the appropriate hash function given the key class.
**
** The C syntax in this function definition may be unfamilar to some 
** programmers, so we provide the following additional explanation:
**
** The name of the function is "hashFunction".  The function takes a
** single parameter "keyClass".  The return value of hashFunction()
** is a pointer to another function.  Specifically, the return value
** of hashFunction() is a pointer to a function that takes two parameters
** with types "const void*" and "int" and returns an "int".
*/
static int (*hashFunction(int keyClass))(const void*,int){
#if 0  /* HASH_INT and HASH_POINTER are never used */
  switch( keyClass ){
    case VTK_SQLITE_HASH_INT:     return &intHash;
    case VTK_SQLITE_HASH_POINTER: return &ptrHash;
    case VTK_SQLITE_HASH_STRING:  return &strHash;
    case VTK_SQLITE_HASH_BINARY:  return &binHash;;
    default: break;
  }
  return 0;
#else
  if( keyClass==VTK_SQLITE_HASH_STRING ){
    return &strHash;
  }else{
    assert( keyClass==VTK_SQLITE_HASH_BINARY );
    return &binHash;
  }
#endif
}

/*
** Return a pointer to the appropriate hash function given the key class.
**
** For help in interpreted the obscure C code in the function definition,
** see the header comment on the previous function.
*/
static int (*compareFunction(int keyClass))(const void*,int,const void*,int){
#if 0 /* HASH_INT and HASH_POINTER are never used */
  switch( keyClass ){
    case VTK_SQLITE_HASH_INT:     return &intCompare;
    case VTK_SQLITE_HASH_POINTER: return &ptrCompare;
    case VTK_SQLITE_HASH_STRING:  return &strCompare;
    case VTK_SQLITE_HASH_BINARY:  return &binCompare;
    default: break;
  }
  return 0;
#else
  if( keyClass==VTK_SQLITE_HASH_STRING ){
    return &strCompare;
  }else{
    assert( keyClass==VTK_SQLITE_HASH_BINARY );
    return &binCompare;
  }
#endif
}

/* Link an element into the hash table
*/
static void insertElement(
  Hash *pH,              /* The complete hash table */
  struct _ht *pEntry,    /* The entry into which pNew is inserted */
  HashElem *pNew         /* The element to be inserted */
){
  HashElem *pHead;       /* First element already in pEntry */
  pHead = pEntry->chain;
  if( pHead ){
    pNew->next = pHead;
    pNew->prev = pHead->prev;
    if( pHead->prev ){ pHead->prev->next = pNew; }
    else             { pH->first = pNew; }
    pHead->prev = pNew;
  }else{
    pNew->next = pH->first;
    if( pH->first ){ pH->first->prev = pNew; }
    pNew->prev = 0;
    pH->first = pNew;
  }
  pEntry->count++;
  pEntry->chain = pNew;
}


/* Resize the hash table so that it cantains "new_size" buckets.
** "new_size" must be a power of 2.  The hash table might fail 
** to resize if vtk_sqliteMalloc() fails.
*/
static void rehash(Hash *pH, int new_size){
  struct _ht *new_ht;            /* The new hash table */
  HashElem *elem, *next_elem;    /* For looping over existing elements */
  int (*xHash)(const void*,int); /* The hash function */

  assert( (new_size & (new_size-1))==0 );
  new_ht = (struct _ht *)pH->xMalloc( new_size*sizeof(struct _ht) );
  if( new_ht==0 ) return;
  if( pH->ht ) pH->xFree(pH->ht);
  pH->ht = new_ht;
  pH->htsize = new_size;
  xHash = hashFunction(pH->keyClass);
  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
    next_elem = elem->next;
    insertElement(pH, &new_ht[h], elem);
  }
}

/* This function (for internal use only) locates an element in an
** hash table that matches the given key.  The hash for this key has
** already been computed and is passed as the 4th parameter.
*/
static HashElem *findElementGivenHash(
  const Hash *pH,     /* The pH to be searched */
  const void *pKey,   /* The key we are searching for */
  int nKey,
  int h               /* The hash for this key. */
){
  HashElem *elem;                /* Used to loop thru the element list */
  int count;                     /* Number of elements left to test */
  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */

  if( pH->ht ){
    struct _ht *pEntry = &pH->ht[h];
    elem = pEntry->chain;
    count = pEntry->count;
    xCompare = compareFunction(pH->keyClass);
    while( count-- && elem ){
      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
        return elem;
      }
      elem = elem->next;
    }
  }
  return 0;
}

/* Remove a single entry from the hash table given a pointer to that
** element and a hash on the element's key.
*/
static void removeElementGivenHash(
  Hash *pH,         /* The pH containing "elem" */
  HashElem* elem,   /* The element to be removed from the pH */
  int h             /* Hash value for the element */
){
  struct _ht *pEntry;
  if( elem->prev ){
    elem->prev->next = elem->next; 
  }else{
    pH->first = elem->next;
  }
  if( elem->next ){
    elem->next->prev = elem->prev;
  }
  pEntry = &pH->ht[h];
  if( pEntry->chain==elem ){
    pEntry->chain = elem->next;
  }
  pEntry->count--;
  if( pEntry->count<=0 ){
    pEntry->chain = 0;
  }
  if( pH->copyKey ){
    pH->xFree(elem->pKey);
  }
  pH->xFree( elem );
  pH->count--;
  if( pH->count<=0 ){
    assert( pH->first==0 );
    assert( pH->count==0 );
    vtk_sqlite3HashClear(pH);
  }
}

/* Attempt to locate an element of the hash table pH with a key
** that matches pKey,nKey.  Return the data for this element if it is
** found, or NULL if there is no match.
*/
VTK_SQLITE_PRIVATE void *vtk_sqlite3HashFind(const Hash *pH, const void *pKey, int nKey){
  int h;             /* A hash on key */
  HashElem *elem;    /* The element that matches key */
  int (*xHash)(const void*,int);  /* The hash function */

  if( pH==0 || pH->ht==0 ) return 0;
  xHash = hashFunction(pH->keyClass);
  assert( xHash!=0 );
  h = (*xHash)(pKey,nKey);
  assert( (pH->htsize & (pH->htsize-1))==0 );
  elem = findElementGivenHash(pH,pKey,nKey, h & (pH->htsize-1));
  return elem ? elem->data : 0;
}

/* Insert an element into the hash table pH.  The key is pKey,nKey
** and the data is "data".
**
** If no element exists with a matching key, then a new
** element is created.  A copy of the key is made if the copyKey
** flag is set.  NULL is returned.
**
** If another element already exists with the same key, then the
** new data replaces the old data and the old data is returned.
** The key is not copied in this instance.  If a malloc fails, then
** the new data is returned and the hash table is unchanged.
**
** If the "data" parameter to this function is NULL, then the
** element corresponding to "key" is removed from the hash table.
*/
VTK_SQLITE_PRIVATE void *vtk_sqlite3HashInsert(Hash *pH, const void *pKey, int nKey, void *data){
  int hraw;             /* Raw hash value of the key */
  int h;                /* the hash of the key modulo hash table size */
  HashElem *elem;       /* Used to loop thru the element list */
  HashElem *new_elem;   /* New element added to the pH */
  int (*xHash)(const void*,int);  /* The hash function */

  assert( pH!=0 );
  xHash = hashFunction(pH->keyClass);
  assert( xHash!=0 );
  hraw = (*xHash)(pKey, nKey);
  assert( (pH->htsize & (pH->htsize-1))==0 );
  h = hraw & (pH->htsize-1);
  elem = findElementGivenHash(pH,pKey,nKey,h);
  if( elem ){
    void *old_data = elem->data;
    if( data==0 ){
      removeElementGivenHash(pH,elem,h);
    }else{
      elem->data = data;
    }
    return old_data;
  }
  if( data==0 ) return 0;
  new_elem = (HashElem*)pH->xMalloc( sizeof(HashElem) );
  if( new_elem==0 ) return data;
  if( pH->copyKey && pKey!=0 ){
    new_elem->pKey = pH->xMalloc( nKey );
    if( new_elem->pKey==0 ){
      pH->xFree(new_elem);
      return data;
    }
    memcpy((void*)new_elem->pKey, pKey, nKey);
  }else{
    new_elem->pKey = (void*)pKey;
  }
  new_elem->nKey = nKey;
  pH->count++;
  if( pH->htsize==0 ){
    rehash(pH,8);
    if( pH->htsize==0 ){
      pH->count = 0;
      if( pH->copyKey ){
        pH->xFree(new_elem->pKey);
      }
      pH->xFree(new_elem);
      return data;
    }
  }
  if( pH->count > pH->htsize ){
    rehash(pH,pH->htsize*2);
  }
  assert( pH->htsize>0 );
  assert( (pH->htsize & (pH->htsize-1))==0 );
  h = hraw & (pH->htsize-1);
  insertElement(pH, &pH->ht[h], new_elem);
  new_elem->data = data;
  return 0;
}

/************** End of hash.c ************************************************/
/************** Begin file opcodes.c *****************************************/
/* Automatically generated.  Do not edit */
/* See the mkopcodec.awk script for details. */
#if !defined(VTK_SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(VTK_SQLITE_DEBUG)
const char *const vtk_sqlite3OpcodeNames[] = { "?",
 /*   1 */ "MemLoad",
 /*   2 */ "VNext",
 /*   3 */ "Column",
 /*   4 */ "SetCookie",
 /*   5 */ "IfMemPos",
 /*   6 */ "Sequence",
 /*   7 */ "MoveGt",
 /*   8 */ "RowKey",
 /*   9 */ "OpenWrite",
 /*  10 */ "If",
 /*  11 */ "Pop",
 /*  12 */ "VRowid",
 /*  13 */ "CollSeq",
 /*  14 */ "OpenRead",
 /*  15 */ "Expire",
 /*  16 */ "Not",
 /*  17 */ "AutoCommit",
 /*  18 */ "IntegrityCk",
 /*  19 */ "Sort",
 /*  20 */ "Function",
 /*  21 */ "Noop",
 /*  22 */ "Return",
 /*  23 */ "NewRowid",
 /*  24 */ "IfMemNeg",
 /*  25 */ "Variable",
 /*  26 */ "String",
 /*  27 */ "RealAffinity",
 /*  28 */ "VRename",
 /*  29 */ "ParseSchema",
 /*  30 */ "VOpen",
 /*  31 */ "Close",
 /*  32 */ "CreateIndex",
 /*  33 */ "IsUnique",
 /*  34 */ "NotFound",
 /*  35 */ "Int64",
 /*  36 */ "MustBeInt",
 /*  37 */ "Halt",
 /*  38 */ "Rowid",
 /*  39 */ "IdxLT",
 /*  40 */ "AddImm",
 /*  41 */ "Statement",
 /*  42 */ "RowData",
 /*  43 */ "MemMax",
 /*  44 */ "Push",
 /*  45 */ "NotExists",
 /*  46 */ "MemIncr",
 /*  47 */ "Gosub",
 /*  48 */ "Integer",
 /*  49 */ "MemInt",
 /*  50 */ "Prev",
 /*  51 */ "VColumn",
 /*  52 */ "CreateTable",
 /*  53 */ "Last",
 /*  54 */ "IncrVacuum",
 /*  55 */ "IdxRowid",
 /*  56 */ "MakeIdxRec",
 /*  57 */ "ResetCount",
 /*  58 */ "FifoWrite",
 /*  59 */ "Callback",
 /*  60 */ "Or",
 /*  61 */ "And",
 /*  62 */ "ContextPush",
 /*  63 */ "DropTrigger",
 /*  64 */ "DropIndex",
 /*  65 */ "IsNull",
 /*  66 */ "NotNull",
 /*  67 */ "Ne",
 /*  68 */ "Eq",
 /*  69 */ "Gt",
 /*  70 */ "Le",
 /*  71 */ "Lt",
 /*  72 */ "Ge",
 /*  73 */ "IdxGE",
 /*  74 */ "BitAnd",
 /*  75 */ "BitOr",
 /*  76 */ "ShiftLeft",
 /*  77 */ "ShiftRight",
 /*  78 */ "Add",
 /*  79 */ "Subtract",
 /*  80 */ "Multiply",
 /*  81 */ "Divide",
 /*  82 */ "Remainder",
 /*  83 */ "Concat",
 /*  84 */ "IdxDelete",
 /*  85 */ "Negative",
 /*  86 */ "Vacuum",
 /*  87 */ "BitNot",
 /*  88 */ "String8",
 /*  89 */ "MoveLe",
 /*  90 */ "IfNot",
 /*  91 */ "DropTable",
 /*  92 */ "MakeRecord",
 /*  93 */ "Delete",
 /*  94 */ "AggFinal",
 /*  95 */ "Dup",
 /*  96 */ "Goto",
 /*  97 */ "TableLock",
 /*  98 */ "FifoRead",
 /*  99 */ "Clear",
 /* 100 */ "IdxGT",
 /* 101 */ "MoveLt",
 /* 102 */ "VerifyCookie",
 /* 103 */ "AggStep",
 /* 104 */ "Pull",
 /* 105 */ "SetNumColumns",
 /* 106 */ "AbsValue",
 /* 107 */ "Transaction",
 /* 108 */ "VFilter",
 /* 109 */ "VDestroy",
 /* 110 */ "ContextPop",
 /* 111 */ "Next",
 /* 112 */ "IdxInsert",
 /* 113 */ "Distinct",
 /* 114 */ "Insert",
 /* 115 */ "Destroy",
 /* 116 */ "ReadCookie",
 /* 117 */ "ForceInt",
 /* 118 */ "LoadAnalysis",
 /* 119 */ "Explain",
 /* 120 */ "IfMemZero",
 /* 121 */ "OpenPseudo",
 /* 122 */ "OpenEphemeral",
 /* 123 */ "Null",
 /* 124 */ "Blob",
 /* 125 */ "Real",
 /* 126 */ "HexBlob",
 /* 127 */ "MemStore",
 /* 128 */ "Rewind",
 /* 129 */ "MoveGe",
 /* 130 */ "VBegin",
 /* 131 */ "VUpdate",
 /* 132 */ "VCreate",
 /* 133 */ "MemMove",
 /* 134 */ "MemNull",
 /* 135 */ "Found",
 /* 136 */ "NullRow",
 /* 137 */ "NotUsed_137",
 /* 138 */ "ToText",
 /* 139 */ "ToBlob",
 /* 140 */ "ToNumeric",
 /* 141 */ "ToInt",
 /* 142 */ "ToReal",
};
#endif

/************** End of opcodes.c *********************************************/
/************** Begin file os_os2.c ******************************************/
/*
** 2006 Feb 14
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains code that is specific to OS/2.
*/


#if OS_OS2

/*
** Macros used to determine whether or not to use threads.
*/
#if defined(THREADSAFE) && THREADSAFE
# define VTK_SQLITE_OS2_THREADS 1
#endif

/*
** Include code that is common to all os_*.c files
*/
/************** Include os_common.h in the middle of os_os2.c ****************/
/************** Begin file os_common.h ***************************************/
/*
** 2004 May 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains macros and a little bit of code that is common to
** all of the platform-specific files (os_*.c) and is #included into those
** files.
**
** This file should be #included by the os_*.c files only.  It is not a
** general purpose header file.
*/

/*
** At least two bugs have slipped in because we changed the MEMORY_DEBUG
** macro to VTK_SQLITE_DEBUG and some older makefiles have not yet made the
** switch.  The following code should catch this problem at compile-time.
*/
#ifdef MEMORY_DEBUG
# error "The MEMORY_DEBUG macro is obsolete.  Use VTK_SQLITE_DEBUG instead."
#endif


/*
 * When testing, this global variable stores the location of the
 * pending-byte in the database file.
 */
#ifdef VTK_SQLITE_TEST
unsigned int vtk_sqlite3_pending_byte = 0x40000000;
#endif

int vtk_sqlite3_os_trace = 0;
#ifdef VTK_SQLITE_DEBUG
#define OSTRACE1(X)         if( vtk_sqlite3_os_trace ) vtk_sqlite3DebugPrintf(X)
#define OSTRACE2(X,Y)       if( vtk_sqlite3_os_trace ) vtk_sqlite3DebugPrintf(X,Y)
#define OSTRACE3(X,Y,Z)     if( vtk_sqlite3_os_trace ) vtk_sqlite3DebugPrintf(X,Y,Z)
#define OSTRACE4(X,Y,Z,A)   if( vtk_sqlite3_os_trace ) vtk_sqlite3DebugPrintf(X,Y,Z,A)
#define OSTRACE5(X,Y,Z,A,B) if( vtk_sqlite3_os_trace ) vtk_sqlite3DebugPrintf(X,Y,Z,A,B)
#define OSTRACE6(X,Y,Z,A,B,C) \
    if(vtk_sqlite3_os_trace) vtk_sqlite3DebugPrintf(X,Y,Z,A,B,C)
#define OSTRACE7(X,Y,Z,A,B,C,D) \
    if(vtk_sqlite3_os_trace) vtk_sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
#else
#define OSTRACE1(X)
#define OSTRACE2(X,Y)
#define OSTRACE3(X,Y,Z)
#define OSTRACE4(X,Y,Z,A)
#define OSTRACE5(X,Y,Z,A,B)
#define OSTRACE6(X,Y,Z,A,B,C)
#define OSTRACE7(X,Y,Z,A,B,C,D)
#endif

/*
** Macros for performance tracing.  Normally turned off.  Only works
** on i486 hardware.
*/
#ifdef VTK_SQLITE_PERFORMANCE_TRACE
__inline__ unsigned long long int hwtime(void){
  unsigned long long int x;
  __asm__("rdtsc\n\t"
          "mov %%edx, %%ecx\n\t"
          :"=A" (x));
  return x;
}
static unsigned long long int g_start;
static unsigned int elapse;
#define TIMER_START       g_start=hwtime()
#define TIMER_END         elapse=hwtime()-g_start
#define TIMER_ELAPSED     elapse
#else
#define TIMER_START
#define TIMER_END
#define TIMER_ELAPSED     0
#endif

/*
** If we compile with the VTK_SQLITE_TEST macro set, then the following block
** of code will give us the ability to simulate a disk I/O error.  This
** is used for testing the I/O recovery logic.
*/
#ifdef VTK_SQLITE_TEST
int vtk_sqlite3_io_error_hit = 0;
int vtk_sqlite3_io_error_pending = 0;
int vtk_sqlite3_io_error_persist = 0;
int vtk_sqlite3_diskfull_pending = 0;
int vtk_sqlite3_diskfull = 0;
#define SimulateIOError(CODE)  \
  if( vtk_sqlite3_io_error_pending || vtk_sqlite3_io_error_hit ) \
     if( vtk_sqlite3_io_error_pending-- == 1 \
         || (vtk_sqlite3_io_error_persist && vtk_sqlite3_io_error_hit) ) \
                { local_ioerr(); CODE; }
static void local_ioerr(){
  IOTRACE(("IOERR\n"));
  vtk_sqlite3_io_error_hit = 1;
}
#define SimulateDiskfullError(CODE) \
   if( vtk_sqlite3_diskfull_pending ){ \
     if( vtk_sqlite3_diskfull_pending == 1 ){ \
       local_ioerr(); \
       vtk_sqlite3_diskfull = 1; \
       vtk_sqlite3_io_error_hit = 1; \
       CODE; \
     }else{ \
       vtk_sqlite3_diskfull_pending--; \
     } \
   }
#else
#define SimulateIOError(A)
#define SimulateDiskfullError(A)
#endif

/*
** When testing, keep a count of the number of open files.
*/
#ifdef VTK_SQLITE_TEST
int vtk_sqlite3_open_file_count = 0;
#define OpenCounter(X)  vtk_sqlite3_open_file_count+=(X)
#else
#define OpenCounter(X)
#endif

/*
** vtk_sqlite3GenericMalloc
** vtk_sqlite3GenericRealloc
** vtk_sqlite3GenericOsFree
** vtk_sqlite3GenericAllocationSize
**
** Implementation of the os level dynamic memory allocation interface in terms
** of the standard malloc(), realloc() and free() found in many operating
** systems. No rocket science here.
**
** There are two versions of these four functions here. The version
** implemented here is only used if memory-management or memory-debugging is
** enabled. This version allocates an extra 8-bytes at the beginning of each
** block and stores the size of the allocation there.
**
** If neither memory-management or debugging is enabled, the second
** set of implementations is used instead.
*/
#if defined(VTK_SQLITE_ENABLE_MEMORY_MANAGEMENT) || defined (VTK_SQLITE_MEMDEBUG)
VTK_SQLITE_PRIVATE void *vtk_sqlite3GenericMalloc(int n){
  char *p = (char *)malloc(n+8);
  assert(n>0);
  assert(sizeof(int)<=8);
  if( p ){
    *(int *)p = n;
    p += 8;
  }
  return (void *)p;
}
VTK_SQLITE_PRIVATE void *vtk_sqlite3GenericRealloc(void *p, int n){
  char *p2 = ((char *)p - 8);
  assert(n>0);
  p2 = (char*)realloc(p2, n+8);
  if( p2 ){
    *(int *)p2 = n;
    p2 += 8;
  }
  return (void *)p2;
}
VTK_SQLITE_PRIVATE void vtk_sqlite3GenericFree(void *p){
  assert(p);
  free((void *)((char *)p - 8));
}
VTK_SQLITE_PRIVATE int vtk_sqlite3GenericAllocationSize(void *p){
  return p ? *(int *)((char *)p - 8) : 0;
}
#else
VTK_SQLITE_PRIVATE void *vtk_sqlite3GenericMalloc(int n){
  char *p = (char *)malloc(n);
  return (void *)p;
}
VTK_SQLITE_PRIVATE void *vtk_sqlite3GenericRealloc(void *p, int n){
  assert(n>0);
  p = realloc(p, n);
  return p;
}
VTK_SQLITE_PRIVATE void vtk_sqlite3GenericFree(void *p){
  assert(p);
  free(p);
}
/* Never actually used, but needed for the linker */
/* We can get rid of this because REDEF_IO is off */
/*
VTK_SQLITE_PRIVATE int vtk_sqlite3GenericAllocationSize(void *p){ (void)p; return 0; }
*/
#endif

/*
** The default size of a disk sector
*/
#ifndef PAGER_SECTOR_SIZE
# define PAGER_SECTOR_SIZE 512
#endif

/************** End of os_common.h *******************************************/
/************** Continuing where we left off in os_os2.c *********************/

/*
** The os2File structure is subclass of OsFile specific for the OS/2
** protability layer.
*/
typedef struct os2File os2File;
struct os2File {
  IoMethod const *pMethod;  /* Always the first entry */
  HFILE h;                  /* Handle for accessing the file */
  int delOnClose;           /* True if file is to be deleted on close */
  char* pathToDel;          /* Name of file to delete on close */
  unsigned char locktype;   /* Type of lock currently held on this file */
};

/*
** Do not include any of the File I/O interface procedures if the
** VTK_SQLITE_OMIT_DISKIO macro is defined (indicating that there database
** will be in-memory only)
*/
#ifndef VTK_SQLITE_OMIT_DISKIO

/*
** Delete the named file
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3Os2Delete( const char *zFilename ){
  APIRET rc = NO_ERROR;

  rc = DosDelete( (PSZ)zFilename );
  OSTRACE2( "DELETE \"%s\"\n", zFilename );
  return rc == NO_ERROR ? VTK_SQLITE_OK : VTK_SQLITE_IOERR;
}

/*
** Return TRUE if the named file exists.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3Os2FileExists( const char *zFilename ){
  FILESTATUS3 fsts3ConfigInfo;
  memset(&fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo));
  return DosQueryPathInfo( (PSZ)zFilename, FIL_STANDARD,
        &fsts3ConfigInfo, sizeof(FILESTATUS3) ) == NO_ERROR;
}

/* Forward declaration */
int allocateOs2File( os2File *pInit, OsFile **pld );

/*
** Attempt to open a file for both reading and writing.  If that
** fails, try opening it read-only.  If the file does not exist,
** try to create it.
**
** On success, a handle for the open file is written to *id
** and *pReadonly is set to 0 if the file was opened for reading and
** writing or 1 if the file was opened read-only.  The function returns
** VTK_SQLITE_OK.
**
** On failure, the function returns VTK_SQLITE_CANTOPEN and leaves
** *id and *pReadonly unchanged.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3Os2OpenReadWrite(
  const char *zFilename,
  OsFile **pld,
  int *pReadonly
){
  os2File  f;
  HFILE    hf;
  ULONG    ulAction;
  APIRET   rc = NO_ERROR;

  assert( *pld == 0 );
  rc = DosOpen( (PSZ)zFilename, &hf, &ulAction, 0L,
            FILE_ARCHIVED | FILE_NORMAL,
                OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS,
                OPEN_FLAGS_FAIL_ON_ERROR | OPEN_FLAGS_RANDOM |
                    OPEN_SHARE_DENYNONE | OPEN_ACCESS_READWRITE, (PEAOP2)NULL );
  if( rc != NO_ERROR ){
    rc = DosOpen( (PSZ)zFilename, &hf, &ulAction, 0L,
            FILE_ARCHIVED | FILE_NORMAL,
                OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS,
                OPEN_FLAGS_FAIL_ON_ERROR | OPEN_FLAGS_RANDOM |
                        OPEN_SHARE_DENYWRITE | OPEN_ACCESS_READONLY, (PEAOP2)NULL );
    if( rc != NO_ERROR ){
        return VTK_SQLITE_CANTOPEN;
    }
    *pReadonly = 1;
  }
  else{
    *pReadonly = 0;
  }
  f.h = hf;
  f.locktype = NO_LOCK;
  f.delOnClose = 0;
  f.pathToDel = NULL;
  OpenCounter(+1);
  OSTRACE3( "OPEN R/W %d \"%s\"\n", hf, zFilename );
  return allocateOs2File( &f, pld );
}


/*
** Attempt to open a new file for exclusive access by this process.
** The file will be opened for both reading and writing.  To avoid
** a potential security problem, we do not allow the file to have
** previously existed.  Nor do we allow the file to be a symbolic
** link.
**
** If delFlag is true, then make arrangements to automatically delete
** the file when it is closed.
**
** On success, write the file handle into *id and return VTK_SQLITE_OK.
**
** On failure, return VTK_SQLITE_CANTOPEN.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3Os2OpenExclusive( const char *zFilename, OsFile **pld, int delFlag ){
  os2File  f;
  HFILE    hf;
  ULONG    ulAction;
  APIRET   rc = NO_ERROR;

  assert( *pld == 0 );
  rc = DosOpen( (PSZ)zFilename, &hf, &ulAction, 0L, FILE_NORMAL,
            OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_REPLACE_IF_EXISTS,
            OPEN_FLAGS_FAIL_ON_ERROR | OPEN_FLAGS_RANDOM |
                OPEN_SHARE_DENYREADWRITE | OPEN_ACCESS_READWRITE, (PEAOP2)NULL );
  if( rc != NO_ERROR ){
    return VTK_SQLITE_CANTOPEN;
  }

  f.h = hf;
  f.locktype = NO_LOCK;
  f.delOnClose = delFlag ? 1 : 0;
  f.pathToDel = delFlag ? vtk_sqlite3OsFullPathname( zFilename ) : NULL;
  OpenCounter( +1 );
  if( delFlag ) DosForceDelete( (PSZ)vtk_sqlite3OsFullPathname( zFilename ) );
  OSTRACE3( "OPEN EX %d \"%s\"\n", hf, vtk_sqlite3OsFullPathname ( zFilename ) );
  return allocateOs2File( &f, pld );
}

/*
** Attempt to open a new file for read-only access.
**
** On success, write the file handle into *id and return VTK_SQLITE_OK.
**
** On failure, return VTK_SQLITE_CANTOPEN.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3Os2OpenReadOnly( const char *zFilename, OsFile **pld ){
  os2File  f;
  HFILE    hf;
  ULONG    ulAction;
  APIRET   rc = NO_ERROR;

  assert( *pld == 0 );
  rc = DosOpen( (PSZ)zFilename, &hf, &ulAction, 0L,
            FILE_NORMAL, OPEN_ACTION_OPEN_IF_EXISTS,
            OPEN_FLAGS_FAIL_ON_ERROR | OPEN_FLAGS_RANDOM |
                OPEN_SHARE_DENYWRITE | OPEN_ACCESS_READONLY, (PEAOP2)NULL );
  if( rc != NO_ERROR ){
    return VTK_SQLITE_CANTOPEN;
  }
  f.h = hf;
  f.locktype = NO_LOCK;
  f.delOnClose = 0;
  f.pathToDel = NULL;
  OpenCounter( +1 );
  OSTRACE3( "OPEN RO %d \"%s\"\n", hf, zFilename );
  return allocateOs2File( &f, pld );
}

/*
** Attempt to open a file descriptor for the directory that contains a
** file.  This file descriptor can be used to fsync() the directory
** in order to make sure the creation of a new file is actually written
** to disk.
**
** This routine is only meaningful for Unix.  It is a no-op under
** OS/2 since OS/2 does not support hard links.
**
** On success, a handle for a previously open file is at *id is
** updated with the new directory file descriptor and VTK_SQLITE_OK is
** returned.
**
** On failure, the function returns VTK_SQLITE_CANTOPEN and leaves
** *id unchanged.
*/
int os2OpenDirectory(
  OsFile *id,
  const char *zDirname
){
  return VTK_SQLITE_OK;
}

/*
** Create a temporary file name in zBuf.  zBuf must be big enough to
** hold at least VTK_SQLITE_TEMPNAME_SIZE characters.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3Os2TempFileName( char *zBuf ){
  static const unsigned char zChars[] =
    "abcdefghijklmnopqrstuvwxyz"
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "0123456789";
  int i, j;
  PSZ zTempPath = 0;
  if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
    if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
      if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
           ULONG ulDriveNum = 0, ulDriveMap = 0;
           DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
           sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
      }
    }
  }
  for(;;){
      sprintf( zBuf, "%s\\"TEMP_FILE_PREFIX, zTempPath );
      j = strlen( zBuf );
      vtk_sqlite3Randomness( 15, &zBuf[j] );
      for( i = 0; i < 15; i++, j++ ){
        zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
      }
      zBuf[j] = 0;
      if( !vtk_sqlite3OsFileExists( zBuf ) ) break;
  }
  OSTRACE2( "TEMP FILENAME: %s\n", zBuf );
  return VTK_SQLITE_OK;
}

/*
** Close a file.
*/
int os2Close( OsFile **pld ){
  os2File *pFile;
  APIRET rc = NO_ERROR;
  if( pld && (pFile = (os2File*)*pld) != 0 ){
    OSTRACE2( "CLOSE %d\n", pFile->h );
    rc = DosClose( pFile->h );
    pFile->locktype = NO_LOCK;
    if( pFile->delOnClose != 0 ){
        rc = DosForceDelete( (PSZ)pFile->pathToDel );
    }
    *pld = 0;
    OpenCounter( -1 );
  }

  return rc == NO_ERROR ? VTK_SQLITE_OK : VTK_SQLITE_IOERR;
}

/*
** Read data from a file into a buffer.  Return VTK_SQLITE_OK if all
** bytes were read successfully and VTK_SQLITE_IOERR if anything goes
** wrong.
*/
int os2Read( OsFile *id, void *pBuf, int amt ){
  ULONG got;
  assert( id!=0 );
  SimulateIOError( return VTK_SQLITE_IOERR );
  OSTRACE3( "READ %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
  DosRead( ((os2File*)id)->h, pBuf, amt, &got );
  if (got == (ULONG)amt)
    return VTK_SQLITE_OK;
  else if (got == 0)
    return VTK_SQLITE_IOERR_READ;
  else {
    memset(&((char*)pBuf)[got], 0, amt-got);
    return VTK_SQLITE_IOERR_SHORT_READ;
  }
}

/*
** Write data from a buffer into a file.  Return VTK_SQLITE_OK on success
** or some other error code on failure.
*/
int os2Write( OsFile *id, const void *pBuf, int amt ){
  APIRET rc = NO_ERROR;
  ULONG wrote;
  assert( id!=0 );
  SimulateIOError( return VTK_SQLITE_IOERR );
  SimulateDiskfullError( return VTK_SQLITE_FULL );
  OSTRACE3( "WRITE %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
  while( amt > 0 &&
      (rc = DosWrite( ((os2File*)id)->h, (PVOID)pBuf, amt, &wrote )) && wrote > 0 ){
      amt -= wrote;
      pBuf = &((char*)pBuf)[wrote];
  }

  return ( rc != NO_ERROR || amt > (int)wrote ) ? VTK_SQLITE_FULL : VTK_SQLITE_OK;
}

/*
** Move the read/write pointer in a file.
*/
int os2Seek( OsFile *id, i64 offset ){
  APIRET rc = NO_ERROR;
  ULONG filePointer = 0L;
  assert( id!=0 );
  rc = DosSetFilePtr( ((os2File*)id)->h, offset, FILE_BEGIN, &filePointer );
  OSTRACE3( "SEEK %d %lld\n", ((os2File*)id)->h, offset );
  return rc == NO_ERROR ? VTK_SQLITE_OK : VTK_SQLITE_IOERR;
}

/*
** Make sure all writes to a particular file are committed to disk.
*/
int os2Sync( OsFile *id, int dataOnly ){
  assert( id!=0 );
  OSTRACE3( "SYNC %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
  return DosResetBuffer( ((os2File*)id)->h ) == NO_ERROR ? VTK_SQLITE_OK : VTK_SQLITE_IOERR;
}

/*
** Sync the directory zDirname. This is a no-op on operating systems other
** than UNIX.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3Os2SyncDirectory( const char *zDirname ){
  SimulateIOError( return VTK_SQLITE_IOERR );
  return VTK_SQLITE_OK;
}

/*
** Truncate an open file to a specified size
*/
int os2Truncate( OsFile *id, i64 nByte ){
  APIRET rc = NO_ERROR;
  ULONG upperBits = nByte>>32;
  assert( id!=0 );
  OSTRACE3( "TRUNCATE %d %lld\n", ((os2File*)id)->h, nByte );
  SimulateIOError( return VTK_SQLITE_IOERR );
  rc = DosSetFilePtr( ((os2File*)id)->h, nByte, FILE_BEGIN, &upperBits );
  if( rc != NO_ERROR ){
    return VTK_SQLITE_IOERR;
  }
  rc = DosSetFilePtr( ((os2File*)id)->h, 0L, FILE_END, &upperBits );
  return rc == NO_ERROR ? VTK_SQLITE_OK : VTK_SQLITE_IOERR;
}

/*
** Determine the current size of a file in bytes
*/
int os2FileSize( OsFile *id, i64 *pSize ){
  APIRET rc = NO_ERROR;
  FILESTATUS3 fsts3FileInfo;
  memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
  assert( id!=0 );
  SimulateIOError( return VTK_SQLITE_IOERR );
  rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
  if( rc == NO_ERROR ){
    *pSize = fsts3FileInfo.cbFile;
    return VTK_SQLITE_OK;
  }
  else{
    return VTK_SQLITE_IOERR;
  }
}

/*
** Acquire a reader lock.
*/
static int getReadLock( os2File *id ){
  FILELOCK  LockArea,
            UnlockArea;
  memset(&LockArea, 0, sizeof(LockArea));
  memset(&UnlockArea, 0, sizeof(UnlockArea));
  LockArea.lOffset = SHARED_FIRST;
  LockArea.lRange = SHARED_SIZE;
  UnlockArea.lOffset = 0L;
  UnlockArea.lRange = 0L;
  return DosSetFileLocks( id->h, &UnlockArea, &LockArea, 2000L, 1L );
}

/*
** Undo a readlock
*/
static int unlockReadLock( os2File *id ){
  FILELOCK  LockArea,
            UnlockArea;
  memset(&LockArea, 0, sizeof(LockArea));
  memset(&UnlockArea, 0, sizeof(UnlockArea));
  LockArea.lOffset = 0L;
  LockArea.lRange = 0L;
  UnlockArea.lOffset = SHARED_FIRST;
  UnlockArea.lRange = SHARED_SIZE;
  return DosSetFileLocks( id->h, &UnlockArea, &LockArea, 2000L, 1L );
}

#ifndef VTK_SQLITE_OMIT_PAGER_PRAGMAS
/*
** Check that a given pathname is a directory and is writable
**
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3Os2IsDirWritable( char *zDirname ){
  FILESTATUS3 fsts3ConfigInfo;
  APIRET rc = NO_ERROR;
  memset(&fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo));
  if( zDirname==0 ) return 0;
  if( strlen(zDirname)>CCHMAXPATH ) return 0;
  rc = DosQueryPathInfo( (PSZ)zDirname, FIL_STANDARD, &fsts3ConfigInfo, sizeof(FILESTATUS3) );
  if( rc != NO_ERROR ) return 0;
  if( (fsts3ConfigInfo.attrFile & FILE_DIRECTORY) != FILE_DIRECTORY ) return 0;

  return 1;
}
#endif /* VTK_SQLITE_OMIT_PAGER_PRAGMAS */

/*
** Lock the file with the lock specified by parameter locktype - one
** of the following:
**
**     (1) SHARED_LOCK
**     (2) RESERVED_LOCK
**     (3) PENDING_LOCK
**     (4) EXCLUSIVE_LOCK
**
** Sometimes when requesting one lock state, additional lock states
** are inserted in between.  The locking might fail on one of the later
** transitions leaving the lock state different from what it started but
** still short of its goal.  The following chart shows the allowed
** transitions and the inserted intermediate states:
**
**    UNLOCKED -> SHARED
**    SHARED -> RESERVED
**    SHARED -> (PENDING) -> EXCLUSIVE
**    RESERVED -> (PENDING) -> EXCLUSIVE
**    PENDING -> EXCLUSIVE
**
** This routine will only increase a lock.  The os2Unlock() routine
** erases all locks at once and returns us immediately to locking level 0.
** It is not possible to lower the locking level one step at a time.  You
** must go straight to locking level 0.
*/
int os2Lock( OsFile *id, int locktype ){
  APIRET rc = VTK_SQLITE_OK;    /* Return code from subroutines */
  APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
  int newLocktype;       /* Set id->locktype to this value before exiting */
  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  FILELOCK  LockArea,
            UnlockArea;
  os2File *pFile = (os2File*)id;
  memset(&LockArea, 0, sizeof(LockArea));
  memset(&UnlockArea, 0, sizeof(UnlockArea));
  assert( pFile!=0 );
  OSTRACE4( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype );

  /* If there is already a lock of this type or more restrictive on the
  ** OsFile, do nothing. Don't use the end_lock: exit path, as
  ** vtk_sqlite3OsEnterMutex() hasn't been called yet.
  */
  if( pFile->locktype>=locktype ){
    return VTK_SQLITE_OK;
  }

  /* Make sure the locking sequence is correct
  */
  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  assert( locktype!=PENDING_LOCK );
  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );

  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
  ** the PENDING_LOCK byte is temporary.
  */
  newLocktype = pFile->locktype;
  if( pFile->locktype==NO_LOCK
   || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
  ){
    int cnt = 3;

    LockArea.lOffset = PENDING_BYTE;
    LockArea.lRange = 1L;
    UnlockArea.lOffset = 0L;
    UnlockArea.lRange = 0L;

    while( cnt-->0 && (res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L) )!=NO_ERROR ){
      /* Try 3 times to get the pending lock.  The pending lock might be
      ** held by another reader process who will release it momentarily.
      */
      OSTRACE2( "could not get a PENDING lock. cnt=%d\n", cnt );
      DosSleep(1);
    }
    gotPendingLock = res;
  }

  /* Acquire a shared lock
  */
  if( locktype==SHARED_LOCK && res ){
    assert( pFile->locktype==NO_LOCK );
    res = getReadLock(pFile);
    if( res == NO_ERROR ){
      newLocktype = SHARED_LOCK;
    }
  }

  /* Acquire a RESERVED lock
  */
  if( locktype==RESERVED_LOCK && res ){
    assert( pFile->locktype==SHARED_LOCK );
    LockArea.lOffset = RESERVED_BYTE;
    LockArea.lRange = 1L;
    UnlockArea.lOffset = 0L;
    UnlockArea.lRange = 0L;
    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
    if( res == NO_ERROR ){
      newLocktype = RESERVED_LOCK;
    }
  }

  /* Acquire a PENDING lock
  */
  if( locktype==EXCLUSIVE_LOCK && res ){
    newLocktype = PENDING_LOCK;
    gotPendingLock = 0;
  }

  /* Acquire an EXCLUSIVE lock
  */
  if( locktype==EXCLUSIVE_LOCK && res ){
    assert( pFile->locktype>=SHARED_LOCK );
    res = unlockReadLock(pFile);
    OSTRACE2( "unreadlock = %d\n", res );
    LockArea.lOffset = SHARED_FIRST;
    LockArea.lRange = SHARED_SIZE;
    UnlockArea.lOffset = 0L;
    UnlockArea.lRange = 0L;
    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
    if( res == NO_ERROR ){
      newLocktype = EXCLUSIVE_LOCK;
    }else{
      OSTRACE2( "error-code = %d\n", res );
    }
  }

  /* If we are holding a PENDING lock that ought to be released, then
  ** release it now.
  */
  if( gotPendingLock && locktype==SHARED_LOCK ){
    LockArea.lOffset = 0L;
    LockArea.lRange = 0L;
    UnlockArea.lOffset = PENDING_BYTE;
    UnlockArea.lRange = 1L;
    DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
  }

  /* Update the state of the lock has held in the file descriptor then
  ** return the appropriate result code.
  */
  if( res == NO_ERROR ){
    rc = VTK_SQLITE_OK;
  }else{
    OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
           locktype, newLocktype );
    rc = VTK_SQLITE_BUSY;
  }
  pFile->locktype = newLocktype;
  return rc;
}

/*
** This routine checks if there is a RESERVED lock held on the specified
** file by this or any other process. If such a lock is held, return
** non-zero, otherwise zero.
*/
int os2CheckReservedLock( OsFile *id ){
  APIRET rc = NO_ERROR;
  os2File *pFile = (os2File*)id;
  assert( pFile!=0 );
  if( pFile->locktype>=RESERVED_LOCK ){
    rc = 1;
    OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile->h, rc );
  }else{
    FILELOCK  LockArea,
              UnlockArea;
    memset(&LockArea, 0, sizeof(LockArea));
    memset(&UnlockArea, 0, sizeof(UnlockArea));
    LockArea.lOffset = RESERVED_BYTE;
    LockArea.lRange = 1L;
    UnlockArea.lOffset = 0L;
    UnlockArea.lRange = 0L;
    rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
    if( rc == NO_ERROR ){
      LockArea.lOffset = 0L;
      LockArea.lRange = 0L;
      UnlockArea.lOffset = RESERVED_BYTE;
      UnlockArea.lRange = 1L;
      rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
    }
    OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile->h, rc );
  }
  return rc;
}

/*
** Lower the locking level on file descriptor id to locktype.  locktype
** must be either NO_LOCK or SHARED_LOCK.
**
** If the locking level of the file descriptor is already at or below
** the requested locking level, this routine is a no-op.
**
** It is not possible for this routine to fail if the second argument
** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
** might return VTK_SQLITE_IOERR;
*/
int os2Unlock( OsFile *id, int locktype ){
  int type;
  APIRET rc = VTK_SQLITE_OK;
  os2File *pFile = (os2File*)id;
  FILELOCK  LockArea,
            UnlockArea;
  memset(&LockArea, 0, sizeof(LockArea));
  memset(&UnlockArea, 0, sizeof(UnlockArea));
  assert( pFile!=0 );
  assert( locktype<=SHARED_LOCK );
  OSTRACE4( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype );
  type = pFile->locktype;
  if( type>=EXCLUSIVE_LOCK ){
    LockArea.lOffset = 0L;
    LockArea.lRange = 0L;
    UnlockArea.lOffset = SHARED_FIRST;
    UnlockArea.lRange = SHARED_SIZE;
    DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
    if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
      /* This should never happen.  We should always be able to
      ** reacquire the read lock */
      rc = VTK_SQLITE_IOERR;
    }
  }
  if( type>=RESERVED_LOCK ){
    LockArea.lOffset = 0L;
    LockArea.lRange = 0L;
    UnlockArea.lOffset = RESERVED_BYTE;
    UnlockArea.lRange = 1L;
    DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
  }
  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
    unlockReadLock(pFile);
  }
  if( type>=PENDING_LOCK ){
    LockArea.lOffset = 0L;
    LockArea.lRange = 0L;
    UnlockArea.lOffset = PENDING_BYTE;
    UnlockArea.lRange = 1L;
    DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
  }
  pFile->locktype = locktype;
  return rc;
}

/*
** Turn a relative pathname into a full pathname.  Return a pointer
** to the full pathname stored in space obtained from vtk_sqliteMalloc().
** The calling function is responsible for freeing this space once it
** is no longer needed.
*/
VTK_SQLITE_PRIVATE char *vtk_sqlite3Os2FullPathname( const char *zRelative ){
  char *zFull = 0;
  if( strchr(zRelative, ':') ){
    vtk_sqlite3SetString( &zFull, zRelative, (char*)0 );
  }else{
    ULONG ulDriveNum = 0;
    ULONG ulDriveMap = 0;
    ULONG cbzBufLen = VTK_SQLITE_TEMPNAME_SIZE;
    char zDrive[2];
    char *zBuff;

    zBuff = vtk_sqliteMalloc( cbzBufLen );
    if( zBuff != 0 ){
      DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
      if( DosQueryCurrentDir( ulDriveNum, (PBYTE)zBuff, &cbzBufLen ) == NO_ERROR ){
        sprintf( zDrive, "%c", (char)('A' + ulDriveNum - 1) );
        vtk_sqlite3SetString( &zFull, zDrive, ":\\", zBuff,
                          "\\", zRelative, (char*)0 );
      }
      vtk_sqliteFree( zBuff );
    }
  }
  return zFull;
}

/*
** The fullSync option is meaningless on os2, or correct me if I'm wrong.  This is a no-op.
** From os_unix.c: Change the value of the fullsync flag in the given file descriptor.
** From os_unix.c: ((unixFile*)id)->fullSync = v;
*/
static void os2SetFullSync( OsFile *id, int v ){
  return;
}

/*
** Return the underlying file handle for an OsFile
*/
static int os2FileHandle( OsFile *id ){
  return (int)((os2File*)id)->h;
}

/*
** Return an integer that indices the type of lock currently held
** by this handle.  (Used for testing and analysis only.)
*/
static int os2LockState( OsFile *id ){
  return ((os2File*)id)->locktype;
}

/*
** Return the sector size in bytes of the underlying block device for
** the specified file. This is almost always 512 bytes, but may be
** larger for some devices.
**
** Vtk_Sqlite code assumes this function cannot fail. It also assumes that
** if two files are created in the same file-system directory (i.e.
** a database and it's journal file) that the sector size will be the
** same for both.
*/
static int os2SectorSize(OsFile *id){
  return VTK_SQLITE_DEFAULT_SECTOR_SIZE;
}

/*
** This vector defines all the methods that can operate on an OsFile
** for os2.
*/
static const IoMethod vtk_sqlite3Os2IoMethod = {
  os2Close,
  os2OpenDirectory,
  os2Read,
  os2Write,
  os2Seek,
  os2Truncate,
  os2Sync,
  os2SetFullSync,
  os2FileHandle,
  os2FileSize,
  os2Lock,
  os2Unlock,
  os2LockState,
  os2CheckReservedLock,
  os2SectorSize,
};

/*
** Allocate memory for an OsFile.  Initialize the new OsFile
** to the value given in pInit and return a pointer to the new
** OsFile.  If we run out of memory, close the file and return NULL.
*/
int allocateOs2File( os2File *pInit, OsFile **pld ){
  os2File *pNew;
  pNew = vtk_sqliteMalloc( sizeof(*pNew) );
  if( pNew==0 ){
    DosClose( pInit->h );
    *pld = 0;
    return VTK_SQLITE_NOMEM;
  }else{
    *pNew = *pInit;
    pNew->pMethod = &vtk_sqlite3Os2IoMethod;
    pNew->locktype = NO_LOCK;
    *pld = (OsFile*)pNew;
    OpenCounter(+1);
    return VTK_SQLITE_OK;
  }
}

#endif /* VTK_SQLITE_OMIT_DISKIO */
/***************************************************************************
** Everything above deals with file I/O.  Everything that follows deals
** with other miscellanous aspects of the operating system interface
****************************************************************************/

#ifndef VTK_SQLITE_OMIT_LOAD_EXTENSION
/*
** Interfaces for opening a shared library, finding entry points
** within the shared library, and closing the shared library.
*/
VTK_SQLITE_PRIVATE void *vtk_sqlite3Os2Dlopen(const char *zFilename){
  UCHAR loadErr[256];
  HMODULE hmod;
  APIRET rc;
  rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilename, &hmod);
  if (rc != NO_ERROR) return 0;
  return (void*)hmod;
}
VTK_SQLITE_PRIVATE void *vtk_sqlite3Os2Dlsym(void *pHandle, const char *zSymbol){
  PFN pfn;
  APIRET rc;
  rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
  if (rc != NO_ERROR) {
    /* if the symbol itself was not found, search again for the same
     * symbol with an extra underscore, that might be needed depending
     * on the calling convention */
    char _zSymbol[256] = "_";
    strncat(_zSymbol, zSymbol, 255);
    rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
  }
  if (rc != NO_ERROR) return 0;
  return (void *)pfn;
}
VTK_SQLITE_PRIVATE int vtk_sqlite3Os2Dlclose(void *pHandle){
  return DosFreeModule((HMODULE)pHandle);
}
#endif /* VTK_SQLITE_OMIT_LOAD_EXTENSION */


/*
** Get information to seed the random number generator.  The seed
** is written into the buffer zBuf[256].  The calling function must
** supply a sufficiently large buffer.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3Os2RandomSeed( char *zBuf ){
  /* We have to initialize zBuf to prevent valgrind from reporting
  ** errors.  The reports issued by valgrind are incorrect - we would
  ** prefer that the randomness be increased by making use of the
  ** uninitialized space in zBuf - but valgrind errors tend to worry
  ** some users.  Rather than argue, it seems easier just to initialize
  ** the whole array and silence valgrind, even if that means less randomness
  ** in the random seed.
  **
  ** When testing, initializing zBuf[] to zero is all we do.  That means
  ** that we always use the same random number sequence. This makes the
  ** tests repeatable.
  */
  memset( zBuf, 0, 256 );
  DosGetDateTime( (PDATETIME)zBuf );
  return VTK_SQLITE_OK;
}

/*
** Sleep for a little while.  Return the amount of time slept.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3Os2Sleep( int ms ){
  DosSleep( ms );
  return ms;
}

/*
** Static variables used for thread synchronization
*/
static int inMutex = 0;
#ifdef VTK_SQLITE_OS2_THREADS
static ULONG mutexOwner;
#endif

/*
** The following pair of routines implement mutual exclusion for
** multi-threaded processes.  Only a single thread is allowed to
** executed code that is surrounded by EnterMutex() and LeaveMutex().
**
** Vtk_Sqlite uses only a single Mutex.  There is not much critical
** code and what little there is executes quickly and without blocking.
*/
VTK_SQLITE_PRIVATE void vtk_sqlite3Os2EnterMutex(){
#ifdef VTK_SQLITE_OS2_THREADS
  PTIB ptib;
  DosEnterCritSec();
  DosGetInfoBlocks( &ptib, NULL );
  mutexOwner = ptib->tib_ptib2->tib2_ultid;
#endif
  assert( !inMutex );
  inMutex = 1;
}
VTK_SQLITE_PRIVATE void vtk_sqlite3Os2LeaveMutex(){
#ifdef VTK_SQLITE_OS2_THREADS
  PTIB ptib;
#endif
  assert( inMutex );
  inMutex = 0;
#ifdef VTK_SQLITE_OS2_THREADS
  DosGetInfoBlocks( &ptib, NULL );
  assert( mutexOwner == ptib->tib_ptib2->tib2_ultid );
  DosExitCritSec();
#endif
}

/*
** Return TRUE if the mutex is currently held.
**
** If the thisThreadOnly parameter is true, return true if and only if the
** calling thread holds the mutex.  If the parameter is false, return
** true if any thread holds the mutex.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3Os2InMutex( int thisThreadOnly ){
#ifdef VTK_SQLITE_OS2_THREADS
  PTIB ptib;
  DosGetInfoBlocks( &ptib, NULL );
  return inMutex>0 && (thisThreadOnly==0 || mutexOwner==ptib->tib_ptib2->tib2_ultid);
#else
  return inMutex>0;
#endif
}

/*
** The following variable, if set to a non-zero value, becomes the result
** returned from vtk_sqlite3OsCurrentTime().  This is used for testing.
*/
#ifdef VTK_SQLITE_TEST
int vtk_sqlite3_current_time = 0;
#endif

/*
** Find the current time (in Universal Coordinated Time).  Write the
** current time and date as a Julian Day number into *prNow and
** return 0.  Return 1 if the time and date cannot be found.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3Os2CurrentTime( double *prNow ){
  double now;
  USHORT second, minute, hour,
         day, month, year;
  DATETIME dt;
  DosGetDateTime( &dt );
  second = (USHORT)dt.seconds;
  minute = (USHORT)dt.minutes + dt.timezone;
  hour = (USHORT)dt.hours;
  day = (USHORT)dt.day;
  month = (USHORT)dt.month;
  year = (USHORT)dt.year;

  /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
     http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
  /* Calculate the Julian days */
  now = day - 32076 +
    1461*(year + 4800 + (month - 14)/12)/4 +
    367*(month - 2 - (month - 14)/12*12)/12 -
    3*((year + 4900 + (month - 14)/12)/100)/4;

  /* Add the fractional hours, mins and seconds */
  now += (hour + 12.0)/24.0;
  now += minute/1440.0;
  now += second/86400.0;
  *prNow = now;
#ifdef VTK_SQLITE_TEST
  if( vtk_sqlite3_current_time ){
    *prNow = vtk_sqlite3_current_time/86400.0 + 2440587.5;
  }
#endif
  return 0;
}

/*
** Remember the number of thread-specific-data blocks allocated.
** Use this to verify that we are not leaking thread-specific-data.
** Ticket #1601
*/
#ifdef VTK_SQLITE_TEST
int vtk_sqlite3_tsd_count = 0;
# define TSD_COUNTER_INCR InterlockedIncrement( &vtk_sqlite3_tsd_count )
# define TSD_COUNTER_DECR InterlockedDecrement( &vtk_sqlite3_tsd_count )
#else
# define TSD_COUNTER_INCR  /* no-op */
# define TSD_COUNTER_DECR  /* no-op */
#endif

/*
** If called with allocateFlag>1, then return a pointer to thread
** specific data for the current thread.  Allocate and zero the
** thread-specific data if it does not already exist necessary.
**
** If called with allocateFlag==0, then check the current thread
** specific data.  Return it if it exists.  If it does not exist,
** then return NULL.
**
** If called with allocateFlag<0, check to see if the thread specific
** data is allocated and is all zero.  If it is then deallocate it.
** Return a pointer to the thread specific data or NULL if it is
** unallocated or gets deallocated.
*/
VTK_SQLITE_PRIVATE ThreadData *vtk_sqlite3Os2ThreadSpecificData( int allocateFlag ){
  static ThreadData **s_ppTsd = NULL;
  static const ThreadData zeroData = {0, 0, 0};
  ThreadData *pTsd;

  if( !s_ppTsd ){
    vtk_sqlite3OsEnterMutex();
    if( !s_ppTsd ){
      PULONG pul;
      APIRET rc = DosAllocThreadLocalMemory(1, &pul);
      if( rc != NO_ERROR ){
        vtk_sqlite3OsLeaveMutex();
        return 0;
      }
      s_ppTsd = (ThreadData **)pul;
    }
    vtk_sqlite3OsLeaveMutex();
  }
  pTsd = *s_ppTsd;
  if( allocateFlag>0 ){
    if( !pTsd ){
      pTsd = vtk_sqlite3OsMalloc( sizeof(zeroData) );
      if( pTsd ){
        *pTsd = zeroData;
        *s_ppTsd = pTsd;
        TSD_COUNTER_INCR;
      }
    }
  }else if( pTsd!=0 && allocateFlag<0
              && memcmp( pTsd, &zeroData, sizeof(ThreadData) )==0 ){
    vtk_sqlite3OsFree(pTsd);
    *s_ppTsd = NULL;
    TSD_COUNTER_DECR;
    pTsd = 0;
  }
  return pTsd;
}
#endif /* OS_OS2 */

/************** End of os_os2.c **********************************************/
/************** Begin file os_unix.c *****************************************/
/*
** 2004 May 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains code that is specific to Unix systems.
*/
#if OS_UNIX              /* This file is used on unix only */

/* #define VTK_SQLITE_ENABLE_LOCKING_STYLE 0 */

/*
** These #defines should enable >2GB file support on Posix if the
** underlying operating system supports it.  If the OS lacks
** large file support, these should be no-ops.
**
** Large file support can be disabled using the -DVTK_SQLITE_DISABLE_LFS switch
** on the compiler command line.  This is necessary if you are compiling
** on a recent machine (ex: RedHat 7.2) but you want your code to work
** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
** without this option, LFS is enable.  But LFS does not exist in the kernel
** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
** portability you should omit LFS.
*/
#ifndef VTK_SQLITE_DISABLE_LFS
# define _LARGE_FILE       1
# ifndef _FILE_OFFSET_BITS
#   define _FILE_OFFSET_BITS 64
# endif
# define _LARGEFILE_SOURCE 1
#endif

/*
** standard include files.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/time.h>
#include <errno.h>
#ifdef VTK_SQLITE_ENABLE_LOCKING_STYLE
#include <sys/ioctl.h>
#include <sys/param.h>
#include <sys/mount.h>
#endif /* VTK_SQLITE_ENABLE_LOCKING_STYLE */

/*
** If we are to be thread-safe, include the pthreads header and define
** the VTK_SQLITE_UNIX_THREADS macro.
*/
#ifdef HAVE_PTHREAD_H
# ifndef THREADSAFE
#  define THREADSAFE 1
# endif
# if THREADSAFE
#  include <pthread.h>
#  define VTK_SQLITE_UNIX_THREADS 1
# endif
#endif

/*
** Default permissions when creating a new file
*/
#ifndef VTK_SQLITE_DEFAULT_FILE_PERMISSIONS
# define VTK_SQLITE_DEFAULT_FILE_PERMISSIONS 0644
#endif



/*
** The unixFile structure is subclass of OsFile specific for the unix
** protability layer.
*/
typedef struct unixFile unixFile;
struct unixFile {
  IoMethod const *pMethod;  /* Always the first entry */
  struct openCnt *pOpen;    /* Info about all open fd's on this inode */
  struct lockInfo *pLock;   /* Info about locks on this inode */
#ifdef VTK_SQLITE_ENABLE_LOCKING_STYLE
  void *lockingContext;     /* Locking style specific state */
#endif /* VTK_SQLITE_ENABLE_LOCKING_STYLE */
  int h;                    /* The file descriptor */
  unsigned char locktype;   /* The type of lock held on this fd */
  unsigned char isOpen;     /* True if needs to be closed */
  unsigned char fullSync;   /* Use F_FULLSYNC if available */
  int dirfd;                /* File descriptor for the directory */
  i64 offset;               /* Seek offset */
#ifdef VTK_SQLITE_UNIX_THREADS
  pthread_t tid;            /* The thread that "owns" this OsFile */
#endif
};

/*
** Provide the ability to override some OS-layer functions during
** testing.  This is used to simulate OS crashes to verify that 
** commits are atomic even in the event of an OS crash.
*/
#ifdef VTK_SQLITE_CRASH_TEST
  extern int vtk_sqlite3CrashTestEnable;
  extern int vtk_sqlite3CrashOpenReadWrite(const char*, OsFile**, int*);
  extern int vtk_sqlite3CrashOpenExclusive(const char*, OsFile**, int);
  extern int vtk_sqlite3CrashOpenReadOnly(const char*, OsFile**, int);
# define CRASH_TEST_OVERRIDE(X,A,B,C) \
    if(vtk_sqlite3CrashTestEnable){ return X(A,B,C); }
#else
# define CRASH_TEST_OVERRIDE(X,A,B,C)  /* no-op */
#endif


/*
** Include code that is common to all os_*.c files
*/
/************** Include os_common.h in the middle of os_unix.c ***************/
/************** Begin file os_common.h ***************************************/
/*
** 2004 May 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains macros and a little bit of code that is common to
** all of the platform-specific files (os_*.c) and is #included into those
** files.
**
** This file should be #included by the os_*.c files only.  It is not a
** general purpose header file.
*/

/*
** At least two bugs have slipped in because we changed the MEMORY_DEBUG
** macro to VTK_SQLITE_DEBUG and some older makefiles have not yet made the
** switch.  The following code should catch this problem at compile-time.
*/
#ifdef MEMORY_DEBUG
# error "The MEMORY_DEBUG macro is obsolete.  Use VTK_SQLITE_DEBUG instead."
#endif


/*
 * When testing, this global variable stores the location of the
 * pending-byte in the database file.
 */
#ifdef VTK_SQLITE_TEST
unsigned int vtk_sqlite3_pending_byte = 0x40000000;
#endif

int vtk_sqlite3_os_trace = 0;
#ifdef VTK_SQLITE_DEBUG
#define OSTRACE1(X)         if( vtk_sqlite3_os_trace ) vtk_sqlite3DebugPrintf(X)
#define OSTRACE2(X,Y)       if( vtk_sqlite3_os_trace ) vtk_sqlite3DebugPrintf(X,Y)
#define OSTRACE3(X,Y,Z)     if( vtk_sqlite3_os_trace ) vtk_sqlite3DebugPrintf(X,Y,Z)
#define OSTRACE4(X,Y,Z,A)   if( vtk_sqlite3_os_trace ) vtk_sqlite3DebugPrintf(X,Y,Z,A)
#define OSTRACE5(X,Y,Z,A,B) if( vtk_sqlite3_os_trace ) vtk_sqlite3DebugPrintf(X,Y,Z,A,B)
#define OSTRACE6(X,Y,Z,A,B,C) \
    if(vtk_sqlite3_os_trace) vtk_sqlite3DebugPrintf(X,Y,Z,A,B,C)
#define OSTRACE7(X,Y,Z,A,B,C,D) \
    if(vtk_sqlite3_os_trace) vtk_sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
#else
#define OSTRACE1(X)
#define OSTRACE2(X,Y)
#define OSTRACE3(X,Y,Z)
#define OSTRACE4(X,Y,Z,A)
#define OSTRACE5(X,Y,Z,A,B)
#define OSTRACE6(X,Y,Z,A,B,C)
#define OSTRACE7(X,Y,Z,A,B,C,D)
#endif

/*
** Macros for performance tracing.  Normally turned off.  Only works
** on i486 hardware.
*/
#ifdef VTK_SQLITE_PERFORMANCE_TRACE
__inline__ unsigned long long int hwtime(void){
  unsigned long long int x;
  __asm__("rdtsc\n\t"
          "mov %%edx, %%ecx\n\t"
          :"=A" (x));
  return x;
}
static unsigned long long int g_start;
static unsigned int elapse;
#define TIMER_START       g_start=hwtime()
#define TIMER_END         elapse=hwtime()-g_start
#define TIMER_ELAPSED     elapse
#else
#define TIMER_START
#define TIMER_END
#define TIMER_ELAPSED     0
#endif

/*
** If we compile with the VTK_SQLITE_TEST macro set, then the following block
** of code will give us the ability to simulate a disk I/O error.  This
** is used for testing the I/O recovery logic.
*/
#ifdef VTK_SQLITE_TEST
int vtk_sqlite3_io_error_hit = 0;
int vtk_sqlite3_io_error_pending = 0;
int vtk_sqlite3_io_error_persist = 0;
int vtk_sqlite3_diskfull_pending = 0;
int vtk_sqlite3_diskfull = 0;
#define SimulateIOError(CODE)  \
  if( vtk_sqlite3_io_error_pending || vtk_sqlite3_io_error_hit ) \
     if( vtk_sqlite3_io_error_pending-- == 1 \
         || (vtk_sqlite3_io_error_persist && vtk_sqlite3_io_error_hit) ) \
                { local_ioerr(); CODE; }
static void local_ioerr(){
  IOTRACE(("IOERR\n"));
  vtk_sqlite3_io_error_hit = 1;
}
#define SimulateDiskfullError(CODE) \
   if( vtk_sqlite3_diskfull_pending ){ \
     if( vtk_sqlite3_diskfull_pending == 1 ){ \
       local_ioerr(); \
       vtk_sqlite3_diskfull = 1; \
       vtk_sqlite3_io_error_hit = 1; \
       CODE; \
     }else{ \
       vtk_sqlite3_diskfull_pending--; \
     } \
   }
#else
#define SimulateIOError(A)
#define SimulateDiskfullError(A)
#endif

/*
** When testing, keep a count of the number of open files.
*/
#ifdef VTK_SQLITE_TEST
int vtk_sqlite3_open_file_count = 0;
#define OpenCounter(X)  vtk_sqlite3_open_file_count+=(X)
#else
#define OpenCounter(X)
#endif

/*
** vtk_sqlite3GenericMalloc
** vtk_sqlite3GenericRealloc
** vtk_sqlite3GenericOsFree
** vtk_sqlite3GenericAllocationSize
**
** Implementation of the os level dynamic memory allocation interface in terms
** of the standard malloc(), realloc() and free() found in many operating
** systems. No rocket science here.
**
** There are two versions of these four functions here. The version
** implemented here is only used if memory-management or memory-debugging is
** enabled. This version allocates an extra 8-bytes at the beginning of each
** block and stores the size of the allocation there.
**
** If neither memory-management or debugging is enabled, the second
** set of implementations is used instead.
*/
#if defined(VTK_SQLITE_ENABLE_MEMORY_MANAGEMENT) || defined (VTK_SQLITE_MEMDEBUG)
VTK_SQLITE_PRIVATE void *vtk_sqlite3GenericMalloc(int n){
  char *p = (char *)malloc(n+8);
  assert(n>0);
  assert(sizeof(int)<=8);
  if( p ){
    *(int *)p = n;
    p += 8;
  }
  return (void *)p;
}
VTK_SQLITE_PRIVATE void *vtk_sqlite3GenericRealloc(void *p, int n){
  char *p2 = ((char *)p - 8);
  assert(n>0);
  p2 = (char*)realloc(p2, n+8);
  if( p2 ){
    *(int *)p2 = n;
    p2 += 8;
  }
  return (void *)p2;
}
VTK_SQLITE_PRIVATE void vtk_sqlite3GenericFree(void *p){
  assert(p);
  free((void *)((char *)p - 8));
}
VTK_SQLITE_PRIVATE int vtk_sqlite3GenericAllocationSize(void *p){
  return p ? *(int *)((char *)p - 8) : 0;
}
#else
VTK_SQLITE_PRIVATE void *vtk_sqlite3GenericMalloc(int n){
  char *p = (char *)malloc(n);
  return (void *)p;
}
VTK_SQLITE_PRIVATE void *vtk_sqlite3GenericRealloc(void *p, int n){
  assert(n>0);
  p = realloc(p, n);
  return p;
}
VTK_SQLITE_PRIVATE void vtk_sqlite3GenericFree(void *p){
  assert(p);
  free(p);
}
/* Never actually used, but needed for the linker */
/* We can get rid of this because REDEF_IO is off */
/*
VTK_SQLITE_PRIVATE int vtk_sqlite3GenericAllocationSize(void *p){ (void)p; return 0; }
*/
#endif

/*
** The default size of a disk sector
*/
#ifndef PAGER_SECTOR_SIZE
# define PAGER_SECTOR_SIZE 512
#endif

/************** End of os_common.h *******************************************/
/************** Continuing where we left off in os_unix.c ********************/

/*
** Do not include any of the File I/O interface procedures if the
** VTK_SQLITE_OMIT_DISKIO macro is defined (indicating that the database
** will be in-memory only)
*/
#ifndef VTK_SQLITE_OMIT_DISKIO


/*
** Define various macros that are missing from some systems.
*/
#ifndef O_LARGEFILE
# define O_LARGEFILE 0
#endif
#ifdef VTK_SQLITE_DISABLE_LFS
# undef O_LARGEFILE
# define O_LARGEFILE 0
#endif
#ifndef O_NOFOLLOW
# define O_NOFOLLOW 0
#endif
#ifndef O_BINARY
# define O_BINARY 0
#endif

/*
** The DJGPP compiler environment looks mostly like Unix, but it
** lacks the fcntl() system call.  So redefine fcntl() to be something
** that always succeeds.  This means that locking does not occur under
** DJGPP.  But it's DOS - what did you expect?
*/
#ifdef __DJGPP__
# define fcntl(A,B,C) 0
#endif

/*
** The threadid macro resolves to the thread-id or to 0.  Used for
** testing and debugging only.
*/
#ifdef VTK_SQLITE_UNIX_THREADS
#define threadid pthread_self()
#else
#define threadid 0
#endif

/*
** Set or check the OsFile.tid field.  This field is set when an OsFile
** is first opened.  All subsequent uses of the OsFile verify that the
** same thread is operating on the OsFile.  Some operating systems do
** not allow locks to be overridden by other threads and that restriction
** means that vtk_sqlite3* database handles cannot be moved from one thread
** to another.  This logic makes sure a user does not try to do that
** by mistake.
**
** Version 3.3.1 (2006-01-15):  OsFiles can be moved from one thread to
** another as long as we are running on a system that supports threads
** overriding each others locks (which now the most common behavior)
** or if no locks are held.  But the OsFile.pLock field needs to be
** recomputed because its key includes the thread-id.  See the 
** transferOwnership() function below for additional information
*/
#if defined(VTK_SQLITE_UNIX_THREADS)
# define SET_THREADID(X)   (X)->tid = pthread_self()
# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
                            !pthread_equal((X)->tid, pthread_self()))
#else
# define SET_THREADID(X)
# define CHECK_THREADID(X) 0
#endif

/*
** Here is the dirt on POSIX advisory locks:  ANSI STD 1003.1 (1996)
** section 6.5.2.2 lines 483 through 490 specify that when a process
** sets or clears a lock, that operation overrides any prior locks set
** by the same process.  It does not explicitly say so, but this implies
** that it overrides locks set by the same process using a different
** file descriptor.  Consider this test case:
**
**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
**
** Suppose ./file1 and ./file2 are really the same file (because
** one is a hard or symbolic link to the other) then if you set
** an exclusive lock on fd1, then try to get an exclusive lock
** on fd2, it works.  I would have expected the second lock to
** fail since there was already a lock on the file due to fd1.
** But not so.  Since both locks came from the same process, the
** second overrides the first, even though they were on different
** file descriptors opened on different file names.
**
** Bummer.  If you ask me, this is broken.  Badly broken.  It means
** that we cannot use POSIX locks to synchronize file access among
** competing threads of the same process.  POSIX locks will work fine
** to synchronize access for threads in separate processes, but not
** threads within the same process.
**
** To work around the problem, Vtk_Sqlite has to manage file locks internally
** on its own.  Whenever a new database is opened, we have to find the
** specific inode of the database file (the inode is determined by the
** st_dev and st_ino fields of the stat structure that fstat() fills in)
** and check for locks already existing on that inode.  When locks are
** created or removed, we have to look at our own internal record of the
** locks to see if another thread has previously set a lock on that same
** inode.
**
** The OsFile structure for POSIX is no longer just an integer file
** descriptor.  It is now a structure that holds the integer file
** descriptor and a pointer to a structure that describes the internal
** locks on the corresponding inode.  There is one locking structure
** per inode, so if the same inode is opened twice, both OsFile structures
** point to the same locking structure.  The locking structure keeps
** a reference count (so we will know when to delete it) and a "cnt"
** field that tells us its internal lock status.  cnt==0 means the
** file is unlocked.  cnt==-1 means the file has an exclusive lock.
** cnt>0 means there are cnt shared locks on the file.
**
** Any attempt to lock or unlock a file first checks the locking
** structure.  The fcntl() system call is only invoked to set a 
** POSIX lock if the internal lock structure transitions between
** a locked and an unlocked state.
**
** 2004-Jan-11:
** More recent discoveries about POSIX advisory locks.  (The more
** I discover, the more I realize the a POSIX advisory locks are
** an abomination.)
**
** If you close a file descriptor that points to a file that has locks,
** all locks on that file that are owned by the current process are
** released.  To work around this problem, each OsFile structure contains
** a pointer to an openCnt structure.  There is one openCnt structure
** per open inode, which means that multiple OsFiles can point to a single
** openCnt.  When an attempt is made to close an OsFile, if there are
** other OsFiles open on the same inode that are holding locks, the call
** to close() the file descriptor is deferred until all of the locks clear.
** The openCnt structure keeps a list of file descriptors that need to
** be closed and that list is walked (and cleared) when the last lock
** clears.
**
** First, under Linux threads, because each thread has a separate
** process ID, lock operations in one thread do not override locks
** to the same file in other threads.  Linux threads behave like
** separate processes in this respect.  But, if you close a file
** descriptor in linux threads, all locks are cleared, even locks
** on other threads and even though the other threads have different
** process IDs.  Linux threads is inconsistent in this respect.
** (I'm beginning to think that linux threads is an abomination too.)
** The consequence of this all is that the hash table for the lockInfo
** structure has to include the process id as part of its key because
** locks in different threads are treated as distinct.  But the 
** openCnt structure should not include the process id in its
** key because close() clears lock on all threads, not just the current
** thread.  Were it not for this goofiness in linux threads, we could
** combine the lockInfo and openCnt structures into a single structure.
**
** 2004-Jun-28:
** On some versions of linux, threads can override each others locks.
** On others not.  Sometimes you can change the behavior on the same
** system by setting the LD_ASSUME_KERNEL environment variable.  The
** POSIX standard is silent as to which behavior is correct, as far
** as I can tell, so other versions of unix might show the same
** inconsistency.  There is no little doubt in my mind that posix
** advisory locks and linux threads are profoundly broken.
**
** To work around the inconsistencies, we have to test at runtime 
** whether or not threads can override each others locks.  This test
** is run once, the first time any lock is attempted.  A static 
** variable is set to record the results of this test for future
** use.
*/

/*
** An instance of the following structure serves as the key used
** to locate a particular lockInfo structure given its inode.
**
** If threads cannot override each others locks, then we set the
** lockKey.tid field to the thread ID.  If threads can override
** each others locks then tid is always set to zero.  tid is omitted
** if we compile without threading support.
*/
struct lockKey {
  dev_t dev;       /* Device number */
  ino_t ino;       /* Inode number */
#ifdef VTK_SQLITE_UNIX_THREADS
  pthread_t tid;   /* Thread ID or zero if threads can override each other */
#endif
};

/*
** An instance of the following structure is allocated for each open
** inode on each thread with a different process ID.  (Threads have
** different process IDs on linux, but not on most other unixes.)
**
** A single inode can have multiple file descriptors, so each OsFile
** structure contains a pointer to an instance of this object and this
** object keeps a count of the number of OsFiles pointing to it.
*/
struct lockInfo {
  struct lockKey key;  /* The lookup key */
  int cnt;             /* Number of SHARED locks held */
  int locktype;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  int nRef;            /* Number of pointers to this structure */
};

/*
** An instance of the following structure serves as the key used
** to locate a particular openCnt structure given its inode.  This
** is the same as the lockKey except that the thread ID is omitted.
*/
struct openKey {
  dev_t dev;   /* Device number */
  ino_t ino;   /* Inode number */
};

/*
** An instance of the following structure is allocated for each open
** inode.  This structure keeps track of the number of locks on that
** inode.  If a close is attempted against an inode that is holding
** locks, the close is deferred until all locks clear by adding the
** file descriptor to be closed to the pending list.
*/
struct openCnt {
  struct openKey key;   /* The lookup key */
  int nRef;             /* Number of pointers to this structure */
  int nLock;            /* Number of outstanding locks */
  int nPending;         /* Number of pending close() operations */
  int *aPending;        /* Malloced space holding fd's awaiting a close() */
};

/* 
** These hash tables map inodes and file descriptors (really, lockKey and
** openKey structures) into lockInfo and openCnt structures.  Access to 
** these hash tables must be protected by a mutex.
*/
static Hash lockHash = {VTK_SQLITE_HASH_BINARY, 0, 0, 0, 
    vtk_sqlite3ThreadSafeMalloc, vtk_sqlite3ThreadSafeFree, 0, 0};
static Hash openHash = {VTK_SQLITE_HASH_BINARY, 0, 0, 0, 
    vtk_sqlite3ThreadSafeMalloc, vtk_sqlite3ThreadSafeFree, 0, 0};

#ifdef VTK_SQLITE_ENABLE_LOCKING_STYLE
/*
** The locking styles are associated with the different file locking
** capabilities supported by different file systems.  
**
** POSIX locking style fully supports shared and exclusive byte-range locks 
** ADP locking only supports exclusive byte-range locks
** FLOCK only supports a single file-global exclusive lock
** DOTLOCK isn't a true locking style, it refers to the use of a special
**   file named the same as the database file with a '.lock' extension, this
**   can be used on file systems that do not offer any reliable file locking
** NO locking means that no locking will be attempted, this is only used for
**   read-only file systems currently
** UNSUPPORTED means that no locking will be attempted, this is only used for
**   file systems that are known to be unsupported
*/
typedef enum {
        posixLockingStyle = 0,       /* standard posix-advisory locks */
        afpLockingStyle,             /* use afp locks */
        flockLockingStyle,           /* use flock() */
        dotlockLockingStyle,         /* use <file>.lock files */
        noLockingStyle,              /* useful for read-only file system */
        unsupportedLockingStyle      /* indicates unsupported file system */
} vtk_sqlite3LockingStyle;
#endif /* VTK_SQLITE_ENABLE_LOCKING_STYLE */

#ifdef VTK_SQLITE_UNIX_THREADS
/*
** This variable records whether or not threads can override each others
** locks.
**
**    0:  No.  Threads cannot override each others locks.
**    1:  Yes.  Threads can override each others locks.
**   -1:  We don't know yet.
**
** On some systems, we know at compile-time if threads can override each
** others locks.  On those systems, the VTK_SQLITE_THREAD_OVERRIDE_LOCK macro
** will be set appropriately.  On other systems, we have to check at
** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
** undefined.
**
** This variable normally has file scope only.  But during testing, we make
** it a global so that the test code can change its value in order to verify
** that the right stuff happens in either case.
*/
#ifndef VTK_SQLITE_THREAD_OVERRIDE_LOCK
# define VTK_SQLITE_THREAD_OVERRIDE_LOCK -1
#endif
#ifdef VTK_SQLITE_TEST
int threadsOverrideEachOthersLocks = VTK_SQLITE_THREAD_OVERRIDE_LOCK;
#else
static int threadsOverrideEachOthersLocks = VTK_SQLITE_THREAD_OVERRIDE_LOCK;
#endif

/*
** This structure holds information passed into individual test
** threads by the testThreadLockingBehavior() routine.
*/
struct threadTestData {
  int fd;                /* File to be locked */
  struct flock lock;     /* The locking operation */
  int result;            /* Result of the locking operation */
};

#ifdef VTK_SQLITE_LOCK_TRACE
/*
** Print out information about all locking operations.
**
** This routine is used for troubleshooting locks on multithreaded
** platforms.  Enable by compiling with the -DVTK_SQLITE_LOCK_TRACE
** command-line option on the compiler.  This code is normally
** turned off.
*/
static int lockTrace(int fd, int op, struct flock *p){
  char *zOpName, *zType;
  int s;
  int savedErrno;
  if( op==F_GETLK ){
    zOpName = "GETLK";
  }else if( op==F_SETLK ){
    zOpName = "SETLK";
  }else{
    s = fcntl(fd, op, p);
    vtk_sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
    return s;
  }
  if( p->l_type==F_RDLCK ){
    zType = "RDLCK";
  }else if( p->l_type==F_WRLCK ){
    zType = "WRLCK";
  }else if( p->l_type==F_UNLCK ){
    zType = "UNLCK";
  }else{
    assert( 0 );
  }
  assert( p->l_whence==SEEK_SET );
  s = fcntl(fd, op, p);
  savedErrno = errno;
  vtk_sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
     (int)p->l_pid, s);
  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
    struct flock l2;
    l2 = *p;
    fcntl(fd, F_GETLK, &l2);
    if( l2.l_type==F_RDLCK ){
      zType = "RDLCK";
    }else if( l2.l_type==F_WRLCK ){
      zType = "WRLCK";
    }else if( l2.l_type==F_UNLCK ){
      zType = "UNLCK";
    }else{
      assert( 0 );
    }
    vtk_sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  }
  errno = savedErrno;
  return s;
}
#define fcntl lockTrace
#endif /* VTK_SQLITE_LOCK_TRACE */

/*
** The testThreadLockingBehavior() routine launches two separate
** threads on this routine.  This routine attempts to lock a file
** descriptor then returns.  The success or failure of that attempt
** allows the testThreadLockingBehavior() procedure to determine
** whether or not threads can override each others locks.
*/
static void *threadLockingTest(void *pArg){
  struct threadTestData *pData = (struct threadTestData*)pArg;
  pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
  return pArg;
}

/*
** This procedure attempts to determine whether or not threads
** can override each others locks then sets the 
** threadsOverrideEachOthersLocks variable appropriately.
*/
static void testThreadLockingBehavior(int fd_orig){
  int fd;
  struct threadTestData d[2];
  pthread_t t[2];

  fd = dup(fd_orig);
  if( fd<0 ) return;
  memset(d, 0, sizeof(d));
  d[0].fd = fd;
  d[0].lock.l_type = F_RDLCK;
  d[0].lock.l_len = 1;
  d[0].lock.l_start = 0;
  d[0].lock.l_whence = SEEK_SET;
  d[1] = d[0];
  d[1].lock.l_type = F_WRLCK;
  pthread_create(&t[0], 0, threadLockingTest, &d[0]);
  pthread_create(&t[1], 0, threadLockingTest, &d[1]);
  pthread_join(t[0], 0);
  pthread_join(t[1], 0);
  close(fd);
  threadsOverrideEachOthersLocks =  d[0].result==0 && d[1].result==0;
}
#endif /* VTK_SQLITE_UNIX_THREADS */

/*
** Release a lockInfo structure previously allocated by findLockInfo().
*/
static void releaseLockInfo(struct lockInfo *pLock){
  assert( vtk_sqlite3OsInMutex(1) );
  if (pLock == NULL)
    return;
  pLock->nRef--;
  if( pLock->nRef==0 ){
    vtk_sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
    vtk_sqlite3ThreadSafeFree(pLock);
  }
}

/*
** Release a openCnt structure previously allocated by findLockInfo().
*/
static void releaseOpenCnt(struct openCnt *pOpen){
  assert( vtk_sqlite3OsInMutex(1) );
  if (pOpen == NULL)
    return;
  pOpen->nRef--;
  if( pOpen->nRef==0 ){
    vtk_sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
    free(pOpen->aPending);
    vtk_sqlite3ThreadSafeFree(pOpen);
  }
}

#ifdef VTK_SQLITE_ENABLE_LOCKING_STYLE
/*
** Tests a byte-range locking query to see if byte range locks are 
** supported, if not we fall back to dotlockLockingStyle.
*/
static vtk_sqlite3LockingStyle vtk_sqlite3TestLockingStyle(const char *filePath, 
  int fd) {
  /* test byte-range lock using fcntl */
  struct flock lockInfo;
  
  lockInfo.l_len = 1;
  lockInfo.l_start = 0;
  lockInfo.l_whence = SEEK_SET;
  lockInfo.l_type = F_RDLCK;
  
  if (fcntl(fd, F_GETLK, &lockInfo) != -1) {
    return posixLockingStyle;
  } 
  
  /* testing for flock can give false positives.  So if if the above test
  ** fails, then we fall back to using dot-lock style locking.
  */  
  return dotlockLockingStyle;
}

/* 
** Examines the f_fstypename entry in the statfs structure as returned by 
** stat() for the file system hosting the database file, assigns the 
** appropriate locking style based on it's value.  These values and 
** assignments are based on Darwin/OSX behavior and have not been tested on 
** other systems.
*/
static vtk_sqlite3LockingStyle vtk_sqlite3DetectLockingStyle(const char *filePath, 
  int fd) {

#ifdef VTK_SQLITE_FIXED_LOCKING_STYLE
  return (vtk_sqlite3LockingStyle)VTK_SQLITE_FIXED_LOCKING_STYLE;
#else
  struct statfs fsInfo;

  if (statfs(filePath, &fsInfo) == -1)
    return vtk_sqlite3TestLockingStyle(filePath, fd);
  
  if (fsInfo.f_flags & MNT_RDONLY)
    return noLockingStyle;
  
  if( (!strcmp(fsInfo.f_fstypename, "hfs")) ||
    (!strcmp(fsInfo.f_fstypename, "ufs")) )
                return posixLockingStyle;
  
  if(!strcmp(fsInfo.f_fstypename, "afpfs"))
    return afpLockingStyle;
  
  if(!strcmp(fsInfo.f_fstypename, "nfs")) 
    return vtk_sqlite3TestLockingStyle(filePath, fd);
  
  if(!strcmp(fsInfo.f_fstypename, "smbfs"))
    return flockLockingStyle;
  
  if(!strcmp(fsInfo.f_fstypename, "msdos"))
    return dotlockLockingStyle;
  
  if(!strcmp(fsInfo.f_fstypename, "webdav"))
    return unsupportedLockingStyle;
  
  return vtk_sqlite3TestLockingStyle(filePath, fd);  
#endif /* VTK_SQLITE_FIXED_LOCKING_STYLE */
}

#endif /* VTK_SQLITE_ENABLE_LOCKING_STYLE */

/*
** Given a file descriptor, locate lockInfo and openCnt structures that
** describes that file descriptor.  Create new ones if necessary.  The
** return values might be uninitialized if an error occurs.
**
** Return the number of errors.
*/
static int findLockInfo(
  int fd,                      /* The file descriptor used in the key */
  struct lockInfo **ppLock,    /* Return the lockInfo structure here */
  struct openCnt **ppOpen      /* Return the openCnt structure here */
){
  int rc;
  struct lockKey key1;
  struct openKey key2;
  struct stat statbuf;
  struct lockInfo *pLock;
  struct openCnt *pOpen;
  rc = fstat(fd, &statbuf);
  if( rc!=0 ) return 1;

  assert( vtk_sqlite3OsInMutex(1) );
  memset(&key1, 0, sizeof(key1));
  key1.dev = statbuf.st_dev;
  key1.ino = statbuf.st_ino;
#ifdef VTK_SQLITE_UNIX_THREADS
  if( threadsOverrideEachOthersLocks<0 ){
    testThreadLockingBehavior(fd);
  }
  key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
#endif
  memset(&key2, 0, sizeof(key2));
  key2.dev = statbuf.st_dev;
  key2.ino = statbuf.st_ino;
  pLock = (struct lockInfo*)vtk_sqlite3HashFind(&lockHash, &key1, sizeof(key1));
  if( pLock==0 ){
    struct lockInfo *pOld;
    pLock = vtk_sqlite3ThreadSafeMalloc( sizeof(*pLock) );
    if( pLock==0 ){
      rc = 1;
      goto exit_findlockinfo;
    }
    pLock->key = key1;
    pLock->nRef = 1;
    pLock->cnt = 0;
    pLock->locktype = 0;
    pOld = vtk_sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
    if( pOld!=0 ){
      assert( pOld==pLock );
      vtk_sqlite3ThreadSafeFree(pLock);
      rc = 1;
      goto exit_findlockinfo;
    }
  }else{
    pLock->nRef++;
  }
  *ppLock = pLock;
  if( ppOpen!=0 ){
    pOpen = (struct openCnt*)vtk_sqlite3HashFind(&openHash, &key2, sizeof(key2));
    if( pOpen==0 ){
      struct openCnt *pOld;
      pOpen = vtk_sqlite3ThreadSafeMalloc( sizeof(*pOpen) );
      if( pOpen==0 ){
        releaseLockInfo(pLock);
        rc = 1;
        goto exit_findlockinfo;
      }
      pOpen->key = key2;
      pOpen->nRef = 1;
      pOpen->nLock = 0;
      pOpen->nPending = 0;
      pOpen->aPending = 0;
      pOld = vtk_sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
      if( pOld!=0 ){
        assert( pOld==pOpen );
        vtk_sqlite3ThreadSafeFree(pOpen);
        releaseLockInfo(pLock);
        rc = 1;
        goto exit_findlockinfo;
      }
    }else{
      pOpen->nRef++;
    }
    *ppOpen = pOpen;
  }

exit_findlockinfo:
  return rc;
}

#ifdef VTK_SQLITE_DEBUG
/*
** Helper function for printing out trace information from debugging
** binaries. This returns the string represetation of the supplied
** integer lock-type.
*/
static const char *locktypeName(int locktype){
  switch( locktype ){
  case NO_LOCK: return "NONE";
  case SHARED_LOCK: return "SHARED";
  case RESERVED_LOCK: return "RESERVED";
  case PENDING_LOCK: return "PENDING";
  case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  }
  return "ERROR";
}
#endif

/*
** If we are currently in a different thread than the thread that the
** unixFile argument belongs to, then transfer ownership of the unixFile
** over to the current thread.
**
** A unixFile is only owned by a thread on systems where one thread is
** unable to override locks created by a different thread.  RedHat9 is
** an example of such a system.
**
** Ownership transfer is only allowed if the unixFile is currently unlocked.
** If the unixFile is locked and an ownership is wrong, then return
** VTK_SQLITE_MISUSE.  VTK_SQLITE_OK is returned if everything works.
*/
#ifdef VTK_SQLITE_UNIX_THREADS
static int transferOwnership(unixFile *pFile){
  int rc;
  pthread_t hSelf;
  if( threadsOverrideEachOthersLocks ){
    /* Ownership transfers not needed on this system */
    return VTK_SQLITE_OK;
  }
  hSelf = pthread_self();
  if( pthread_equal(pFile->tid, hSelf) ){
    /* We are still in the same thread */
    OSTRACE1("No-transfer, same thread\n");
    return VTK_SQLITE_OK;
  }
  if( pFile->locktype!=NO_LOCK ){
    /* We cannot change ownership while we are holding a lock! */
    return VTK_SQLITE_MISUSE;
  }
  OSTRACE4("Transfer ownership of %d from %d to %d\n",
            pFile->h, pFile->tid, hSelf);
  pFile->tid = hSelf;
  if (pFile->pLock != NULL) {
    releaseLockInfo(pFile->pLock);
    rc = findLockInfo(pFile->h, &pFile->pLock, 0);
    OSTRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
           locktypeName(pFile->locktype),
           locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
    return rc;
  } else {
    return VTK_SQLITE_OK;
  }
}
#else
  /* On single-threaded builds, ownership transfer is a no-op */
# define transferOwnership(X) VTK_SQLITE_OK
#endif

/*
** Delete the named file
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3UnixDelete(const char *zFilename){
  SimulateIOError(return VTK_SQLITE_IOERR_DELETE);
  unlink(zFilename);
  return VTK_SQLITE_OK;
}

/*
** Return TRUE if the named file exists.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3UnixFileExists(const char *zFilename){
  return access(zFilename, 0)==0;
}

/* Forward declaration */
static int allocateUnixFile(
  int h,                    /* File descriptor of the open file */
  OsFile **pId,             /* Write the real file descriptor here */
  const char *zFilename,    /* Name of the file being opened */
  int delFlag               /* If true, make sure the file deletes on close */
);

/*
** Attempt to open a file for both reading and writing.  If that
** fails, try opening it read-only.  If the file does not exist,
** try to create it.
**
** On success, a handle for the open file is written to *id
** and *pReadonly is set to 0 if the file was opened for reading and
** writing or 1 if the file was opened read-only.  The function returns
** VTK_SQLITE_OK.
**
** On failure, the function returns VTK_SQLITE_CANTOPEN and leaves
** *id and *pReadonly unchanged.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3UnixOpenReadWrite(
  const char *zFilename,
  OsFile **pId,
  int *pReadonly
){
  int h;
  
  CRASH_TEST_OVERRIDE(vtk_sqlite3CrashOpenReadWrite, zFilename, pId, pReadonly);
  assert( 0==*pId );
  h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY,
                        VTK_SQLITE_DEFAULT_FILE_PERMISSIONS);
  if( h<0 ){
#ifdef EISDIR
    if( errno==EISDIR ){
      return VTK_SQLITE_CANTOPEN;
    }
#endif
    h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
    if( h<0 ){
      return VTK_SQLITE_CANTOPEN; 
    }
    *pReadonly = 1;
  }else{
    *pReadonly = 0;
  }
  return allocateUnixFile(h, pId, zFilename, 0);
}


/*
** Attempt to open a new file for exclusive access by this process.
** The file will be opened for both reading and writing.  To avoid
** a potential security problem, we do not allow the file to have
** previously existed.  Nor do we allow the file to be a symbolic
** link.
**
** If delFlag is true, then make arrangements to automatically delete
** the file when it is closed.
**
** On success, write the file handle into *id and return VTK_SQLITE_OK.
**
** On failure, return VTK_SQLITE_CANTOPEN.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3UnixOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
  int h;

  CRASH_TEST_OVERRIDE(vtk_sqlite3CrashOpenExclusive, zFilename, pId, delFlag);
  assert( 0==*pId );
  h = open(zFilename,
                O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY,
                delFlag ? 0600 : VTK_SQLITE_DEFAULT_FILE_PERMISSIONS);
  if( h<0 ){
    return VTK_SQLITE_CANTOPEN;
  }
  return allocateUnixFile(h, pId, zFilename, delFlag);
}

/*
** Attempt to open a new file for read-only access.
**
** On success, write the file handle into *id and return VTK_SQLITE_OK.
**
** On failure, return VTK_SQLITE_CANTOPEN.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3UnixOpenReadOnly(const char *zFilename, OsFile **pId){
  int h;
  
  CRASH_TEST_OVERRIDE(vtk_sqlite3CrashOpenReadOnly, zFilename, pId, 0);
  assert( 0==*pId );
  h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
  if( h<0 ){
    return VTK_SQLITE_CANTOPEN;
  }
  return allocateUnixFile(h, pId, zFilename, 0);
}

/*
** Attempt to open a file descriptor for the directory that contains a
** file.  This file descriptor can be used to fsync() the directory
** in order to make sure the creation of a new file is actually written
** to disk.
**
** This routine is only meaningful for Unix.  It is a no-op under
** windows since windows does not support hard links.
**
** If FULL_FSYNC is enabled, this function is not longer useful, 
** a FULL_FSYNC sync applies to all pending disk operations.
**
** On success, a handle for a previously open file at *id is
** updated with the new directory file descriptor and VTK_SQLITE_OK is
** returned.
**
** On failure, the function returns VTK_SQLITE_CANTOPEN and leaves
** *id unchanged.
*/
static int unixOpenDirectory(
  OsFile *id,
  const char *zDirname
){
  int h;
  unixFile *pFile = (unixFile*)id;
  assert( pFile!=0 );
  SET_THREADID(pFile);
  assert( pFile->dirfd<0 );
  pFile->dirfd = h = open(zDirname, O_RDONLY|O_BINARY, 0);
  if( h<0 ){
    return VTK_SQLITE_CANTOPEN; 
  }
#ifdef FD_CLOEXEC
  fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
#endif
  OSTRACE3("OPENDIR %-3d %s\n", h, zDirname);
  return VTK_SQLITE_OK;
}

/*
** Create a temporary file name in zBuf.  zBuf must be big enough to
** hold at least VTK_SQLITE_TEMPNAME_SIZE characters.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3UnixTempFileName(char *zBuf){
  static const char *azDirs[] = {
     0,
     "/var/tmp",
     "/usr/tmp",
     "/tmp",
     ".",
  };
  static const unsigned char zChars[] =
    "abcdefghijklmnopqrstuvwxyz"
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "0123456789";
  int i, j;
  struct stat buf;
  const char *zDir = ".";
  azDirs[0] = vtk_sqlite3_temp_directory;
  for(i=0; i<(int)(sizeof(azDirs)/sizeof(azDirs[0])); i++){
    if( azDirs[i]==0 ) continue;
    if( stat(azDirs[i], &buf) ) continue;
    if( !S_ISDIR(buf.st_mode) ) continue;
    if( access(azDirs[i], 07) ) continue;
    zDir = azDirs[i];
    break;
  }
  do{
    vtk_sqlite3_snprintf(VTK_SQLITE_TEMPNAME_SIZE, zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
    j = strlen(zBuf);
    vtk_sqlite3Randomness(15, &zBuf[j]);
    for(i=0; i<15; i++, j++){
      zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
    }
    zBuf[j] = 0;
  }while( access(zBuf,0)==0 );
  return VTK_SQLITE_OK; 
}

/*
** Check that a given pathname is a directory and is writable 
**
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3UnixIsDirWritable(char *zBuf){
#ifndef VTK_SQLITE_OMIT_PAGER_PRAGMAS
  struct stat buf;
  if( zBuf==0 ) return 0;
  if( zBuf[0]==0 ) return 0;
  if( stat(zBuf, &buf) ) return 0;
  if( !S_ISDIR(buf.st_mode) ) return 0;
  if( access(zBuf, 07) ) return 0;
#endif /* VTK_SQLITE_OMIT_PAGER_PRAGMAS */
  return 1;
}

/*
** Seek to the offset in id->offset then read cnt bytes into pBuf.
** Return the number of bytes actually read.  Update the offset.
*/
static int seekAndRead(unixFile *id, void *pBuf, int cnt){
  int got;
  i64 newOffset;
  TIMER_START;
#if defined(USE_PREAD)
  got = pread(id->h, pBuf, cnt, id->offset);
  SimulateIOError( got = -1 );
#elif defined(USE_PREAD64)
  got = pread64(id->h, pBuf, cnt, id->offset);
  SimulateIOError( got = -1 );
#else
  newOffset = lseek(id->h, id->offset, SEEK_SET);
  SimulateIOError( newOffset-- );
  if( newOffset!=id->offset ){
    return -1;
  }
  got = read(id->h, pBuf, cnt);
#endif
  TIMER_END;
  OSTRACE5("READ    %-3d %5d %7lld %d\n", id->h, got, id->offset, TIMER_ELAPSED);
  if( got>0 ){
    id->offset += got;
  }
  return got;
}

/*
** Read data from a file into a buffer.  Return VTK_SQLITE_OK if all
** bytes were read successfully and VTK_SQLITE_IOERR if anything goes
** wrong.
*/
static int unixRead(OsFile *id, void *pBuf, int amt){
  int got;
  assert( id );
  got = seekAndRead((unixFile*)id, pBuf, amt);
  if( got==amt ){
    return VTK_SQLITE_OK;
  }else if( got<0 ){
    return VTK_SQLITE_IOERR_READ;
  }else{
    memset(&((char*)pBuf)[got], 0, amt-got);
    return VTK_SQLITE_IOERR_SHORT_READ;
  }
}

/*
** Seek to the offset in id->offset then read cnt bytes into pBuf.
** Return the number of bytes actually read.  Update the offset.
*/
static int seekAndWrite(unixFile *id, const void *pBuf, int cnt){
  int got;
  i64 newOffset;
  TIMER_START;
#if defined(USE_PREAD)
  got = pwrite(id->h, pBuf, cnt, id->offset);
#elif defined(USE_PREAD64)
  got = pwrite64(id->h, pBuf, cnt, id->offset);
#else
  newOffset = lseek(id->h, id->offset, SEEK_SET);
  if( newOffset!=id->offset ){
    return -1;
  }
  got = write(id->h, pBuf, cnt);
#endif
  TIMER_END;
  OSTRACE5("WRITE   %-3d %5d %7lld %d\n", id->h, got, id->offset, TIMER_ELAPSED);
  if( got>0 ){
    id->offset += got;
  }
  return got;
}


/*
** Write data from a buffer into a file.  Return VTK_SQLITE_OK on success
** or some other error code on failure.
*/
static int unixWrite(OsFile *id, const void *pBuf, int amt){
  int wrote = 0;
  assert( id );
  assert( amt>0 );
  while( amt>0 && (wrote = seekAndWrite((unixFile*)id, pBuf, amt))>0 ){
    amt -= wrote;
    pBuf = &((char*)pBuf)[wrote];
  }
  SimulateIOError(( wrote=(-1), amt=1 ));
  SimulateDiskfullError(( wrote=0, amt=1 ));
  if( amt>0 ){
    if( wrote<0 ){
      return VTK_SQLITE_IOERR_WRITE;
    }else{
      return VTK_SQLITE_FULL;
    }
  }
  return VTK_SQLITE_OK;
}

/*
** Move the read/write pointer in a file.
*/
static int unixSeek(OsFile *id, i64 offset){
  assert( id );
#ifdef VTK_SQLITE_TEST
  if( offset ) SimulateDiskfullError(return VTK_SQLITE_FULL);
#endif
  ((unixFile*)id)->offset = offset;
  return VTK_SQLITE_OK;
}

#ifdef VTK_SQLITE_TEST
/*
** Count the number of fullsyncs and normal syncs.  This is used to test
** that syncs and fullsyncs are occuring at the right times.
*/
int vtk_sqlite3_sync_count = 0;
int vtk_sqlite3_fullsync_count = 0;
#endif

/*
** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
** Otherwise use fsync() in its place.
*/
#ifndef HAVE_FDATASYNC
# define fdatasync fsync
#endif

/*
** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
** only available on Mac OS X.  But that could change.
*/
#ifdef F_FULLFSYNC
# define HAVE_FULLFSYNC 1
#else
# define HAVE_FULLFSYNC 0
#endif


/*
** The fsync() system call does not work as advertised on many
** unix systems.  The following procedure is an attempt to make
** it work better.
**
** The VTK_SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
** for testing when we want to run through the test suite quickly.
** You are strongly advised *not* to deploy with VTK_SQLITE_NO_SYNC
** enabled, however, since with VTK_SQLITE_NO_SYNC enabled, an OS crash
** or power failure will likely corrupt the database file.
*/
static int full_fsync(int fd, int fullSync, int dataOnly){
  int rc;
  
  (void)fullSync; (void)dataOnly; /* use args */

  /* Record the number of times that we do a normal fsync() and 
  ** FULLSYNC.  This is used during testing to verify that this procedure
  ** gets called with the correct arguments.
  */
#ifdef VTK_SQLITE_TEST
  if( fullSync ) vtk_sqlite3_fullsync_count++;
  vtk_sqlite3_sync_count++;
#endif

  /* If we compiled with the VTK_SQLITE_NO_SYNC flag, then syncing is a
  ** no-op
  */
#ifdef VTK_SQLITE_NO_SYNC
  rc = VTK_SQLITE_OK;
#else

#if HAVE_FULLFSYNC
  if( fullSync ){
    rc = fcntl(fd, F_FULLFSYNC, 0);
  }else{
    rc = 1;
  }
  /* If the FULLFSYNC failed, fall back to attempting an fsync().
   * It shouldn't be possible for fullfsync to fail on the local 
   * file system (on OSX), so failure indicates that FULLFSYNC
   * isn't supported for this file system. So, attempt an fsync 
   * and (for now) ignore the overhead of a superfluous fcntl call.  
   * It'd be better to detect fullfsync support once and avoid 
   * the fcntl call every time sync is called.
   */
  if( rc ) rc = fsync(fd);

#else 
  if( dataOnly ){
    rc = fdatasync(fd);
  }else{
    rc = fsync(fd);
  }
#endif /* HAVE_FULLFSYNC */
#endif /* defined(VTK_SQLITE_NO_SYNC) */

  return rc;
}

/*
** Make sure all writes to a particular file are committed to disk.
**
** If dataOnly==0 then both the file itself and its metadata (file
** size, access time, etc) are synced.  If dataOnly!=0 then only the
** file data is synced.
**
** Under Unix, also make sure that the directory entry for the file
** has been created by fsync-ing the directory that contains the file.
** If we do not do this and we encounter a power failure, the directory
** entry for the journal might not exist after we reboot.  The next
** Vtk_Sqlite to access the file will not know that the journal exists (because
** the directory entry for the journal was never created) and the transaction
** will not roll back - possibly leading to database corruption.
*/
static int unixSync(OsFile *id, int dataOnly){
  int rc;
  unixFile *pFile = (unixFile*)id;
  assert( pFile );
  OSTRACE2("SYNC    %-3d\n", pFile->h);
  rc = full_fsync(pFile->h, pFile->fullSync, dataOnly);
  SimulateIOError( rc=1 );
  if( rc ){
    return VTK_SQLITE_IOERR_FSYNC;
  }
  if( pFile->dirfd>=0 ){
    OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
            HAVE_FULLFSYNC, pFile->fullSync);
#ifndef VTK_SQLITE_DISABLE_DIRSYNC
    /* The directory sync is only attempted if full_fsync is
    ** turned off or unavailable.  If a full_fsync occurred above,
    ** then the directory sync is superfluous.
    */
    if( (!HAVE_FULLFSYNC || !pFile->fullSync) && full_fsync(pFile->dirfd,0,0) ){
       /*
       ** We have received multiple reports of fsync() returning
       ** errors when applied to directories on certain file systems.
       ** A failed directory sync is not a big deal.  So it seems
       ** better to ignore the error.  Ticket #1657
       */
       /* return VTK_SQLITE_IOERR; */
    }
#endif
    close(pFile->dirfd);  /* Only need to sync once, so close the directory */
    pFile->dirfd = -1;    /* when we are done. */
  }
  return VTK_SQLITE_OK;
}

/*
** Sync the directory zDirname. This is a no-op on operating systems other
** than UNIX.
**
** This is used to make sure the master journal file has truely been deleted
** before making changes to individual journals on a multi-database commit.
** The F_FULLFSYNC option is not needed here.
*/
VTK_SQLITE_PRIVATE int vtk_sqlite3UnixSyncDirectory(const char *zDirname){
#ifdef VTK_SQLITE_DISABLE_DIRSYNC
  return VTK_SQLITE_OK;
#else
  int fd;
  int r;
  fd = open(zDirname, O_RDONLY|O_BINARY, 0);
  OSTRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
  if( fd<0 ){
    return VTK_SQLITE_CANTOPEN; 
  }
  r = fsync(fd);
  close(fd);
  SimulateIOError( r=1 );
  if( r ){
    return VTK_SQLITE_IOERR_DIR_FSYNC;
  }else{
    return VTK_SQLITE_OK;
  }
#endif
}

/*
** Truncate an open file to a specified size
*/
static int unixTruncate(OsFile *id, i64 nByte){
  int rc;
  assert( id );
  rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
  SimulateIOError( rc=1 );
  if( rc ){
    return VTK_SQLITE_IOERR_TRUNCATE;
  }else{
    return VTK_SQLITE_OK;
  }
}

/*
** Determine the current size of a file in bytes
*/
static int unixFileSize(OsFile *id, i64 *pSize){
  int rc;
  struct stat buf;
  assert( id );
  rc = fstat(((unixFile*)id)->h, &buf);
  SimulateIOError( rc=1 );
  if( rc!=0 ){
    return VTK_SQLITE_IOERR_FSTAT;
  }
  *pSize = buf.st_size;
  return VTK_SQLITE_OK;
}

/*
** This routine checks if there is a RESERVED lock held on the specified
** file by this or any other process. If such a lock is held, return
** non-zero.  If the file is unlocked or holds only SHARED locks, then
** return zero.
*/
static int unixCheckReservedLock(OsFile *id){
  int r = 0;
  unixFile *pFile = (unixFile*)id;

  assert( pFile );
  vtk_sqlite3OsEnterMutex(); /* Because pFile->pLock is shared across threads */

  /* Check if a thread in this process holds such a lock */
  if( pFile->pLock->locktype>SHARED_LOCK ){
    r = 1;
  }

  /* Otherwise see if some other process holds it.
  */
  if( !r ){
    struct flock lock;
    lock.l_whence = SEEK_SET;
    lock.l_start = RESERVED_BYTE;
    lock.l_len = 1;
    lock.l_type = F_WRLCK;
    fcntl(pFile->h, F_GETLK, &lock);
    if( lock.l_type!=F_UNLCK ){
      r = 1;
    }
  }
  
  vtk_sqlite3OsLeaveMutex();
  OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);

  return r;
}

/*
** Lock the file with the lock specified by parameter locktype - one
** of the following:
**
**     (1) SHARED_LOCK
**     (2) RESERVED_LOCK
**     (3) PENDING_LOCK
**     (4) EXCLUSIVE_LOCK
**
** Sometimes when requesting one lock state, additional lock states
** are inserted in between.  The locking might fail on one of the later
** transitions leaving the lock state different from what it started but
** still short of its goal.  The following chart shows the allowed
** transitions and the inserted intermediate states:
**
**    UNLOCKED -> SHARED
**    SHARED -> RESERVED
**    SHARED -> (PENDING) -> EXCLUSIVE
**    RESERVED -> (PENDING) -> EXCLUSIVE
**    PENDING -> EXCLUSIVE
**
** This routine will only increase a lock.  Use the vtk_sqlite3OsUnlock()
** routine to lower a locking level.
*/
static int unixLock(OsFile *id, int locktype){
  /* The following describes the implementation of the various locks and
  ** lock transitions in terms of the POSIX advisory shared and exclusive
  ** lock primitives (called read-locks and write-locks below, to avoid
  ** confusion with Vtk_Sqlite lock names). The algorithms are complicated
  ** slightly in order to be compatible with windows systems simultaneously
  ** accessing the same database file, in case that is ever required.
  **
  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  ** byte', each single bytes at well known offsets, and the 'shared byte
  ** range', a range of 510 bytes at a well known offset.
  **
  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  ** byte'.  If this is successful, a random byte from the 'shared byte
  ** range' is read-locked and the lock on the 'pending byte' released.
  **
  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  ** A RESERVED lock is implemented by grabbing a write-lock on the
  ** 'reserved byte'. 
  **
  ** A process may only obtain a PENDING lock after it has obtained a
  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  ** on the 'pending byte'. This ensures that no new SHARED locks can be
  ** obtained, but existing SHARED locks are allowed to persist. A process
  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  ** This property is used by the algorithm for rolling back a journal file
  ** after a crash.
  **
  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  ** implemented by obtaining a write-lock on the entire 'shared byte
  ** range'. Since all other locks require a read-lock on one of the bytes
  ** within this range, this ensures that no other locks are held on the
  ** database. 
  **
  ** The reason a single byte cannot be used instead of the 'shared byte
  ** range' is that some versions of windows do not support read-locks. By
  ** locking a random byte from a range, concurrent SHARED locks may exist
  ** even if the locking primitive used is always a write-lock.
  */
  int rc = VTK_SQLITE_OK;
  unixFile *pFile = (unixFile*)id;
  struct lockInfo *pLock = pFile->pLock;
  struct flock lock;
  int s;

  assert( pFile );
  OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d\n", pFile->h,
      locktypeName(locktype), locktypeName(pFile->locktype),
      locktypeName(pLock->locktype), pLock->cnt , getpid());

  /* If there is already a lock of this type or more restrictive on the
  ** OsFile, do nothing. Don't use the end_lock: exit path, as
  ** vtk_sqlite3OsEnterMutex() hasn't been called yet.
  */
  if( pFile->locktype>=locktype ){
    OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
            locktypeName(locktype));
    return VTK_SQLITE_OK;
  }

  /* Make sure the locking sequence is correct
  */
  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  assert( locktype!=PENDING_LOCK );
  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );

  /* This mutex is needed because pFile->pLock is shared across threads
  */
  vtk_sqlite3OsEnterMutex();

  /* Make sure the current thread owns the pFile.
  */
  rc = transferOwnership(pFile);
  if( rc!=VTK_SQLITE_OK ){
    vtk_sqlite3OsLeaveMutex();
    return rc;
  }
  pLock = pFile->pLock;

  /* If some thread using this PID has a lock via a different OsFile*
  ** handle that precludes the requested lock, return BUSY.
  */
  if( (pFile->locktype!=pLock->locktype && 
          (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
  ){
    rc = VTK_SQLITE_BUSY;
    goto end_lock;
  }

  /* If a SHARED lock is requested, and some thread using this PID already
  ** has a SHARED or RESERVED lock, then increment reference counts and
  ** return VTK_SQLITE_OK.
  */
  if( locktype==SHARED_LOCK && 
      (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
    assert( locktype==SHARED_LOCK );
    assert( pFile->locktype==0 );
    assert( pLock->cnt>0 );
    pFile->locktype = SHARED_LOCK;
    pLock->cnt++;
    pFile->pOpen->nLock++;
    goto end_lock;
  }

  lock.l_len = 1L;

  lock.l_whence = SEEK_SET;

  /* A PENDING lock is needed before acquiring a SHARED lock and before
  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
  ** be released.
  */
  if( locktype==SHARED_LOCK 
      || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
  ){
    lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
    lock.l_start = PENDING_BYTE;
    s = fcntl(pFile->h, F_SETLK, &lock);
    if( s==(-1) ){
      rc = (errno==EINVAL) ? VTK_SQLITE_NOLFS : VTK_SQLITE_BUSY;
      goto end_lock;
    }
  }


  /* If control gets to this point, then actually go ahead and make
  ** operating system calls for the specified lock.
  */
  if( locktype==SHARED_LOCK ){
    assert( pLock->cnt==0 );
    assert( pLock->locktype==0 );

    /* Now get the read-lock */
    lock.l_start = SHARED_FIRST;
    lock.l_len = SHARED_SIZE;
    s = fcntl(pFile->h, F_SETLK, &lock);

    /* Drop the temporary PENDING lock */
    lock.l_start = PENDING_BYTE;
    lock.l_len = 1L;
    lock.l_type = F_UNLCK;
    if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
      rc = VTK_SQLITE_IOERR_UNLOCK;  /* This should never happen */
      goto end_lock;
    }
    if( s==(-1) ){
      rc = (errno==EINVAL) ? VTK_SQLITE_NOLFS : VTK_SQLITE_BUSY;
    }<