sqliteInt.h.svn-base
上传用户:sunhongbo
上传日期:2022-01-25
资源大小:3010k
文件大小:93k
源码类别:

数据库系统

开发平台:

C/C++

  1. /*
  2. ** 2001 September 15
  3. **
  4. ** The author disclaims copyright to this source code.  In place of
  5. ** a legal notice, here is a blessing:
  6. **
  7. **    May you do good and not evil.
  8. **    May you find forgiveness for yourself and forgive others.
  9. **    May you share freely, never taking more than you give.
  10. **
  11. *************************************************************************
  12. ** Internal interface definitions for SQLite.
  13. **
  14. ** @(#) $Id: sqliteInt.h,v 1.693 2008/04/15 14:36:42 drh Exp $
  15. */
  16. #ifndef _SQLITEINT_H_
  17. #define _SQLITEINT_H_
  18. /*
  19. ** Include the configuration header output by 'configure' if it was run
  20. ** (otherwise we get an empty default).
  21. */
  22. #include "config.h"
  23. #include "sqliteLimit.h"
  24. /* Disable nuisance warnings on Borland compilers */
  25. #if defined(__BORLANDC__)
  26. #pragma warn -rch /* unreachable code */
  27. #pragma warn -ccc /* Condition is always true or false */
  28. #pragma warn -aus /* Assigned value is never used */
  29. #pragma warn -csu /* Comparing signed and unsigned */
  30. #pragma warn -spa /* Suspicous pointer arithmetic */
  31. #endif
  32. /* Needed for various definitions... */
  33. #define _GNU_SOURCE
  34. /*
  35. ** Include standard header files as necessary
  36. */
  37. #ifdef HAVE_STDINT_H
  38. #include <stdint.h>
  39. #endif
  40. #ifdef HAVE_INTTYPES_H
  41. #include <inttypes.h>
  42. #endif
  43. /*
  44. ** If possible, use the C99 intptr_t type to define an integral type of
  45. ** equivalent size to a pointer.  (Technically it's >= sizeof(void *), but
  46. ** practically it's == sizeof(void *)).  We fall back to an int if this type
  47. ** isn't defined.
  48. */
  49. #ifdef HAVE_INTPTR_T
  50.   typedef intptr_t sqlite3_intptr_t;
  51. #else
  52.   typedef int sqlite3_intptr_t;
  53. #endif
  54. /*
  55. ** A macro used to aid in coverage testing.  When doing coverage
  56. ** testing, the condition inside the argument must be evaluated 
  57. ** both true and false in order to get full branch coverage.
  58. ** This macro can be inserted to ensure adequate test coverage
  59. ** in places where simple condition/decision coverage is inadequate.
  60. */
  61. #ifdef SQLITE_COVERAGE_TEST
  62.   void sqlite3Coverage(int);
  63. # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
  64. #else
  65. # define testcase(X)
  66. #endif
  67. /*
  68. ** The macro unlikely() is a hint that surrounds a boolean
  69. ** expression that is usually false.  Macro likely() surrounds
  70. ** a boolean expression that is usually true.  GCC is able to
  71. ** use these hints to generate better code, sometimes.
  72. */
  73. #if defined(__GNUC__) && 0
  74. # define likely(X)    __builtin_expect((X),1)
  75. # define unlikely(X)  __builtin_expect((X),0)
  76. #else
  77. # define likely(X)    !!(X)
  78. # define unlikely(X)  !!(X)
  79. #endif
  80. /*
  81. ** These #defines should enable >2GB file support on Posix if the
  82. ** underlying operating system supports it.  If the OS lacks
  83. ** large file support, or if the OS is windows, these should be no-ops.
  84. **
  85. ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
  86. ** system #includes.  Hence, this block of code must be the very first
  87. ** code in all source files.
  88. **
  89. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  90. ** on the compiler command line.  This is necessary if you are compiling
  91. ** on a recent machine (ex: RedHat 7.2) but you want your code to work
  92. ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
  93. ** without this option, LFS is enable.  But LFS does not exist in the kernel
  94. ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
  95. ** portability you should omit LFS.
  96. **
  97. ** Similar is true for MacOS.  LFS is only supported on MacOS 9 and later.
  98. */
  99. #ifndef SQLITE_DISABLE_LFS
  100. # define _LARGE_FILE       1
  101. # ifndef _FILE_OFFSET_BITS
  102. #   define _FILE_OFFSET_BITS 64
  103. # endif
  104. # define _LARGEFILE_SOURCE 1
  105. #endif
  106. /*
  107. ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
  108. ** Older versions of SQLite used an optional THREADSAFE macro.
  109. ** We support that for legacy
  110. */
  111. #if !defined(SQLITE_THREADSAFE)
  112. #if defined(THREADSAFE)
  113. # define SQLITE_THREADSAFE THREADSAFE
  114. #else
  115. # define SQLITE_THREADSAFE 0
  116. #endif
  117. #endif
  118. /*
  119. ** Exactly one of the following macros must be defined in order to
  120. ** specify which memory allocation subsystem to use.
  121. **
  122. **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
  123. **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
  124. **     SQLITE_MEMORY_SIZE            // internal allocator #1
  125. **     SQLITE_MMAP_HEAP_SIZE         // internal mmap() allocator
  126. **     SQLITE_POW2_MEMORY_SIZE       // internal power-of-two allocator
  127. **
  128. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  129. ** the default.
  130. */
  131. #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+
  132.     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+
  133.     defined(SQLITE_POW2_MEMORY_SIZE)>1
  134. # error "At most one of the following compile-time configuration options
  135.  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,
  136.  SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE"
  137. #endif
  138. #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+
  139.     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+
  140.     defined(SQLITE_POW2_MEMORY_SIZE)==0
  141. # define SQLITE_SYSTEM_MALLOC 1
  142. #endif
  143. /*
  144. ** If SQLITE_MALLOC_SOFT_LIMIT is defined, then try to keep the
  145. ** sizes of memory allocations below this value where possible.
  146. */
  147. #if defined(SQLITE_POW2_MEMORY_SIZE) && !defined(SQLITE_MALLOC_SOFT_LIMIT)
  148. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  149. #endif
  150. /*
  151. ** We need to define _XOPEN_SOURCE as follows in order to enable
  152. ** recursive mutexes on most unix systems.  But Mac OS X is different.
  153. ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
  154. ** so it is omitted there.  See ticket #2673.
  155. **
  156. ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
  157. ** implemented on some systems.  So we avoid defining it at all
  158. ** if it is already defined or if it is unneeded because we are
  159. ** not doing a threadsafe build.  Ticket #2681.
  160. **
  161. ** See also ticket #2741.
  162. */
  163. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
  164. #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
  165. #endif
  166. #if defined(SQLITE_TCL) || defined(TCLSH)
  167. # include <tcl.h>
  168. #endif
  169. /*
  170. ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
  171. ** Setting NDEBUG makes the code smaller and run faster.  So the following
  172. ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
  173. ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
  174. ** feature.
  175. */
  176. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
  177. # define NDEBUG 1
  178. #endif
  179. #include "sqlite3.h"
  180. #include "hash.h"
  181. #include "parse.h"
  182. #include <stdio.h>
  183. #include <stdlib.h>
  184. #include <string.h>
  185. #include <assert.h>
  186. #include <stddef.h>
  187. #define sqlite3_isnan(X)  ((X)!=(X))
  188. /*
  189. ** If compiling for a processor that lacks floating point support,
  190. ** substitute integer for floating-point
  191. */
  192. #ifdef SQLITE_OMIT_FLOATING_POINT
  193. # define double sqlite_int64
  194. # define LONGDOUBLE_TYPE sqlite_int64
  195. # ifndef SQLITE_BIG_DBL
  196. #   define SQLITE_BIG_DBL (0x7fffffffffffffff)
  197. # endif
  198. # define SQLITE_OMIT_DATETIME_FUNCS 1
  199. # define SQLITE_OMIT_TRACE 1
  200. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  201. #endif
  202. #ifndef SQLITE_BIG_DBL
  203. # define SQLITE_BIG_DBL (1e99)
  204. #endif
  205. /*
  206. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  207. ** afterward. Having this macro allows us to cause the C compiler 
  208. ** to omit code used by TEMP tables without messy #ifndef statements.
  209. */
  210. #ifdef SQLITE_OMIT_TEMPDB
  211. #define OMIT_TEMPDB 1
  212. #else
  213. #define OMIT_TEMPDB 0
  214. #endif
  215. /*
  216. ** If the following macro is set to 1, then NULL values are considered
  217. ** distinct when determining whether or not two entries are the same
  218. ** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
  219. ** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
  220. ** is the way things are suppose to work.
  221. **
  222. ** If the following macro is set to 0, the NULLs are indistinct for
  223. ** a UNIQUE index.  In this mode, you can only have a single NULL entry
  224. ** for a column declared UNIQUE.  This is the way Informix and SQL Server
  225. ** work.
  226. */
  227. #define NULL_DISTINCT_FOR_UNIQUE 1
  228. /*
  229. ** The "file format" number is an integer that is incremented whenever
  230. ** the VDBE-level file format changes.  The following macros define the
  231. ** the default file format for new databases and the maximum file format
  232. ** that the library can read.
  233. */
  234. #define SQLITE_MAX_FILE_FORMAT 4
  235. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  236. # define SQLITE_DEFAULT_FILE_FORMAT 1
  237. #endif
  238. /*
  239. ** Provide a default value for TEMP_STORE in case it is not specified
  240. ** on the command-line
  241. */
  242. #ifndef TEMP_STORE
  243. # define TEMP_STORE 1
  244. #endif
  245. /*
  246. ** GCC does not define the offsetof() macro so we'll have to do it
  247. ** ourselves.
  248. */
  249. #ifndef offsetof
  250. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  251. #endif
  252. /*
  253. ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
  254. ** not, there are still machines out there that use EBCDIC.)
  255. */
  256. #if 'A' == '301'
  257. # define SQLITE_EBCDIC 1
  258. #else
  259. # define SQLITE_ASCII 1
  260. #endif
  261. /*
  262. ** Integers of known sizes.  These typedefs might change for architectures
  263. ** where the sizes very.  Preprocessor macros are available so that the
  264. ** types can be conveniently redefined at compile-type.  Like this:
  265. **
  266. **         cc '-DUINTPTR_TYPE=long long int' ...
  267. */
  268. #ifndef UINT32_TYPE
  269. # ifdef HAVE_UINT32_T
  270. #  define UINT32_TYPE uint32_t
  271. # else
  272. #  define UINT32_TYPE unsigned int
  273. # endif
  274. #endif
  275. #ifndef UINT16_TYPE
  276. # ifdef HAVE_UINT16_T
  277. #  define UINT16_TYPE uint16_t
  278. # else
  279. #  define UINT16_TYPE unsigned short int
  280. # endif
  281. #endif
  282. #ifndef INT16_TYPE
  283. # ifdef HAVE_INT16_T
  284. #  define INT16_TYPE int16_t
  285. # else
  286. #  define INT16_TYPE short int
  287. # endif
  288. #endif
  289. #ifndef UINT8_TYPE
  290. # ifdef HAVE_UINT8_T
  291. #  define UINT8_TYPE uint8_t
  292. # else
  293. #  define UINT8_TYPE unsigned char
  294. # endif
  295. #endif
  296. #ifndef INT8_TYPE
  297. # ifdef HAVE_INT8_T
  298. #  define INT8_TYPE int8_t
  299. # else
  300. #  define INT8_TYPE signed char
  301. # endif
  302. #endif
  303. #ifndef LONGDOUBLE_TYPE
  304. # define LONGDOUBLE_TYPE long double
  305. #endif
  306. typedef sqlite_int64 i64;          /* 8-byte signed integer */
  307. typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
  308. typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
  309. typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
  310. typedef INT16_TYPE i16;            /* 2-byte signed integer */
  311. typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
  312. typedef UINT8_TYPE i8;             /* 1-byte signed integer */
  313. /*
  314. ** Macros to determine whether the machine is big or little endian,
  315. ** evaluated at runtime.
  316. */
  317. #ifdef SQLITE_AMALGAMATION
  318. const int sqlite3one;
  319. #else
  320. extern const int sqlite3one;
  321. #endif
  322. #if defined(i386) || defined(__i386__) || defined(_M_IX86)
  323. # define SQLITE_BIGENDIAN    0
  324. # define SQLITE_LITTLEENDIAN 1
  325. # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
  326. #else
  327. # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
  328. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  329. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  330. #endif
  331. /*
  332. ** An instance of the following structure is used to store the busy-handler
  333. ** callback for a given sqlite handle. 
  334. **
  335. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  336. ** callback for the database handle. Each pager opened via the sqlite
  337. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  338. ** callback is currently invoked only from within pager.c.
  339. */
  340. typedef struct BusyHandler BusyHandler;
  341. struct BusyHandler {
  342.   int (*xFunc)(void *,int);  /* The busy callback */
  343.   void *pArg;                /* First arg to busy callback */
  344.   int nBusy;                 /* Incremented with each busy call */
  345. };
  346. /*
  347. ** Name of the master database table.  The master database table
  348. ** is a special table that holds the names and attributes of all
  349. ** user tables and indices.
  350. */
  351. #define MASTER_NAME       "sqlite_master"
  352. #define TEMP_MASTER_NAME  "sqlite_temp_master"
  353. /*
  354. ** The root-page of the master database table.
  355. */
  356. #define MASTER_ROOT       1
  357. /*
  358. ** The name of the schema table.
  359. */
  360. #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  361. /*
  362. ** A convenience macro that returns the number of elements in
  363. ** an array.
  364. */
  365. #define ArraySize(X)    (sizeof(X)/sizeof(X[0]))
  366. /*
  367. ** Forward references to structures
  368. */
  369. typedef struct AggInfo AggInfo;
  370. typedef struct AuthContext AuthContext;
  371. typedef struct Bitvec Bitvec;
  372. typedef struct CollSeq CollSeq;
  373. typedef struct Column Column;
  374. typedef struct Db Db;
  375. typedef struct Schema Schema;
  376. typedef struct Expr Expr;
  377. typedef struct ExprList ExprList;
  378. typedef struct FKey FKey;
  379. typedef struct FuncDef FuncDef;
  380. typedef struct IdList IdList;
  381. typedef struct Index Index;
  382. typedef struct KeyClass KeyClass;
  383. typedef struct KeyInfo KeyInfo;
  384. typedef struct Module Module;
  385. typedef struct NameContext NameContext;
  386. typedef struct Parse Parse;
  387. typedef struct Select Select;
  388. typedef struct SrcList SrcList;
  389. typedef struct StrAccum StrAccum;
  390. typedef struct Table Table;
  391. typedef struct TableLock TableLock;
  392. typedef struct Token Token;
  393. typedef struct TriggerStack TriggerStack;
  394. typedef struct TriggerStep TriggerStep;
  395. typedef struct Trigger Trigger;
  396. typedef struct WhereInfo WhereInfo;
  397. typedef struct WhereLevel WhereLevel;
  398. /*
  399. ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
  400. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  401. ** pointer types (i.e. FuncDef) defined above.
  402. */
  403. #include "btree.h"
  404. #include "vdbe.h"
  405. #include "pager.h"
  406. #include "os.h"
  407. #include "mutex.h"
  408. /*
  409. ** Each database file to be accessed by the system is an instance
  410. ** of the following structure.  There are normally two of these structures
  411. ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
  412. ** aDb[1] is the database file used to hold temporary tables.  Additional
  413. ** databases may be attached.
  414. */
  415. struct Db {
  416.   char *zName;         /* Name of this database */
  417.   Btree *pBt;          /* The B*Tree structure for this database file */
  418.   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
  419.   u8 safety_level;     /* How aggressive at synching data to disk */
  420.   void *pAux;               /* Auxiliary data.  Usually NULL */
  421.   void (*xFreeAux)(void*);  /* Routine to free pAux */
  422.   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
  423. };
  424. /*
  425. ** An instance of the following structure stores a database schema.
  426. **
  427. ** If there are no virtual tables configured in this schema, the
  428. ** Schema.db variable is set to NULL. After the first virtual table
  429. ** has been added, it is set to point to the database connection 
  430. ** used to create the connection. Once a virtual table has been
  431. ** added to the Schema structure and the Schema.db variable populated, 
  432. ** only that database connection may use the Schema to prepare 
  433. ** statements.
  434. */
  435. struct Schema {
  436.   int schema_cookie;   /* Database schema version number for this file */
  437.   Hash tblHash;        /* All tables indexed by name */
  438.   Hash idxHash;        /* All (named) indices indexed by name */
  439.   Hash trigHash;       /* All triggers indexed by name */
  440.   Hash aFKey;          /* Foreign keys indexed by to-table */
  441.   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
  442.   u8 file_format;      /* Schema format version for this file */
  443.   u8 enc;              /* Text encoding used by this database */
  444.   u16 flags;           /* Flags associated with this schema */
  445.   int cache_size;      /* Number of pages to use in the cache */
  446. #ifndef SQLITE_OMIT_VIRTUALTABLE
  447.   sqlite3 *db;         /* "Owner" connection. See comment above */
  448. #endif
  449. };
  450. /*
  451. ** These macros can be used to test, set, or clear bits in the 
  452. ** Db.flags field.
  453. */
  454. #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
  455. #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
  456. #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
  457. #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
  458. /*
  459. ** Allowed values for the DB.flags field.
  460. **
  461. ** The DB_SchemaLoaded flag is set after the database schema has been
  462. ** read into internal hash tables.
  463. **
  464. ** DB_UnresetViews means that one or more views have column names that
  465. ** have been filled out.  If the schema changes, these column names might
  466. ** changes and so the view will need to be reset.
  467. */
  468. #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
  469. #define DB_UnresetViews    0x0002  /* Some views have defined column names */
  470. #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
  471. /*
  472. ** The number of different kinds of things that can be limited
  473. ** using the sqlite3_limit() interface.
  474. */
  475. #define SQLITE_N_LIMIT (SQLITE_LIMIT_VARIABLE_NUMBER+1)
  476. /*
  477. ** Each database is an instance of the following structure.
  478. **
  479. ** The sqlite.lastRowid records the last insert rowid generated by an
  480. ** insert statement.  Inserts on views do not affect its value.  Each
  481. ** trigger has its own context, so that lastRowid can be updated inside
  482. ** triggers as usual.  The previous value will be restored once the trigger
  483. ** exits.  Upon entering a before or instead of trigger, lastRowid is no
  484. ** longer (since after version 2.8.12) reset to -1.
  485. **
  486. ** The sqlite.nChange does not count changes within triggers and keeps no
  487. ** context.  It is reset at start of sqlite3_exec.
  488. ** The sqlite.lsChange represents the number of changes made by the last
  489. ** insert, update, or delete statement.  It remains constant throughout the
  490. ** length of a statement and is then updated by OP_SetCounts.  It keeps a
  491. ** context stack just like lastRowid so that the count of changes
  492. ** within a trigger is not seen outside the trigger.  Changes to views do not
  493. ** affect the value of lsChange.
  494. ** The sqlite.csChange keeps track of the number of current changes (since
  495. ** the last statement) and is used to update sqlite_lsChange.
  496. **
  497. ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
  498. ** store the most recent error code and, if applicable, string. The
  499. ** internal function sqlite3Error() is used to set these variables
  500. ** consistently.
  501. */
  502. struct sqlite3 {
  503.   sqlite3_vfs *pVfs;            /* OS Interface */
  504.   int nDb;                      /* Number of backends currently in use */
  505.   Db *aDb;                      /* All backends */
  506.   int flags;                    /* Miscellanous flags. See below */
  507.   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
  508.   int errCode;                  /* Most recent error code (SQLITE_*) */
  509.   int errMask;                  /* & result codes with this before returning */
  510.   u8 autoCommit;                /* The auto-commit flag. */
  511.   u8 temp_store;                /* 1: file 2: memory 0: default */
  512.   u8 mallocFailed;              /* True if we have seen a malloc failure */
  513.   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
  514.   int nextPagesize;             /* Pagesize after VACUUM if >0 */
  515.   int nTable;                   /* Number of tables in the database */
  516.   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
  517.   i64 lastRowid;                /* ROWID of most recent insert (see above) */
  518.   i64 priorNewRowid;            /* Last randomly generated ROWID */
  519.   int magic;                    /* Magic number for detect library misuse */
  520.   int nChange;                  /* Value returned by sqlite3_changes() */
  521.   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
  522.   sqlite3_mutex *mutex;         /* Connection mutex */
  523.   int aLimit[SQLITE_N_LIMIT];   /* Limits */
  524.   struct sqlite3InitInfo {      /* Information used during initialization */
  525.     int iDb;                    /* When back is being initialized */
  526.     int newTnum;                /* Rootpage of table being initialized */
  527.     u8 busy;                    /* TRUE if currently initializing */
  528.   } init;
  529.   int nExtension;               /* Number of loaded extensions */
  530.   void **aExtension;            /* Array of shared libraray handles */
  531.   struct Vdbe *pVdbe;           /* List of active virtual machines */
  532.   int activeVdbeCnt;            /* Number of vdbes currently executing */
  533.   void (*xTrace)(void*,const char*);        /* Trace function */
  534.   void *pTraceArg;                          /* Argument to the trace function */
  535.   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
  536.   void *pProfileArg;                        /* Argument to profile function */
  537.   void *pCommitArg;                 /* Argument to xCommitCallback() */   
  538.   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
  539.   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
  540.   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  541.   void *pUpdateArg;
  542.   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  543.   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  544.   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  545.   void *pCollNeededArg;
  546.   sqlite3_value *pErr;          /* Most recent error message */
  547.   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
  548.   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
  549.   union {
  550.     int isInterrupted;          /* True if sqlite3_interrupt has been called */
  551.     double notUsed1;            /* Spacer */
  552.   } u1;
  553. #ifndef SQLITE_OMIT_AUTHORIZATION
  554.   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  555.                                 /* Access authorization function */
  556.   void *pAuthArg;               /* 1st argument to the access auth function */
  557. #endif
  558. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  559.   int (*xProgress)(void *);     /* The progress callback */
  560.   void *pProgressArg;           /* Argument to the progress callback */
  561.   int nProgressOps;             /* Number of opcodes for progress callback */
  562. #endif
  563. #ifndef SQLITE_OMIT_VIRTUALTABLE
  564.   Hash aModule;                 /* populated by sqlite3_create_module() */
  565.   Table *pVTab;                 /* vtab with active Connect/Create method */
  566.   sqlite3_vtab **aVTrans;       /* Virtual tables with open transactions */
  567.   int nVTrans;                  /* Allocated size of aVTrans */
  568. #endif
  569.   Hash aFunc;                   /* All functions that can be in SQL exprs */
  570.   Hash aCollSeq;                /* All collating sequences */
  571.   BusyHandler busyHandler;      /* Busy callback */
  572.   int busyTimeout;              /* Busy handler timeout, in msec */
  573.   Db aDbStatic[2];              /* Static space for the 2 default backends */
  574. #ifdef SQLITE_SSE
  575.   sqlite3_stmt *pFetch;         /* Used by SSE to fetch stored statements */
  576. #endif
  577.   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
  578. };
  579. /*
  580. ** A macro to discover the encoding of a database.
  581. */
  582. #define ENC(db) ((db)->aDb[0].pSchema->enc)
  583. /*
  584. ** Possible values for the sqlite.flags and or Db.flags fields.
  585. **
  586. ** On sqlite.flags, the SQLITE_InTrans value means that we have
  587. ** executed a BEGIN.  On Db.flags, SQLITE_InTrans means a statement
  588. ** transaction is active on that particular database file.
  589. */
  590. #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
  591. #define SQLITE_InTrans        0x00000008  /* True if in a transaction */
  592. #define SQLITE_InternChanges  0x00000010  /* Uncommitted Hash table changes */
  593. #define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
  594. #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
  595. #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
  596.                                           /*   DELETE, or UPDATE and return */
  597.                                           /*   the count using a callback. */
  598. #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
  599.                                           /*   result set is empty */
  600. #define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
  601. #define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
  602. #define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
  603. #define SQLITE_NoReadlock     0x00001000  /* Readlocks are omitted when 
  604.                                           ** accessing read-only databases */
  605. #define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
  606. #define SQLITE_ReadUncommitted 0x00004000 /* For shared-cache mode */
  607. #define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
  608. #define SQLITE_FullFSync      0x00010000  /* Use full fsync on the backend */
  609. #define SQLITE_LoadExtension  0x00020000  /* Enable load_extension */
  610. #define SQLITE_RecoveryMode   0x00040000  /* Ignore schema errors */
  611. #define SQLITE_SharedCache    0x00080000  /* Cache sharing is enabled */
  612. #define SQLITE_Vtab           0x00100000  /* There exists a virtual table */
  613. /*
  614. ** Possible values for the sqlite.magic field.
  615. ** The numbers are obtained at random and have no special meaning, other
  616. ** than being distinct from one another.
  617. */
  618. #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
  619. #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
  620. #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
  621. #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
  622. #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
  623. /*
  624. ** Each SQL function is defined by an instance of the following
  625. ** structure.  A pointer to this structure is stored in the sqlite.aFunc
  626. ** hash table.  When multiple functions have the same name, the hash table
  627. ** points to a linked list of these structures.
  628. */
  629. struct FuncDef {
  630.   i16 nArg;            /* Number of arguments.  -1 means unlimited */
  631.   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
  632.   u8 needCollSeq;      /* True if sqlite3GetFuncCollSeq() might be called */
  633.   u8 flags;            /* Some combination of SQLITE_FUNC_* */
  634.   void *pUserData;     /* User data parameter */
  635.   FuncDef *pNext;      /* Next function with same name */
  636.   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
  637.   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
  638.   void (*xFinalize)(sqlite3_context*);                /* Aggregate finializer */
  639.   char zName[1];       /* SQL name of the function.  MUST BE LAST */
  640. };
  641. /*
  642. ** Each SQLite module (virtual table definition) is defined by an
  643. ** instance of the following structure, stored in the sqlite3.aModule
  644. ** hash table.
  645. */
  646. struct Module {
  647.   const sqlite3_module *pModule;       /* Callback pointers */
  648.   const char *zName;                   /* Name passed to create_module() */
  649.   void *pAux;                          /* pAux passed to create_module() */
  650.   void (*xDestroy)(void *);            /* Module destructor function */
  651. };
  652. /*
  653. ** Possible values for FuncDef.flags
  654. */
  655. #define SQLITE_FUNC_LIKE   0x01  /* Candidate for the LIKE optimization */
  656. #define SQLITE_FUNC_CASE   0x02  /* Case-sensitive LIKE-type function */
  657. #define SQLITE_FUNC_EPHEM  0x04  /* Ephermeral.  Delete with VDBE */
  658. /*
  659. ** information about each column of an SQL table is held in an instance
  660. ** of this structure.
  661. */
  662. struct Column {
  663.   char *zName;     /* Name of this column */
  664.   Expr *pDflt;     /* Default value of this column */
  665.   char *zType;     /* Data type for this column */
  666.   char *zColl;     /* Collating sequence.  If NULL, use the default */
  667.   u8 notNull;      /* True if there is a NOT NULL constraint */
  668.   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
  669.   char affinity;   /* One of the SQLITE_AFF_... values */
  670. #ifndef SQLITE_OMIT_VIRTUALTABLE
  671.   u8 isHidden;     /* True if this column is 'hidden' */
  672. #endif
  673. };
  674. /*
  675. ** A "Collating Sequence" is defined by an instance of the following
  676. ** structure. Conceptually, a collating sequence consists of a name and
  677. ** a comparison routine that defines the order of that sequence.
  678. **
  679. ** There may two seperate implementations of the collation function, one
  680. ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
  681. ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
  682. ** native byte order. When a collation sequence is invoked, SQLite selects
  683. ** the version that will require the least expensive encoding
  684. ** translations, if any.
  685. **
  686. ** The CollSeq.pUser member variable is an extra parameter that passed in
  687. ** as the first argument to the UTF-8 comparison function, xCmp.
  688. ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
  689. ** xCmp16.
  690. **
  691. ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
  692. ** collating sequence is undefined.  Indices built on an undefined
  693. ** collating sequence may not be read or written.
  694. */
  695. struct CollSeq {
  696.   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
  697.   u8 enc;               /* Text encoding handled by xCmp() */
  698.   u8 type;              /* One of the SQLITE_COLL_... values below */
  699.   void *pUser;          /* First argument to xCmp() */
  700.   int (*xCmp)(void*,int, const void*, int, const void*);
  701.   void (*xDel)(void*);  /* Destructor for pUser */
  702. };
  703. /*
  704. ** Allowed values of CollSeq flags:
  705. */
  706. #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
  707. #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
  708. #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
  709. #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
  710. /*
  711. ** A sort order can be either ASC or DESC.
  712. */
  713. #define SQLITE_SO_ASC       0  /* Sort in ascending order */
  714. #define SQLITE_SO_DESC      1  /* Sort in ascending order */
  715. /*
  716. ** Column affinity types.
  717. **
  718. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  719. ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
  720. ** the speed a little by number the values consecutively.  
  721. **
  722. ** But rather than start with 0 or 1, we begin with 'a'.  That way,
  723. ** when multiple affinity types are concatenated into a string and
  724. ** used as the P4 operand, they will be more readable.
  725. **
  726. ** Note also that the numeric types are grouped together so that testing
  727. ** for a numeric type is a single comparison.
  728. */
  729. #define SQLITE_AFF_TEXT     'a'
  730. #define SQLITE_AFF_NONE     'b'
  731. #define SQLITE_AFF_NUMERIC  'c'
  732. #define SQLITE_AFF_INTEGER  'd'
  733. #define SQLITE_AFF_REAL     'e'
  734. #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
  735. /*
  736. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  737. ** affinity value. 
  738. */
  739. #define SQLITE_AFF_MASK     0x67
  740. /*
  741. ** Additional bit values that can be ORed with an affinity without
  742. ** changing the affinity.
  743. */
  744. #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
  745. #define SQLITE_NULLEQUAL    0x10  /* compare NULLs equal */
  746. #define SQLITE_STOREP2      0x80  /* Store result in reg[P2] rather than jump */
  747. /*
  748. ** Each SQL table is represented in memory by an instance of the
  749. ** following structure.
  750. **
  751. ** Table.zName is the name of the table.  The case of the original
  752. ** CREATE TABLE statement is stored, but case is not significant for
  753. ** comparisons.
  754. **
  755. ** Table.nCol is the number of columns in this table.  Table.aCol is a
  756. ** pointer to an array of Column structures, one for each column.
  757. **
  758. ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
  759. ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
  760. ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
  761. ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
  762. ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
  763. ** is generated for each row of the table.  Table.hasPrimKey is true if
  764. ** the table has any PRIMARY KEY, INTEGER or otherwise.
  765. **
  766. ** Table.tnum is the page number for the root BTree page of the table in the
  767. ** database file.  If Table.iDb is the index of the database table backend
  768. ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
  769. ** holds temporary tables and indices.  If Table.isEphem
  770. ** is true, then the table is stored in a file that is automatically deleted
  771. ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
  772. ** refers VDBE cursor number that holds the table open, not to the root
  773. ** page number.  Transient tables are used to hold the results of a
  774. ** sub-query that appears instead of a real table name in the FROM clause 
  775. ** of a SELECT statement.
  776. */
  777. struct Table {
  778.   char *zName;     /* Name of the table */
  779.   int nCol;        /* Number of columns in this table */
  780.   Column *aCol;    /* Information about each column */
  781.   int iPKey;       /* If not less then 0, use aCol[iPKey] as the primary key */
  782.   Index *pIndex;   /* List of SQL indexes on this table. */
  783.   int tnum;        /* Root BTree node for this table (see note above) */
  784.   Select *pSelect; /* NULL for tables.  Points to definition if a view. */
  785.   int nRef;          /* Number of pointers to this Table */
  786.   Trigger *pTrigger; /* List of SQL triggers on this table */
  787.   FKey *pFKey;       /* Linked list of all foreign keys in this table */
  788.   char *zColAff;     /* String defining the affinity of each column */
  789. #ifndef SQLITE_OMIT_CHECK
  790.   Expr *pCheck;      /* The AND of all CHECK constraints */
  791. #endif
  792. #ifndef SQLITE_OMIT_ALTERTABLE
  793.   int addColOffset;  /* Offset in CREATE TABLE statement to add a new column */
  794. #endif
  795.   u8 readOnly;     /* True if this table should not be written by the user */
  796.   u8 isEphem;      /* True if created using OP_OpenEphermeral */
  797.   u8 hasPrimKey;   /* True if there exists a primary key */
  798.   u8 keyConf;      /* What to do in case of uniqueness conflict on iPKey */
  799.   u8 autoInc;      /* True if the integer primary key is autoincrement */
  800. #ifndef SQLITE_OMIT_VIRTUALTABLE
  801.   u8 isVirtual;             /* True if this is a virtual table */
  802.   u8 isCommit;              /* True once the CREATE TABLE has been committed */
  803.   Module *pMod;             /* Pointer to the implementation of the module */
  804.   sqlite3_vtab *pVtab;      /* Pointer to the module instance */
  805.   int nModuleArg;           /* Number of arguments to the module */
  806.   char **azModuleArg;       /* Text of all module args. [0] is module name */
  807. #endif
  808.   Schema *pSchema;          /* Schema that contains this table */
  809. };
  810. /*
  811. ** Test to see whether or not a table is a virtual table.  This is
  812. ** done as a macro so that it will be optimized out when virtual
  813. ** table support is omitted from the build.
  814. */
  815. #ifndef SQLITE_OMIT_VIRTUALTABLE
  816. #  define IsVirtual(X)      ((X)->isVirtual)
  817. #  define IsHiddenColumn(X) ((X)->isHidden)
  818. #else
  819. #  define IsVirtual(X)      0
  820. #  define IsHiddenColumn(X) 0
  821. #endif
  822. /*
  823. ** Each foreign key constraint is an instance of the following structure.
  824. **
  825. ** A foreign key is associated with two tables.  The "from" table is
  826. ** the table that contains the REFERENCES clause that creates the foreign
  827. ** key.  The "to" table is the table that is named in the REFERENCES clause.
  828. ** Consider this example:
  829. **
  830. **     CREATE TABLE ex1(
  831. **       a INTEGER PRIMARY KEY,
  832. **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  833. **     );
  834. **
  835. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  836. **
  837. ** Each REFERENCES clause generates an instance of the following structure
  838. ** which is attached to the from-table.  The to-table need not exist when
  839. ** the from-table is created.  The existance of the to-table is not checked
  840. ** until an attempt is made to insert data into the from-table.
  841. **
  842. ** The sqlite.aFKey hash table stores pointers to this structure
  843. ** given the name of a to-table.  For each to-table, all foreign keys
  844. ** associated with that table are on a linked list using the FKey.pNextTo
  845. ** field.
  846. */
  847. struct FKey {
  848.   Table *pFrom;     /* The table that constains the REFERENCES clause */
  849.   FKey *pNextFrom;  /* Next foreign key in pFrom */
  850.   char *zTo;        /* Name of table that the key points to */
  851.   FKey *pNextTo;    /* Next foreign key that points to zTo */
  852.   int nCol;         /* Number of columns in this key */
  853.   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
  854.     int iFrom;         /* Index of column in pFrom */
  855.     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
  856.   } *aCol;          /* One entry for each of nCol column s */
  857.   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
  858.   u8 updateConf;    /* How to resolve conflicts that occur on UPDATE */
  859.   u8 deleteConf;    /* How to resolve conflicts that occur on DELETE */
  860.   u8 insertConf;    /* How to resolve conflicts that occur on INSERT */
  861. };
  862. /*
  863. ** SQLite supports many different ways to resolve a constraint
  864. ** error.  ROLLBACK processing means that a constraint violation
  865. ** causes the operation in process to fail and for the current transaction
  866. ** to be rolled back.  ABORT processing means the operation in process
  867. ** fails and any prior changes from that one operation are backed out,
  868. ** but the transaction is not rolled back.  FAIL processing means that
  869. ** the operation in progress stops and returns an error code.  But prior
  870. ** changes due to the same operation are not backed out and no rollback
  871. ** occurs.  IGNORE means that the particular row that caused the constraint
  872. ** error is not inserted or updated.  Processing continues and no error
  873. ** is returned.  REPLACE means that preexisting database rows that caused
  874. ** a UNIQUE constraint violation are removed so that the new insert or
  875. ** update can proceed.  Processing continues and no error is reported.
  876. **
  877. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  878. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  879. ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
  880. ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
  881. ** referenced table row is propagated into the row that holds the
  882. ** foreign key.
  883. ** 
  884. ** The following symbolic values are used to record which type
  885. ** of action to take.
  886. */
  887. #define OE_None     0   /* There is no constraint to check */
  888. #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
  889. #define OE_Abort    2   /* Back out changes but do no rollback transaction */
  890. #define OE_Fail     3   /* Stop the operation but leave all prior changes */
  891. #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
  892. #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
  893. #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  894. #define OE_SetNull  7   /* Set the foreign key value to NULL */
  895. #define OE_SetDflt  8   /* Set the foreign key value to its default */
  896. #define OE_Cascade  9   /* Cascade the changes */
  897. #define OE_Default  99  /* Do whatever the default action is */
  898. /*
  899. ** An instance of the following structure is passed as the first
  900. ** argument to sqlite3VdbeKeyCompare and is used to control the 
  901. ** comparison of the two index keys.
  902. **
  903. ** If the KeyInfo.incrKey value is true and the comparison would
  904. ** otherwise be equal, then return a result as if the second key
  905. ** were larger.
  906. */
  907. struct KeyInfo {
  908.   sqlite3 *db;        /* The database connection */
  909.   u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
  910.   u8 incrKey;         /* Increase 2nd key by epsilon before comparison */
  911.   u8 prefixIsEqual;   /* Treat a prefix as equal */
  912.   int nField;         /* Number of entries in aColl[] */
  913.   u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
  914.   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
  915. };
  916. /*
  917. ** Each SQL index is represented in memory by an
  918. ** instance of the following structure.
  919. **
  920. ** The columns of the table that are to be indexed are described
  921. ** by the aiColumn[] field of this structure.  For example, suppose
  922. ** we have the following table and index:
  923. **
  924. **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  925. **     CREATE INDEX Ex2 ON Ex1(c3,c1);
  926. **
  927. ** In the Table structure describing Ex1, nCol==3 because there are
  928. ** three columns in the table.  In the Index structure describing
  929. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  930. ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
  931. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  932. ** The second column to be indexed (c1) has an index of 0 in
  933. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  934. **
  935. ** The Index.onError field determines whether or not the indexed columns
  936. ** must be unique and what to do if they are not.  When Index.onError=OE_None,
  937. ** it means this is not a unique index.  Otherwise it is a unique index
  938. ** and the value of Index.onError indicate the which conflict resolution 
  939. ** algorithm to employ whenever an attempt is made to insert a non-unique
  940. ** element.
  941. */
  942. struct Index {
  943.   char *zName;     /* Name of this index */
  944.   int nColumn;     /* Number of columns in the table used by this index */
  945.   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
  946.   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
  947.   Table *pTable;   /* The SQL table being indexed */
  948.   int tnum;        /* Page containing root of this index in database file */
  949.   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  950.   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
  951.   char *zColAff;   /* String defining the affinity of each column */
  952.   Index *pNext;    /* The next index associated with the same table */
  953.   Schema *pSchema; /* Schema containing this index */
  954.   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
  955.   char **azColl;   /* Array of collation sequence names for index */
  956. };
  957. /*
  958. ** Each token coming out of the lexer is an instance of
  959. ** this structure.  Tokens are also used as part of an expression.
  960. **
  961. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  962. ** may contain random values.  Do not make any assuptions about Token.dyn
  963. ** and Token.n when Token.z==0.
  964. */
  965. struct Token {
  966.   const unsigned char *z; /* Text of the token.  Not NULL-terminated! */
  967.   unsigned dyn  : 1;      /* True for malloced memory, false for static */
  968.   unsigned n    : 31;     /* Number of characters in this token */
  969. };
  970. /*
  971. ** An instance of this structure contains information needed to generate
  972. ** code for a SELECT that contains aggregate functions.
  973. **
  974. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  975. ** pointer to this structure.  The Expr.iColumn field is the index in
  976. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  977. ** code for that node.
  978. **
  979. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  980. ** original Select structure that describes the SELECT statement.  These
  981. ** fields do not need to be freed when deallocating the AggInfo structure.
  982. */
  983. struct AggInfo {
  984.   u8 directMode;          /* Direct rendering mode means take data directly
  985.                           ** from source tables rather than from accumulators */
  986.   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
  987.                           ** than the source table */
  988.   int sortingIdx;         /* Cursor number of the sorting index */
  989.   ExprList *pGroupBy;     /* The group by clause */
  990.   int nSortingColumn;     /* Number of columns in the sorting index */
  991.   struct AggInfo_col {    /* For each column used in source tables */
  992.     Table *pTab;             /* Source table */
  993.     int iTable;              /* Cursor number of the source table */
  994.     int iColumn;             /* Column number within the source table */
  995.     int iSorterColumn;       /* Column number in the sorting index */
  996.     int iMem;                /* Memory location that acts as accumulator */
  997.     Expr *pExpr;             /* The original expression */
  998.   } *aCol;
  999.   int nColumn;            /* Number of used entries in aCol[] */
  1000.   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
  1001.   int nAccumulator;       /* Number of columns that show through to the output.
  1002.                           ** Additional columns are used only as parameters to
  1003.                           ** aggregate functions */
  1004.   struct AggInfo_func {   /* For each aggregate function */
  1005.     Expr *pExpr;             /* Expression encoding the function */
  1006.     FuncDef *pFunc;          /* The aggregate function implementation */
  1007.     int iMem;                /* Memory location that acts as accumulator */
  1008.     int iDistinct;           /* Ephermeral table used to enforce DISTINCT */
  1009.   } *aFunc;
  1010.   int nFunc;              /* Number of entries in aFunc[] */
  1011.   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
  1012. };
  1013. /*
  1014. ** Each node of an expression in the parse tree is an instance
  1015. ** of this structure.
  1016. **
  1017. ** Expr.op is the opcode.  The integer parser token codes are reused
  1018. ** as opcodes here.  For example, the parser defines TK_GE to be an integer
  1019. ** code representing the ">=" operator.  This same integer code is reused
  1020. ** to represent the greater-than-or-equal-to operator in the expression
  1021. ** tree.
  1022. **
  1023. ** Expr.pRight and Expr.pLeft are subexpressions.  Expr.pList is a list
  1024. ** of argument if the expression is a function.
  1025. **
  1026. ** Expr.token is the operator token for this node.  For some expressions
  1027. ** that have subexpressions, Expr.token can be the complete text that gave
  1028. ** rise to the Expr.  In the latter case, the token is marked as being
  1029. ** a compound token.
  1030. **
  1031. ** An expression of the form ID or ID.ID refers to a column in a table.
  1032. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  1033. ** the integer cursor number of a VDBE cursor pointing to that table and
  1034. ** Expr.iColumn is the column number for the specific column.  If the
  1035. ** expression is used as a result in an aggregate SELECT, then the
  1036. ** value is also stored in the Expr.iAgg column in the aggregate so that
  1037. ** it can be accessed after all aggregates are computed.
  1038. **
  1039. ** If the expression is a function, the Expr.iTable is an integer code
  1040. ** representing which function.  If the expression is an unbound variable
  1041. ** marker (a question mark character '?' in the original SQL) then the
  1042. ** Expr.iTable holds the index number for that variable.
  1043. **
  1044. ** If the expression is a subquery then Expr.iColumn holds an integer
  1045. ** register number containing the result of the subquery.  If the
  1046. ** subquery gives a constant result, then iTable is -1.  If the subquery
  1047. ** gives a different answer at different times during statement processing
  1048. ** then iTable is the address of a subroutine that computes the subquery.
  1049. **
  1050. ** The Expr.pSelect field points to a SELECT statement.  The SELECT might
  1051. ** be the right operand of an IN operator.  Or, if a scalar SELECT appears
  1052. ** in an expression the opcode is TK_SELECT and Expr.pSelect is the only
  1053. ** operand.
  1054. **
  1055. ** If the Expr is of type OP_Column, and the table it is selecting from
  1056. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  1057. ** corresponding table definition.
  1058. */
  1059. struct Expr {
  1060.   u8 op;                 /* Operation performed by this node */
  1061.   char affinity;         /* The affinity of the column or 0 if not a column */
  1062.   u16 flags;             /* Various flags.  See below */
  1063.   CollSeq *pColl;        /* The collation type of the column or 0 */
  1064.   Expr *pLeft, *pRight;  /* Left and right subnodes */
  1065.   ExprList *pList;       /* A list of expressions used as function arguments
  1066.                          ** or in "<expr> IN (<expr-list)" */
  1067.   Token token;           /* An operand token */
  1068.   Token span;            /* Complete text of the expression */
  1069.   int iTable, iColumn;   /* When op==TK_COLUMN, then this expr node means the
  1070.                          ** iColumn-th field of the iTable-th table. */
  1071.   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  1072.   int iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  1073.   int iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
  1074.   Select *pSelect;       /* When the expression is a sub-select.  Also the
  1075.                          ** right side of "<expr> IN (<select>)" */
  1076.   Table *pTab;           /* Table for OP_Column expressions. */
  1077. /*  Schema *pSchema; */
  1078. #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
  1079.   int nHeight;           /* Height of the tree headed by this node */
  1080. #endif
  1081. };
  1082. /*
  1083. ** The following are the meanings of bits in the Expr.flags field.
  1084. */
  1085. #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
  1086. #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
  1087. #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
  1088. #define EP_Error      0x0008  /* Expression contains one or more errors */
  1089. #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
  1090. #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
  1091. #define EP_Dequoted   0x0040  /* True if the string has been dequoted */
  1092. #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
  1093. #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
  1094. #define EP_AnyAff     0x0200  /* Can take a cached column of any affinity */
  1095. #define EP_FixedDest  0x0400  /* Result needed in a specific register */
  1096. /*
  1097. ** These macros can be used to test, set, or clear bits in the 
  1098. ** Expr.flags field.
  1099. */
  1100. #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
  1101. #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
  1102. #define ExprSetProperty(E,P)     (E)->flags|=(P)
  1103. #define ExprClearProperty(E,P)   (E)->flags&=~(P)
  1104. /*
  1105. ** A list of expressions.  Each expression may optionally have a
  1106. ** name.  An expr/name combination can be used in several ways, such
  1107. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  1108. ** list of "ID = expr" items in an UPDATE.  A list of expressions can
  1109. ** also be used as the argument to a function, in which case the a.zName
  1110. ** field is not used.
  1111. */
  1112. struct ExprList {
  1113.   int nExpr;             /* Number of expressions on the list */
  1114.   int nAlloc;            /* Number of entries allocated below */
  1115.   int iECursor;          /* VDBE Cursor associated with this ExprList */
  1116.   struct ExprList_item {
  1117.     Expr *pExpr;           /* The list of expressions */
  1118.     char *zName;           /* Token associated with this expression */
  1119.     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
  1120.     u8 isAgg;              /* True if this is an aggregate like count(*) */
  1121.     u8 done;               /* A flag to indicate when processing is finished */
  1122.   } *a;                  /* One entry for each expression */
  1123. };
  1124. /*
  1125. ** An instance of this structure can hold a simple list of identifiers,
  1126. ** such as the list "a,b,c" in the following statements:
  1127. **
  1128. **      INSERT INTO t(a,b,c) VALUES ...;
  1129. **      CREATE INDEX idx ON t(a,b,c);
  1130. **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  1131. **
  1132. ** The IdList.a.idx field is used when the IdList represents the list of
  1133. ** column names after a table name in an INSERT statement.  In the statement
  1134. **
  1135. **     INSERT INTO t(a,b,c) ...
  1136. **
  1137. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  1138. */
  1139. struct IdList {
  1140.   struct IdList_item {
  1141.     char *zName;      /* Name of the identifier */
  1142.     int idx;          /* Index in some Table.aCol[] of a column named zName */
  1143.   } *a;
  1144.   int nId;         /* Number of identifiers on the list */
  1145.   int nAlloc;      /* Number of entries allocated for a[] below */
  1146. };
  1147. /*
  1148. ** The bitmask datatype defined below is used for various optimizations.
  1149. **
  1150. ** Changing this from a 64-bit to a 32-bit type limits the number of
  1151. ** tables in a join to 32 instead of 64.  But it also reduces the size
  1152. ** of the library by 738 bytes on ix86.
  1153. */
  1154. typedef u64 Bitmask;
  1155. /*
  1156. ** The following structure describes the FROM clause of a SELECT statement.
  1157. ** Each table or subquery in the FROM clause is a separate element of
  1158. ** the SrcList.a[] array.
  1159. **
  1160. ** With the addition of multiple database support, the following structure
  1161. ** can also be used to describe a particular table such as the table that
  1162. ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
  1163. ** such a table must be a simple name: ID.  But in SQLite, the table can
  1164. ** now be identified by a database name, a dot, then the table name: ID.ID.
  1165. **
  1166. ** The jointype starts out showing the join type between the current table
  1167. ** and the next table on the list.  The parser builds the list this way.
  1168. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  1169. ** jointype expresses the join between the table and the previous table.
  1170. */
  1171. struct SrcList {
  1172.   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
  1173.   i16 nAlloc;      /* Number of entries allocated in a[] below */
  1174.   struct SrcList_item {
  1175.     char *zDatabase;  /* Name of database holding this table */
  1176.     char *zName;      /* Name of the table */
  1177.     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
  1178.     Table *pTab;      /* An SQL table corresponding to zName */
  1179.     Select *pSelect;  /* A SELECT statement used in place of a table name */
  1180.     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
  1181.     u8 jointype;      /* Type of join between this able and the previous */
  1182.     int iCursor;      /* The VDBE cursor number used to access this table */
  1183.     Expr *pOn;        /* The ON clause of a join */
  1184.     IdList *pUsing;   /* The USING clause of a join */
  1185.     Bitmask colUsed;  /* Bit N (1<<N) set if column N or pTab is used */
  1186.   } a[1];             /* One entry for each identifier on the list */
  1187. };
  1188. /*
  1189. ** Permitted values of the SrcList.a.jointype field
  1190. */
  1191. #define JT_INNER     0x0001    /* Any kind of inner or cross join */
  1192. #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
  1193. #define JT_NATURAL   0x0004    /* True for a "natural" join */
  1194. #define JT_LEFT      0x0008    /* Left outer join */
  1195. #define JT_RIGHT     0x0010    /* Right outer join */
  1196. #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
  1197. #define JT_ERROR     0x0040    /* unknown or unsupported join type */
  1198. /*
  1199. ** For each nested loop in a WHERE clause implementation, the WhereInfo
  1200. ** structure contains a single instance of this structure.  This structure
  1201. ** is intended to be private the the where.c module and should not be
  1202. ** access or modified by other modules.
  1203. **
  1204. ** The pIdxInfo and pBestIdx fields are used to help pick the best
  1205. ** index on a virtual table.  The pIdxInfo pointer contains indexing
  1206. ** information for the i-th table in the FROM clause before reordering.
  1207. ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
  1208. ** The pBestIdx pointer is a copy of pIdxInfo for the i-th table after
  1209. ** FROM clause ordering.  This is a little confusing so I will repeat
  1210. ** it in different words.  WhereInfo.a[i].pIdxInfo is index information 
  1211. ** for WhereInfo.pTabList.a[i].  WhereInfo.a[i].pBestInfo is the
  1212. ** index information for the i-th loop of the join.  pBestInfo is always
  1213. ** either NULL or a copy of some pIdxInfo.  So for cleanup it is 
  1214. ** sufficient to free all of the pIdxInfo pointers.
  1215. ** 
  1216. */
  1217. struct WhereLevel {
  1218.   int iFrom;            /* Which entry in the FROM clause */
  1219.   int flags;            /* Flags associated with this level */
  1220.   int iMem;             /* First memory cell used by this level */
  1221.   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
  1222.   Index *pIdx;          /* Index used.  NULL if no index */
  1223.   int iTabCur;          /* The VDBE cursor used to access the table */
  1224.   int iIdxCur;          /* The VDBE cursor used to acesss pIdx */
  1225.   int brk;              /* Jump here to break out of the loop */
  1226.   int nxt;              /* Jump here to start the next IN combination */
  1227.   int cont;             /* Jump here to continue with the next loop cycle */
  1228.   int top;              /* First instruction of interior of the loop */
  1229.   int op, p1, p2;       /* Opcode used to terminate the loop */
  1230.   int nEq;              /* Number of == or IN constraints on this loop */
  1231.   int nIn;              /* Number of IN operators constraining this loop */
  1232.   struct InLoop {
  1233.     int iCur;              /* The VDBE cursor used by this IN operator */
  1234.     int topAddr;           /* Top of the IN loop */
  1235.   } *aInLoop;           /* Information about each nested IN operator */
  1236.   sqlite3_index_info *pBestIdx;  /* Index information for this level */
  1237.   /* The following field is really not part of the current level.  But
  1238.   ** we need a place to cache index information for each table in the
  1239.   ** FROM clause and the WhereLevel structure is a convenient place.
  1240.   */
  1241.   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
  1242. };
  1243. /*
  1244. ** Flags appropriate for the wflags parameter of sqlite3WhereBegin().
  1245. */
  1246. #define WHERE_ORDERBY_NORMAL     0   /* No-op */
  1247. #define WHERE_ORDERBY_MIN        1   /* ORDER BY processing for min() func */
  1248. #define WHERE_ORDERBY_MAX        2   /* ORDER BY processing for max() func */
  1249. #define WHERE_ONEPASS_DESIRED    4   /* Want to do one-pass UPDATE/DELETE */
  1250. /*
  1251. ** The WHERE clause processing routine has two halves.  The
  1252. ** first part does the start of the WHERE loop and the second
  1253. ** half does the tail of the WHERE loop.  An instance of
  1254. ** this structure is returned by the first half and passed
  1255. ** into the second half to give some continuity.
  1256. */
  1257. struct WhereInfo {
  1258.   Parse *pParse;       /* Parsing and code generating context */
  1259.   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
  1260.   SrcList *pTabList;   /* List of tables in the join */
  1261.   int iTop;            /* The very beginning of the WHERE loop */
  1262.   int iContinue;       /* Jump here to continue with next record */
  1263.   int iBreak;          /* Jump here to break out of the loop */
  1264.   int nLevel;          /* Number of nested loop */
  1265.   sqlite3_index_info **apInfo;  /* Array of pointers to index info structures */
  1266.   WhereLevel a[1];     /* Information about each nest loop in the WHERE */
  1267. };
  1268. /*
  1269. ** A NameContext defines a context in which to resolve table and column
  1270. ** names.  The context consists of a list of tables (the pSrcList) field and
  1271. ** a list of named expression (pEList).  The named expression list may
  1272. ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
  1273. ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
  1274. ** pEList corresponds to the result set of a SELECT and is NULL for
  1275. ** other statements.
  1276. **
  1277. ** NameContexts can be nested.  When resolving names, the inner-most 
  1278. ** context is searched first.  If no match is found, the next outer
  1279. ** context is checked.  If there is still no match, the next context
  1280. ** is checked.  This process continues until either a match is found
  1281. ** or all contexts are check.  When a match is found, the nRef member of
  1282. ** the context containing the match is incremented. 
  1283. **
  1284. ** Each subquery gets a new NameContext.  The pNext field points to the
  1285. ** NameContext in the parent query.  Thus the process of scanning the
  1286. ** NameContext list corresponds to searching through successively outer
  1287. ** subqueries looking for a match.
  1288. */
  1289. struct NameContext {
  1290.   Parse *pParse;       /* The parser */
  1291.   SrcList *pSrcList;   /* One or more tables used to resolve names */
  1292.   ExprList *pEList;    /* Optional list of named expressions */
  1293.   int nRef;            /* Number of names resolved by this context */
  1294.   int nErr;            /* Number of errors encountered while resolving names */
  1295.   u8 allowAgg;         /* Aggregate functions allowed here */
  1296.   u8 hasAgg;           /* True if aggregates are seen */
  1297.   u8 isCheck;          /* True if resolving names in a CHECK constraint */
  1298.   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
  1299.   AggInfo *pAggInfo;   /* Information about aggregates at this level */
  1300.   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
  1301. };
  1302. /*
  1303. ** An instance of the following structure contains all information
  1304. ** needed to generate code for a single SELECT statement.
  1305. **
  1306. ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
  1307. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  1308. ** limit and nOffset to the value of the offset (or 0 if there is not
  1309. ** offset).  But later on, nLimit and nOffset become the memory locations
  1310. ** in the VDBE that record the limit and offset counters.
  1311. **
  1312. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  1313. ** These addresses must be stored so that we can go back and fill in
  1314. ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
  1315. ** the number of columns in P2 can be computed at the same time
  1316. ** as the OP_OpenEphm instruction is coded because not
  1317. ** enough information about the compound query is known at that point.
  1318. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  1319. ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
  1320. ** sequences for the ORDER BY clause.
  1321. */
  1322. struct Select {
  1323.   ExprList *pEList;      /* The fields of the result */
  1324.   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  1325.   u8 isDistinct;         /* True if the DISTINCT keyword is present */
  1326.   u8 isResolved;         /* True once sqlite3SelectResolve() has run. */
  1327.   u8 isAgg;              /* True if this is an aggregate query */
  1328.   u8 usesEphm;           /* True if uses an OpenEphemeral opcode */
  1329.   u8 disallowOrderBy;    /* Do not allow an ORDER BY to be attached if TRUE */
  1330.   char affinity;         /* MakeRecord with this affinity for SRT_Set */
  1331.   SrcList *pSrc;         /* The FROM clause */
  1332.   Expr *pWhere;          /* The WHERE clause */
  1333.   ExprList *pGroupBy;    /* The GROUP BY clause */
  1334.   Expr *pHaving;         /* The HAVING clause */
  1335.   ExprList *pOrderBy;    /* The ORDER BY clause */
  1336.   Select *pPrior;        /* Prior select in a compound select statement */
  1337.   Select *pNext;         /* Next select to the left in a compound */
  1338.   Select *pRightmost;    /* Right-most select in a compound select statement */
  1339.   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
  1340.   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
  1341.   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
  1342.   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
  1343. };
  1344. /*
  1345. ** The results of a select can be distributed in several ways.
  1346. */
  1347. #define SRT_Union        1  /* Store result as keys in an index */
  1348. #define SRT_Except       2  /* Remove result from a UNION index */
  1349. #define SRT_Exists       3  /* Store 1 if the result is not empty */
  1350. #define SRT_Discard      4  /* Do not save the results anywhere */
  1351. /* The ORDER BY clause is ignored for all of the above */
  1352. #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
  1353. #define SRT_Callback     5  /* Invoke a callback with each row of result */
  1354. #define SRT_Mem          6  /* Store result in a memory cell */
  1355. #define SRT_Set          7  /* Store non-null results as keys in an index */
  1356. #define SRT_Table        8  /* Store result as data with an automatic rowid */
  1357. #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
  1358. #define SRT_Subroutine  10  /* Call a subroutine to handle results */
  1359. /*
  1360. ** A structure used to customize the behaviour of sqlite3Select(). See
  1361. ** comments above sqlite3Select() for details.
  1362. */
  1363. typedef struct SelectDest SelectDest;
  1364. struct SelectDest {
  1365.   u8 eDest;         /* How to dispose of the results */
  1366.   u8 affinity;      /* Affinity used when eDest==SRT_Set */
  1367.   int iParm;        /* A parameter used by the eDest disposal method */
  1368.   int iMem;         /* Base register where results are written */
  1369.   int nMem;         /* Number of registers allocated */
  1370. };
  1371. /*
  1372. ** An SQL parser context.  A copy of this structure is passed through
  1373. ** the parser and down into all the parser action routine in order to
  1374. ** carry around information that is global to the entire parse.
  1375. **
  1376. ** The structure is divided into two parts.  When the parser and code
  1377. ** generate call themselves recursively, the first part of the structure
  1378. ** is constant but the second part is reset at the beginning and end of
  1379. ** each recursion.
  1380. **
  1381. ** The nTableLock and aTableLock variables are only used if the shared-cache 
  1382. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  1383. ** used to store the set of table-locks required by the statement being
  1384. ** compiled. Function sqlite3TableLock() is used to add entries to the
  1385. ** list.
  1386. */
  1387. struct Parse {
  1388.   sqlite3 *db;         /* The main database structure */
  1389.   int rc;              /* Return code from execution */
  1390.   char *zErrMsg;       /* An error message */
  1391.   Vdbe *pVdbe;         /* An engine for executing database bytecode */
  1392.   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
  1393.   u8 nameClash;        /* A permanent table name clashes with temp table name */
  1394.   u8 checkSchema;      /* Causes schema cookie check after an error */
  1395.   u8 nested;           /* Number of nested calls to the parser/code generator */
  1396.   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
  1397.   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
  1398.   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
  1399.   int aTempReg[8];     /* Holding area for temporary registers */
  1400.   int nRangeReg;       /* Size of the temporary register block */
  1401.   int iRangeReg;       /* First register in temporary register block */
  1402.   int nErr;            /* Number of errors seen */
  1403.   int nTab;            /* Number of previously allocated VDBE cursors */
  1404.   int nMem;            /* Number of memory cells used so far */
  1405.   int nSet;            /* Number of sets used so far */
  1406.   int ckBase;          /* Base register of data during check constraints */
  1407.   int disableColCache; /* True to disable adding to column cache */
  1408.   int nColCache;       /* Number of entries in the column cache */
  1409.   int iColCache;       /* Next entry of the cache to replace */
  1410.   struct yColCache {
  1411.     int iTable;           /* Table cursor number */
  1412.     int iColumn;          /* Table column number */
  1413.     char affChange;       /* True if this register has had an affinity change */
  1414.     int iReg;             /* Register holding value of this column */
  1415.   } aColCache[10];     /* One for each valid column cache entry */
  1416.   u32 writeMask;       /* Start a write transaction on these databases */
  1417.   u32 cookieMask;      /* Bitmask of schema verified databases */
  1418.   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
  1419.   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
  1420. #ifndef SQLITE_OMIT_SHARED_CACHE
  1421.   int nTableLock;        /* Number of locks in aTableLock */
  1422.   TableLock *aTableLock; /* Required table locks for shared-cache mode */
  1423. #endif
  1424.   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
  1425.   int regRoot;         /* Register holding root page number for new objects */
  1426.   /* Above is constant between recursions.  Below is reset before and after
  1427.   ** each recursion */
  1428.   int nVar;            /* Number of '?' variables seen in the SQL so far */
  1429.   int nVarExpr;        /* Number of used slots in apVarExpr[] */
  1430.   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
  1431.   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
  1432.   u8 explain;          /* True if the EXPLAIN flag is found on the query */
  1433.   Token sErrToken;     /* The token at which the error occurred */
  1434.   Token sNameToken;    /* Token with unqualified schema object name */
  1435.   Token sLastToken;    /* The last token parsed */
  1436.   const char *zSql;    /* All SQL text */
  1437.   const char *zTail;   /* All SQL text past the last semicolon parsed */
  1438.   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
  1439.   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
  1440.   TriggerStack *trigStack;  /* Trigger actions being coded */
  1441.   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  1442. #ifndef SQLITE_OMIT_VIRTUALTABLE
  1443.   Token sArg;                /* Complete text of a module argument */
  1444.   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
  1445.   Table *pVirtualLock;       /* Require virtual table lock on this table */
  1446. #endif
  1447. #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
  1448.   int nHeight;            /* Expression tree height of current sub-select */
  1449. #endif
  1450. };
  1451. #ifdef SQLITE_OMIT_VIRTUALTABLE
  1452.   #define IN_DECLARE_VTAB 0
  1453. #else
  1454.   #define IN_DECLARE_VTAB (pParse->declareVtab)
  1455. #endif
  1456. /*
  1457. ** An instance of the following structure can be declared on a stack and used
  1458. ** to save the Parse.zAuthContext value so that it can be restored later.
  1459. */
  1460. struct AuthContext {
  1461.   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
  1462.   Parse *pParse;              /* The Parse structure */
  1463. };
  1464. /*
  1465. ** Bitfield flags for P2 value in OP_Insert and OP_Delete
  1466. */
  1467. #define OPFLAG_NCHANGE   1    /* Set to update db->nChange */
  1468. #define OPFLAG_LASTROWID 2    /* Set to update db->lastRowid */
  1469. #define OPFLAG_ISUPDATE  4    /* This OP_Insert is an sql UPDATE */
  1470. #define OPFLAG_APPEND    8    /* This is likely to be an append */
  1471. /*
  1472.  * Each trigger present in the database schema is stored as an instance of
  1473.  * struct Trigger. 
  1474.  *
  1475.  * Pointers to instances of struct Trigger are stored in two ways.
  1476.  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
  1477.  *    database). This allows Trigger structures to be retrieved by name.
  1478.  * 2. All triggers associated with a single table form a linked list, using the
  1479.  *    pNext member of struct Trigger. A pointer to the first element of the
  1480.  *    linked list is stored as the "pTrigger" member of the associated
  1481.  *    struct Table.
  1482.  *
  1483.  * The "step_list" member points to the first element of a linked list
  1484.  * containing the SQL statements specified as the trigger program.
  1485.  */
  1486. struct Trigger {
  1487.   char *name;             /* The name of the trigger                        */
  1488.   char *table;            /* The table or view to which the trigger applies */
  1489.   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
  1490.   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  1491.   Expr *pWhen;            /* The WHEN clause of the expresion (may be NULL) */
  1492.   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
  1493.                              the <column-list> is stored here */
  1494.   Token nameToken;        /* Token containing zName. Use during parsing only */
  1495.   Schema *pSchema;        /* Schema containing the trigger */
  1496.   Schema *pTabSchema;     /* Schema containing the table */
  1497.   TriggerStep *step_list; /* Link list of trigger program steps             */
  1498.   Trigger *pNext;         /* Next trigger associated with the table */
  1499. };
  1500. /*
  1501. ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
  1502. ** determine which. 
  1503. **
  1504. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  1505. ** In that cases, the constants below can be ORed together.
  1506. */
  1507. #define TRIGGER_BEFORE  1
  1508. #define TRIGGER_AFTER   2
  1509. /*
  1510.  * An instance of struct TriggerStep is used to store a single SQL statement
  1511.  * that is a part of a trigger-program. 
  1512.  *
  1513.  * Instances of struct TriggerStep are stored in a singly linked list (linked
  1514.  * using the "pNext" member) referenced by the "step_list" member of the 
  1515.  * associated struct Trigger instance. The first element of the linked list is
  1516.  * the first step of the trigger-program.
  1517.  * 
  1518.  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  1519.  * "SELECT" statement. The meanings of the other members is determined by the 
  1520.  * value of "op" as follows:
  1521.  *
  1522.  * (op == TK_INSERT)
  1523.  * orconf    -> stores the ON CONFLICT algorithm
  1524.  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
  1525.  *              this stores a pointer to the SELECT statement. Otherwise NULL.
  1526.  * target    -> A token holding the name of the table to insert into.
  1527.  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  1528.  *              this stores values to be inserted. Otherwise NULL.
  1529.  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
  1530.  *              statement, then this stores the column-names to be
  1531.  *              inserted into.
  1532.  *
  1533.  * (op == TK_DELETE)
  1534.  * target    -> A token holding the name of the table to delete from.
  1535.  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
  1536.  *              Otherwise NULL.
  1537.  * 
  1538.  * (op == TK_UPDATE)
  1539.  * target    -> A token holding the name of the table to update rows of.
  1540.  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
  1541.  *              Otherwise NULL.
  1542.  * pExprList -> A list of the columns to update and the expressions to update
  1543.  *              them to. See sqlite3Update() documentation of "pChanges"
  1544.  *              argument.
  1545.  * 
  1546.  */
  1547. struct TriggerStep {
  1548.   int op;              /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  1549.   int orconf;          /* OE_Rollback etc. */
  1550.   Trigger *pTrig;      /* The trigger that this step is a part of */
  1551.   Select *pSelect;     /* Valid for SELECT and sometimes 
  1552.                           INSERT steps (when pExprList == 0) */
  1553.   Token target;        /* Valid for DELETE, UPDATE, INSERT steps */
  1554.   Expr *pWhere;        /* Valid for DELETE, UPDATE steps */
  1555.   ExprList *pExprList; /* Valid for UPDATE statements and sometimes 
  1556.                            INSERT steps (when pSelect == 0)         */
  1557.   IdList *pIdList;     /* Valid for INSERT statements only */
  1558.   TriggerStep *pNext;  /* Next in the link-list */
  1559.   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
  1560. };
  1561. /*
  1562.  * An instance of struct TriggerStack stores information required during code
  1563.  * generation of a single trigger program. While the trigger program is being
  1564.  * coded, its associated TriggerStack instance is pointed to by the
  1565.  * "pTriggerStack" member of the Parse structure.
  1566.  *
  1567.  * The pTab member points to the table that triggers are being coded on. The 
  1568.  * newIdx member contains the index of the vdbe cursor that points at the temp
  1569.  * table that stores the new.* references. If new.* references are not valid
  1570.  * for the trigger being coded (for example an ON DELETE trigger), then newIdx
  1571.  * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
  1572.  *
  1573.  * The ON CONFLICT policy to be used for the trigger program steps is stored 
  1574.  * as the orconf member. If this is OE_Default, then the ON CONFLICT clause 
  1575.  * specified for individual triggers steps is used.
  1576.  *
  1577.  * struct TriggerStack has a "pNext" member, to allow linked lists to be
  1578.  * constructed. When coding nested triggers (triggers fired by other triggers)
  1579.  * each nested trigger stores its parent trigger's TriggerStack as the "pNext" 
  1580.  * pointer. Once the nested trigger has been coded, the pNext value is restored
  1581.  * to the pTriggerStack member of the Parse stucture and coding of the parent
  1582.  * trigger continues.
  1583.  *
  1584.  * Before a nested trigger is coded, the linked list pointed to by the 
  1585.  * pTriggerStack is scanned to ensure that the trigger is not about to be coded
  1586.  * recursively. If this condition is detected, the nested trigger is not coded.
  1587.  */
  1588. struct TriggerStack {
  1589.   Table *pTab;         /* Table that triggers are currently being coded on */
  1590.   int newIdx;          /* Index of vdbe cursor to "new" temp table */
  1591.   int oldIdx;          /* Index of vdbe cursor to "old" temp table */
  1592.   u32 newColMask;
  1593.   u32 oldColMask;
  1594.   int orconf;          /* Current orconf policy */
  1595.   int ignoreJump;      /* where to jump to for a RAISE(IGNORE) */
  1596.   Trigger *pTrigger;   /* The trigger currently being coded */
  1597.   TriggerStack *pNext; /* Next trigger down on the trigger stack */
  1598. };
  1599. /*
  1600. ** The following structure contains information used by the sqliteFix...
  1601. ** routines as they walk the parse tree to make database references
  1602. ** explicit.  
  1603. */
  1604. typedef struct DbFixer DbFixer;
  1605. struct DbFixer {
  1606.   Parse *pParse;      /* The parsing context.  Error messages written here */
  1607.   const char *zDb;    /* Make sure all objects are contained in this database */
  1608.   const char *zType;  /* Type of the container - used for error messages */
  1609.   const Token *pName; /* Name of the container - used for error messages */
  1610. };
  1611. /*
  1612. ** An objected used to accumulate the text of a string where we
  1613. ** do not necessarily know how big the string will be in the end.
  1614. */
  1615. struct StrAccum {
  1616.   char *zBase;     /* A base allocation.  Not from malloc. */
  1617.   char *zText;     /* The string collected so far */
  1618.   int  nChar;      /* Length of the string so far */
  1619.   int  nAlloc;     /* Amount of space allocated in zText */
  1620.   int  mxAlloc;        /* Maximum allowed string length */
  1621.   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
  1622.   u8   useMalloc;      /* True if zText is enlargable using realloc */
  1623.   u8   tooBig;         /* Becomes true if string size exceeds limits */
  1624. };
  1625. /*
  1626. ** A pointer to this structure is used to communicate information
  1627. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  1628. */
  1629. typedef struct {
  1630.   sqlite3 *db;        /* The database being initialized */
  1631.   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
  1632.   char **pzErrMsg;    /* Error message stored here */
  1633.   int rc;             /* Result code stored here */
  1634. } InitData;
  1635. /*
  1636. ** Assuming zIn points to the first byte of a UTF-8 character,
  1637. ** advance zIn to point to the first byte of the next UTF-8 character.
  1638. */
  1639. #define SQLITE_SKIP_UTF8(zIn) {                        
  1640.   if( (*(zIn++))>=0xc0 ){                              
  1641.     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             
  1642.   }                                                    
  1643. }
  1644. /*
  1645. ** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production
  1646. ** builds) or a function call (for debugging).  If it is a function call,
  1647. ** it allows the operator to set a breakpoint at the spot where database
  1648. ** corruption is first detected.
  1649. */
  1650. #ifdef SQLITE_DEBUG
  1651.   int sqlite3Corrupt(void);
  1652. # define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
  1653. # define DEBUGONLY(X)        X
  1654. #else
  1655. # define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
  1656. # define DEBUGONLY(X)
  1657. #endif
  1658. /*
  1659. ** Internal function prototypes
  1660. */
  1661. int sqlite3StrICmp(const char *, const char *);
  1662. int sqlite3StrNICmp(const char *, const char *, int);
  1663. int sqlite3IsNumber(const char*, int*, u8);
  1664. void *sqlite3MallocZero(unsigned);
  1665. void *sqlite3DbMallocZero(sqlite3*, unsigned);
  1666. void *sqlite3DbMallocRaw(sqlite3*, unsigned);
  1667. char *sqlite3StrDup(const char*);
  1668. char *sqlite3StrNDup(const char*, int);
  1669. char *sqlite3DbStrDup(sqlite3*,const char*);
  1670. char *sqlite3DbStrNDup(sqlite3*,const char*, int);
  1671. void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
  1672. void *sqlite3DbRealloc(sqlite3 *, void *, int);
  1673. int sqlite3MallocSize(void *);
  1674. char *sqlite3MPrintf(sqlite3*,const char*, ...);
  1675. char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  1676. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  1677.   void sqlite3DebugPrintf(const char*, ...);
  1678. #endif
  1679. #if defined(SQLITE_TEST)
  1680.   void *sqlite3TextToPtr(const char*);
  1681. #endif
  1682. void sqlite3SetString(char **, ...);
  1683. void sqlite3ErrorMsg(Parse*, const char*, ...);
  1684. void sqlite3ErrorClear(Parse*);
  1685. void sqlite3Dequote(char*);
  1686. void sqlite3DequoteExpr(sqlite3*, Expr*);
  1687. int sqlite3KeywordCode(const unsigned char*, int);
  1688. int sqlite3RunParser(Parse*, const char*, char **);
  1689. void sqlite3FinishCoding(Parse*);
  1690. int sqlite3GetTempReg(Parse*);
  1691. void sqlite3ReleaseTempReg(Parse*,int);
  1692. int sqlite3GetTempRange(Parse*,int);
  1693. void sqlite3ReleaseTempRange(Parse*,int,int);
  1694. Expr *sqlite3Expr(sqlite3*, int, Expr*, Expr*, const Token*);
  1695. Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
  1696. Expr *sqlite3RegisterExpr(Parse*,Token*);
  1697. Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  1698. void sqlite3ExprSpan(Expr*,Token*,Token*);
  1699. Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  1700. void sqlite3ExprAssignVarNumber(Parse*, Expr*);
  1701. void sqlite3ExprDelete(Expr*);
  1702. ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*,Token*);
  1703. void sqlite3ExprListDelete(ExprList*);
  1704. int sqlite3Init(sqlite3*, char**);
  1705. int sqlite3InitCallback(void*, int, char**, char**);
  1706. void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  1707. void sqlite3ResetInternalSchema(sqlite3*, int);
  1708. void sqlite3BeginParse(Parse*,int);
  1709. void sqlite3CommitInternalChanges(sqlite3*);
  1710. Table *sqlite3ResultSetOfSelect(Parse*,char*,Select*);
  1711. void sqlite3OpenMasterTable(Parse *, int);
  1712. void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  1713. void sqlite3AddColumn(Parse*,Token*);
  1714. void sqlite3AddNotNull(Parse*, int);
  1715. void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  1716. void sqlite3AddCheckConstraint(Parse*, Expr*);
  1717. void sqlite3AddColumnType(Parse*,Token*);
  1718. void sqlite3AddDefaultValue(Parse*,Expr*);
  1719. void sqlite3AddCollateType(Parse*, Token*);
  1720. void sqlite3EndTable(Parse*,Token*,Token*,Select*);
  1721. Bitvec *sqlite3BitvecCreate(u32);
  1722. int sqlite3BitvecTest(Bitvec*, u32);
  1723. int sqlite3BitvecSet(Bitvec*, u32);
  1724. void sqlite3BitvecClear(Bitvec*, u32);
  1725. void sqlite3BitvecDestroy(Bitvec*);
  1726. int sqlite3BitvecBuiltinTest(int,int*);
  1727. void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
  1728. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  1729.   int sqlite3ViewGetColumnNames(Parse*,Table*);
  1730. #else
  1731. # define sqlite3ViewGetColumnNames(A,B) 0
  1732. #endif
  1733. void sqlite3DropTable(Parse*, SrcList*, int, int);
  1734. void sqlite3DeleteTable(Table*);
  1735. void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
  1736. void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
  1737. IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  1738. int sqlite3IdListIndex(IdList*,const char*);
  1739. SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  1740. SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*, Token*,
  1741.                                       Select*, Expr*, IdList*);
  1742. void sqlite3SrcListShiftJoinType(SrcList*);
  1743. void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  1744. void sqlite3IdListDelete(IdList*);
  1745. void sqlite3SrcListDelete(SrcList*);
  1746. void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  1747.                         Token*, int, int);
  1748. void sqlite3DropIndex(Parse*, SrcList*, int);
  1749. int sqlite3Select(Parse*, Select*, SelectDest*, Select*, int, int*, char *aff);
  1750. Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  1751.                          Expr*,ExprList*,int,Expr*,Expr*);
  1752. void sqlite3SelectDelete(Select*);
  1753. Table *sqlite3SrcListLookup(Parse*, SrcList*);
  1754. int sqlite3IsReadOnly(Parse*, Table*, int);
  1755. void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  1756. void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
  1757. void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
  1758. WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u8);
  1759. void sqlite3WhereEnd(WhereInfo*);
  1760. int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, int);
  1761. void sqlite3ExprCodeMove(Parse*, int, int);
  1762. void sqlite3ExprClearColumnCache(Parse*, int);
  1763. void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  1764. int sqlite3ExprWritableRegister(Parse*,int,int);
  1765. void sqlite3ExprHardCopy(Parse*,int,int);
  1766. int sqlite3ExprCode(Parse*, Expr*, int);
  1767. int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  1768. int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  1769. int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  1770. void sqlite3ExprCodeConstants(Parse*, Expr*);
  1771. int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
  1772. void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  1773. void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  1774. Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  1775. Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
  1776. Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  1777. void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  1778. void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  1779. void sqlite3Vacuum(Parse*);
  1780. int sqlite3RunVacuum(char**, sqlite3*);
  1781. char *sqlite3NameFromToken(sqlite3*, Token*);
  1782. int sqlite3ExprCompare(Expr*, Expr*);
  1783. int sqlite3ExprResolveNames(NameContext *, Expr *);
  1784. void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  1785. void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  1786. Vdbe *sqlite3GetVdbe(Parse*);
  1787. Expr *sqlite3CreateIdExpr(Parse *, const char*);
  1788. void sqlite3PrngSaveState(void);
  1789. void sqlite3PrngRestoreState(void);
  1790. void sqlite3PrngResetState(void);
  1791. void sqlite3RollbackAll(sqlite3*);
  1792. void sqlite3CodeVerifySchema(Parse*, int);
  1793. void sqlite3BeginTransaction(Parse*, int);
  1794. void sqlite3CommitTransaction(Parse*);
  1795. void sqlite3RollbackTransaction(Parse*);
  1796. int sqlite3ExprIsConstant(Expr*);
  1797. int sqlite3ExprIsConstantNotJoin(Expr*);
  1798. int sqlite3ExprIsConstantOrFunction(Expr*);
  1799. int sqlite3ExprIsInteger(Expr*, int*);
  1800. int sqlite3IsRowid(const char*);
  1801. void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int);
  1802. void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
  1803. int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
  1804. void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
  1805.                                      int*,int,int,int,int);
  1806. void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*,int,int,int,int);
  1807. int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
  1808. void sqlite3BeginWriteOperation(Parse*, int, int);
  1809. Expr *sqlite3ExprDup(sqlite3*,Expr*);
  1810. void sqlite3TokenCopy(sqlite3*,Token*, Token*);
  1811. ExprList *sqlite3ExprListDup(sqlite3*,ExprList*);
  1812. SrcList *sqlite3SrcListDup(sqlite3*,SrcList*);
  1813. IdList *sqlite3IdListDup(sqlite3*,IdList*);
  1814. Select *sqlite3SelectDup(sqlite3*,Select*);
  1815. FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
  1816. void sqlite3RegisterBuiltinFunctions(sqlite3*);
  1817. void sqlite3RegisterDateTimeFunctions(sqlite3*);
  1818. #ifdef SQLITE_DEBUG
  1819.   int sqlite3SafetyOn(sqlite3*);
  1820.   int sqlite3SafetyOff(sqlite3*);
  1821. #else
  1822. # define sqlite3SafetyOn(A) 0
  1823. # define sqlite3SafetyOff(A) 0
  1824. #endif
  1825. int sqlite3SafetyCheckOk(sqlite3*);
  1826. int sqlite3SafetyCheckSickOrOk(sqlite3*);
  1827. void sqlite3ChangeCookie(Parse*, int);
  1828. void sqlite3MaterializeView(Parse*, Select*, Expr*, int);
  1829. #ifndef SQLITE_OMIT_TRIGGER
  1830.   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  1831.                            Expr*,int, int);
  1832.   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  1833.   void sqlite3DropTrigger(Parse*, SrcList*, int);
  1834.   void sqlite3DropTriggerPtr(Parse*, Trigger*);
  1835.   int sqlite3TriggersExist(Parse*, Table*, int, ExprList*);
  1836.   int sqlite3CodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int, 
  1837.                            int, int, u32*, u32*);
  1838.   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  1839.   void sqlite3DeleteTriggerStep(TriggerStep*);
  1840.   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  1841.   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  1842.                                         ExprList*,Select*,int);
  1843.   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, int);
  1844.   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  1845.   void sqlite3DeleteTrigger(Trigger*);
  1846.   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  1847. #else
  1848. # define sqlite3TriggersExist(A,B,C,D,E,F) 0
  1849. # define sqlite3DeleteTrigger(A)
  1850. # define sqlite3DropTriggerPtr(A,B)
  1851. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  1852. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I,J,K) 0
  1853. #endif
  1854. int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  1855. void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  1856. void sqlite3DeferForeignKey(Parse*, int);
  1857. #ifndef SQLITE_OMIT_AUTHORIZATION
  1858.   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  1859.   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  1860.   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  1861.   void sqlite3AuthContextPop(AuthContext*);
  1862. #else
  1863. # define sqlite3AuthRead(a,b,c,d)
  1864. # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
  1865. # define sqlite3AuthContextPush(a,b,c)
  1866. # define sqlite3AuthContextPop(a)  ((void)(a))
  1867. #endif
  1868. void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  1869. void sqlite3Detach(Parse*, Expr*);
  1870. int sqlite3BtreeFactory(const sqlite3 *db, const char *zFilename,
  1871.                        int omitJournal, int nCache, int flags, Btree **ppBtree);
  1872. int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  1873. int sqlite3FixSrcList(DbFixer*, SrcList*);
  1874. int sqlite3FixSelect(DbFixer*, Select*);
  1875. int sqlite3FixExpr(DbFixer*, Expr*);
  1876. int sqlite3FixExprList(DbFixer*, ExprList*);
  1877. int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  1878. int sqlite3AtoF(const char *z, double*);
  1879. char *sqlite3_snprintf(int,char*,const char*,...);
  1880. int sqlite3GetInt32(const char *, int*);
  1881. int sqlite3FitsIn64Bits(const char *, int);
  1882. int sqlite3Utf16ByteLen(const void *pData, int nChar);
  1883. int sqlite3Utf8CharLen(const char *pData, int nByte);
  1884. int sqlite3Utf8Read(const u8*, const u8*, const u8**);
  1885. int sqlite3PutVarint(unsigned char*, u64);
  1886. int sqlite3PutVarint32(unsigned char*, u32);
  1887. int sqlite3GetVarint(const unsigned char *, u64 *);
  1888. int sqlite3GetVarint32(const unsigned char *, u32 *);
  1889. int sqlite3VarintLen(u64 v);
  1890. void sqlite3IndexAffinityStr(Vdbe *, Index *);
  1891. void sqlite3TableAffinityStr(Vdbe *, Table *);
  1892. char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  1893. int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  1894. char sqlite3ExprAffinity(Expr *pExpr);
  1895. int sqlite3Atoi64(const char*, i64*);
  1896. void sqlite3Error(sqlite3*, int, const char*,...);
  1897. void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  1898. int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  1899. const char *sqlite3ErrStr(int);
  1900. int sqlite3ReadSchema(Parse *pParse);
  1901. CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char *,int,int);
  1902. CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName);
  1903. CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  1904. Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
  1905. int sqlite3CheckCollSeq(Parse *, CollSeq *);
  1906. int sqlite3CheckObjectName(Parse *, const char *);
  1907. void sqlite3VdbeSetChanges(sqlite3 *, int);
  1908. const void *sqlite3ValueText(sqlite3_value*, u8);
  1909. int sqlite3ValueBytes(sqlite3_value*, u8);
  1910. void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
  1911.                         void(*)(void*));
  1912. void sqlite3ValueFree(sqlite3_value*);
  1913. sqlite3_value *sqlite3ValueNew(sqlite3 *);
  1914. char *sqlite3Utf16to8(sqlite3 *, const void*, int);
  1915. int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  1916. void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  1917. #ifndef SQLITE_AMALGAMATION
  1918. extern const unsigned char sqlite3UpperToLower[];
  1919. #endif
  1920. void sqlite3RootPageMoved(Db*, int, int);
  1921. void sqlite3Reindex(Parse*, Token*, Token*);
  1922. void sqlite3AlterFunctions(sqlite3*);
  1923. void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  1924. int sqlite3GetToken(const unsigned char *, int *);
  1925. void sqlite3NestedParse(Parse*, const char*, ...);
  1926. void sqlite3ExpirePreparedStatements(sqlite3*);
  1927. void sqlite3CodeSubselect(Parse *, Expr *);
  1928. int sqlite3SelectResolve(Parse *, Select *, NameContext *);
  1929. void sqlite3ColumnDefault(Vdbe *, Table *, int);
  1930. void sqlite3AlterFinishAddColumn(Parse *, Token *);
  1931. void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  1932. CollSeq *sqlite3GetCollSeq(sqlite3*, CollSeq *, const char *, int);
  1933. char sqlite3AffinityType(const Token*);
  1934. void sqlite3Analyze(Parse*, Token*, Token*);
  1935. int sqlite3InvokeBusyHandler(BusyHandler*);
  1936. int sqlite3FindDb(sqlite3*, Token*);
  1937. int sqlite3AnalysisLoad(sqlite3*,int iDB);
  1938. void sqlite3DefaultRowEst(Index*);
  1939. void sqlite3RegisterLikeFunctions(sqlite3*, int);
  1940. int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  1941. void sqlite3AttachFunctions(sqlite3 *);
  1942. void sqlite3MinimumFileFormat(Parse*, int, int);
  1943. void sqlite3SchemaFree(void *);
  1944. Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  1945. int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  1946. KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
  1947. int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
  1948.   void (*)(sqlite3_context*,int,sqlite3_value **),
  1949.   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
  1950. int sqlite3ApiExit(sqlite3 *db, int);
  1951. int sqlite3OpenTempDatabase(Parse *);
  1952. void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  1953. char *sqlite3StrAccumFinish(StrAccum*);
  1954. void sqlite3StrAccumReset(StrAccum*);
  1955. void sqlite3SelectDestInit(SelectDest*,int,int);
  1956. /*
  1957. ** The interface to the LEMON-generated parser
  1958. */
  1959. void *sqlite3ParserAlloc(void*(*)(size_t));
  1960. void sqlite3ParserFree(void*, void(*)(void*));
  1961. void sqlite3Parser(void*, int, Token, Parse*);
  1962. int sqlite3AutoLoadExtensions(sqlite3*);
  1963. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  1964.   void sqlite3CloseExtensions(sqlite3*);
  1965. #else
  1966. # define sqlite3CloseExtensions(X)
  1967. #endif
  1968. #ifndef SQLITE_OMIT_SHARED_CACHE
  1969.   void sqlite3TableLock(Parse *, int, int, u8, const char *);
  1970. #else
  1971.   #define sqlite3TableLock(v,w,x,y,z)
  1972. #endif
  1973. #ifdef SQLITE_TEST
  1974.   int sqlite3Utf8To8(unsigned char*);
  1975. #endif
  1976. #ifdef SQLITE_OMIT_VIRTUALTABLE
  1977. #  define sqlite3VtabClear(X)
  1978. #  define sqlite3VtabSync(X,Y) (Y)
  1979. #  define sqlite3VtabRollback(X)
  1980. #  define sqlite3VtabCommit(X)
  1981. #else
  1982.    void sqlite3VtabClear(Table*);
  1983.    int sqlite3VtabSync(sqlite3 *db, int rc);
  1984.    int sqlite3VtabRollback(sqlite3 *db);
  1985.    int sqlite3VtabCommit(sqlite3 *db);
  1986. #endif
  1987. void sqlite3VtabLock(sqlite3_vtab*);
  1988. void sqlite3VtabUnlock(sqlite3*, sqlite3_vtab*);
  1989. void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
  1990. void sqlite3VtabFinishParse(Parse*, Token*);
  1991. void sqlite3VtabArgInit(Parse*);
  1992. void sqlite3VtabArgExtend(Parse*, Token*);
  1993. int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  1994. int sqlite3VtabCallConnect(Parse*, Table*);
  1995. int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  1996. int sqlite3VtabBegin(sqlite3 *, sqlite3_vtab *);
  1997. FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  1998. void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  1999. int sqlite3Reprepare(Vdbe*);
  2000. void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  2001. CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  2002. /*
  2003. ** Available fault injectors.  Should be numbered beginning with 0.
  2004. */
  2005. #define SQLITE_FAULTINJECTOR_MALLOC     0
  2006. #define SQLITE_FAULTINJECTOR_COUNT      1
  2007. /*
  2008. ** The interface to the fault injector subsystem.  If the fault injector
  2009. ** mechanism is disabled at compile-time then set up macros so that no
  2010. ** unnecessary code is generated.
  2011. */
  2012. #ifndef SQLITE_OMIT_BUILTIN_TEST
  2013.   void sqlite3FaultConfig(int,int,int);
  2014.   int sqlite3FaultFailures(int);
  2015.   int sqlite3FaultBenignFailures(int);
  2016.   int sqlite3FaultPending(int);
  2017.   void sqlite3FaultBenign(int,int);
  2018.   int sqlite3FaultStep(int);
  2019. #else
  2020. # define sqlite3FaultConfig(A,B,C)
  2021. # define sqlite3FaultFailures(A)         0
  2022. # define sqlite3FaultBenignFailures(A)   0
  2023. # define sqlite3FaultPending(A)          (-1)
  2024. # define sqlite3FaultBenign(A,B)
  2025. # define sqlite3FaultStep(A)             0
  2026. #endif
  2027.   
  2028.   
  2029. #define IN_INDEX_ROWID           1
  2030. #define IN_INDEX_EPH             2
  2031. #define IN_INDEX_INDEX           3
  2032. int sqlite3FindInIndex(Parse *, Expr *, int);
  2033. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  2034.   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  2035.   int sqlite3JournalSize(sqlite3_vfs *);
  2036.   int sqlite3JournalCreate(sqlite3_file *);
  2037. #else
  2038.   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
  2039. #endif
  2040. #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
  2041.   void sqlite3ExprSetHeight(Expr *);
  2042.   int sqlite3SelectExprHeight(Select *);
  2043. #else
  2044.   #define sqlite3ExprSetHeight(x)
  2045. #endif
  2046. u32 sqlite3Get4byte(const u8*);
  2047. void sqlite3Put4byte(u8*, u32);
  2048. #ifdef SQLITE_SSE
  2049. #include "sseInt.h"
  2050. #endif
  2051. #ifdef SQLITE_DEBUG
  2052.   void sqlite3ParserTrace(FILE*, char *);
  2053. #endif
  2054. /*
  2055. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  2056. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  2057. ** print I/O tracing messages. 
  2058. */
  2059. #ifdef SQLITE_ENABLE_IOTRACE
  2060. # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  2061.   void sqlite3VdbeIOTraceSql(Vdbe*);
  2062. #else
  2063. # define IOTRACE(A)
  2064. # define sqlite3VdbeIOTraceSql(X)
  2065. #endif
  2066. SQLITE_EXTERN void (*sqlite3IoTrace)(const char*,...);
  2067. #endif