You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1192 lines
52 KiB

  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$
  15. */
  16. #include "config.h"
  17. #include "sqlite.h"
  18. #include "hash.h"
  19. #include "vdbe.h"
  20. #include "parse.h"
  21. #include "btree.h"
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include <assert.h>
  26. /*
  27. ** The maximum number of in-memory pages to use for the main database
  28. ** table and for temporary tables.
  29. */
  30. #define MAX_PAGES 2000
  31. #define TEMP_PAGES 500
  32. /*
  33. ** If the following macro is set to 1, then NULL values are considered
  34. ** distinct for the SELECT DISTINCT statement and for UNION or EXCEPT
  35. ** compound queries. No other SQL database engine (among those tested)
  36. ** works this way except for OCELOT. But the SQL92 spec implies that
  37. ** this is how things should work.
  38. **
  39. ** If the following macro is set to 0, then NULLs are indistinct for
  40. ** SELECT DISTINCT and for UNION.
  41. */
  42. #define NULL_ALWAYS_DISTINCT 0
  43. /*
  44. ** If the following macro is set to 1, then NULL values are considered
  45. ** distinct when determining whether or not two entries are the same
  46. ** in a UNIQUE index. This is the way PostgreSQL, Oracle, DB2, MySQL,
  47. ** OCELOT, and Firebird all work. The SQL92 spec explicitly says this
  48. ** is the way things are suppose to work.
  49. **
  50. ** If the following macro is set to 0, the NULLs are indistinct for
  51. ** a UNIQUE index. In this mode, you can only have a single NULL entry
  52. ** for a column declared UNIQUE. This is the way Informix and SQL Server
  53. ** work.
  54. */
  55. #define NULL_DISTINCT_FOR_UNIQUE 1
  56. /*
  57. ** The maximum number of attached databases. This must be at least 2
  58. ** in order to support the main database file (0) and the file used to
  59. ** hold temporary tables (1). And it must be less than 256 because
  60. ** an unsigned character is used to stored the database index.
  61. */
  62. #define MAX_ATTACHED 10
  63. /*
  64. ** The next macro is used to determine where TEMP tables and indices
  65. ** are stored. Possible values:
  66. **
  67. ** 0 Always use a temporary files
  68. ** 1 Use a file unless overridden by "PRAGMA temp_store"
  69. ** 2 Use memory unless overridden by "PRAGMA temp_store"
  70. ** 3 Always use memory
  71. */
  72. #ifndef TEMP_STORE
  73. # define TEMP_STORE 1
  74. #endif
  75. /*
  76. ** When building SQLite for embedded systems where memory is scarce,
  77. ** you can define one or more of the following macros to omit extra
  78. ** features of the library and thus keep the size of the library to
  79. ** a minimum.
  80. */
  81. /* #define SQLITE_OMIT_AUTHORIZATION 1 */
  82. /* #define SQLITE_OMIT_INMEMORYDB 1 */
  83. /* #define SQLITE_OMIT_VACUUM 1 */
  84. /*
  85. ** Integers of known sizes. These typedefs might change for architectures
  86. ** where the sizes very. Preprocessor macros are available so that the
  87. ** types can be conveniently redefined at compile-type. Like this:
  88. **
  89. ** cc '-DUINTPTR_TYPE=long long int' ...
  90. */
  91. #ifndef UINT32_TYPE
  92. # define UINT32_TYPE unsigned int
  93. #endif
  94. #ifndef UINT16_TYPE
  95. # define UINT16_TYPE unsigned short int
  96. #endif
  97. #ifndef UINT8_TYPE
  98. # define UINT8_TYPE unsigned char
  99. #endif
  100. #ifndef INTPTR_TYPE
  101. # if SQLITE_PTR_SZ==4
  102. # define INTPTR_TYPE int
  103. # else
  104. # define INTPTR_TYPE long long
  105. # endif
  106. #endif
  107. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  108. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  109. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  110. typedef INTPTR_TYPE ptr; /* Big enough to hold a pointer */
  111. typedef unsigned INTPTR_TYPE uptr; /* Big enough to hold a pointer */
  112. /*
  113. ** This macro casts a pointer to an integer. Useful for doing
  114. ** pointer arithmetic.
  115. */
  116. #define Addr(X) ((uptr)X)
  117. /*
  118. ** The maximum number of bytes of data that can be put into a single
  119. ** row of a single table. The upper bound on this limit is 16777215
  120. ** bytes (or 16MB-1). We have arbitrarily set the limit to just 1MB
  121. ** here because the overflow page chain is inefficient for really big
  122. ** records and we want to discourage people from thinking that
  123. ** multi-megabyte records are OK. If your needs are different, you can
  124. ** change this define and recompile to increase or decrease the record
  125. ** size.
  126. **
  127. ** The 16777198 is computed as follows: 238 bytes of payload on the
  128. ** original pages plus 16448 overflow pages each holding 1020 bytes of
  129. ** data.
  130. */
  131. #define MAX_BYTES_PER_ROW 1048576
  132. /* #define MAX_BYTES_PER_ROW 16777198 */
  133. /*
  134. ** If memory allocation problems are found, recompile with
  135. **
  136. ** -DMEMORY_DEBUG=1
  137. **
  138. ** to enable some sanity checking on malloc() and free(). To
  139. ** check for memory leaks, recompile with
  140. **
  141. ** -DMEMORY_DEBUG=2
  142. **
  143. ** and a line of text will be written to standard error for
  144. ** each malloc() and free(). This output can be analyzed
  145. ** by an AWK script to determine if there are any leaks.
  146. */
  147. #ifdef MEMORY_DEBUG
  148. # define sqliteMalloc(X) sqliteMalloc_(X,1,__FILE__,__LINE__)
  149. # define sqliteMallocRaw(X) sqliteMalloc_(X,0,__FILE__,__LINE__)
  150. # define sqliteFree(X) sqliteFree_(X,__FILE__,__LINE__)
  151. # define sqliteRealloc(X,Y) sqliteRealloc_(X,Y,__FILE__,__LINE__)
  152. # define sqliteStrDup(X) sqliteStrDup_(X,__FILE__,__LINE__)
  153. # define sqliteStrNDup(X,Y) sqliteStrNDup_(X,Y,__FILE__,__LINE__)
  154. void sqliteStrRealloc(char**);
  155. #else
  156. # define sqliteStrRealloc(X)
  157. #endif
  158. /*
  159. ** This variable gets set if malloc() ever fails. After it gets set,
  160. ** the SQLite library shuts down permanently.
  161. */
  162. extern int sqlite_malloc_failed;
  163. /*
  164. ** The following global variables are used for testing and debugging
  165. ** only. They only work if MEMORY_DEBUG is defined.
  166. */
  167. #ifdef MEMORY_DEBUG
  168. extern int sqlite_nMalloc; /* Number of sqliteMalloc() calls */
  169. extern int sqlite_nFree; /* Number of sqliteFree() calls */
  170. extern int sqlite_iMallocFail; /* Fail sqliteMalloc() after this many calls */
  171. #endif
  172. /*
  173. ** Name of the master database table. The master database table
  174. ** is a special table that holds the names and attributes of all
  175. ** user tables and indices.
  176. */
  177. #define MASTER_NAME "sqlite_master"
  178. #define TEMP_MASTER_NAME "sqlite_temp_master"
  179. /*
  180. ** The name of the schema table.
  181. */
  182. #define SCHEMA_TABLE(x) (x?TEMP_MASTER_NAME:MASTER_NAME)
  183. /*
  184. ** A convenience macro that returns the number of elements in
  185. ** an array.
  186. */
  187. #define ArraySize(X) (sizeof(X)/sizeof(X[0]))
  188. /*
  189. ** Forward references to structures
  190. */
  191. typedef struct Column Column;
  192. typedef struct Table Table;
  193. typedef struct Index Index;
  194. typedef struct Instruction Instruction;
  195. typedef struct Expr Expr;
  196. typedef struct ExprList ExprList;
  197. typedef struct Parse Parse;
  198. typedef struct Token Token;
  199. typedef struct IdList IdList;
  200. typedef struct SrcList SrcList;
  201. typedef struct WhereInfo WhereInfo;
  202. typedef struct WhereLevel WhereLevel;
  203. typedef struct Select Select;
  204. typedef struct AggExpr AggExpr;
  205. typedef struct FuncDef FuncDef;
  206. typedef struct Trigger Trigger;
  207. typedef struct TriggerStep TriggerStep;
  208. typedef struct TriggerStack TriggerStack;
  209. typedef struct FKey FKey;
  210. typedef struct Db Db;
  211. typedef struct AuthContext AuthContext;
  212. /*
  213. ** Each database file to be accessed by the system is an instance
  214. ** of the following structure. There are normally two of these structures
  215. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  216. ** aDb[1] is the database file used to hold temporary tables. Additional
  217. ** databases may be attached.
  218. */
  219. struct Db {
  220. char *zName; /* Name of this database */
  221. Btree *pBt; /* The B*Tree structure for this database file */
  222. int schema_cookie; /* Database schema version number for this file */
  223. Hash tblHash; /* All tables indexed by name */
  224. Hash idxHash; /* All (named) indices indexed by name */
  225. Hash trigHash; /* All triggers indexed by name */
  226. Hash aFKey; /* Foreign keys indexed by to-table */
  227. u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */
  228. u16 flags; /* Flags associated with this database */
  229. };
  230. /*
  231. ** These macros can be used to test, set, or clear bits in the
  232. ** Db.flags field.
  233. */
  234. #define DbHasProperty(D,I,P) (((D)->aDb[I].flags&(P))==(P))
  235. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].flags&(P))!=0)
  236. #define DbSetProperty(D,I,P) (D)->aDb[I].flags|=(P)
  237. #define DbClearProperty(D,I,P) (D)->aDb[I].flags&=~(P)
  238. /*
  239. ** Allowed values for the DB.flags field.
  240. **
  241. ** The DB_Locked flag is set when the first OP_Transaction or OP_Checkpoint
  242. ** opcode is emitted for a database. This prevents multiple occurances
  243. ** of those opcodes for the same database in the same program. Similarly,
  244. ** the DB_Cookie flag is set when the OP_VerifyCookie opcode is emitted,
  245. ** and prevents duplicate OP_VerifyCookies from taking up space and slowing
  246. ** down execution.
  247. **
  248. ** The DB_SchemaLoaded flag is set after the database schema has been
  249. ** read into internal hash tables.
  250. **
  251. ** DB_UnresetViews means that one or more views have column names that
  252. ** have been filled out. If the schema changes, these column names might
  253. ** changes and so the view will need to be reset.
  254. */
  255. #define DB_Locked 0x0001 /* OP_Transaction opcode has been emitted */
  256. #define DB_Cookie 0x0002 /* OP_VerifyCookie opcode has been emiited */
  257. #define DB_SchemaLoaded 0x0004 /* The schema has been loaded */
  258. #define DB_UnresetViews 0x0008 /* Some views have defined column names */
  259. /*
  260. ** Each database is an instance of the following structure.
  261. **
  262. ** The sqlite.file_format is initialized by the database file
  263. ** and helps determines how the data in the database file is
  264. ** represented. This field allows newer versions of the library
  265. ** to read and write older databases. The various file formats
  266. ** are as follows:
  267. **
  268. ** file_format==1 Version 2.1.0.
  269. ** file_format==2 Version 2.2.0. Add support for INTEGER PRIMARY KEY.
  270. ** file_format==3 Version 2.6.0. Fix empty-string index bug.
  271. ** file_format==4 Version 2.7.0. Add support for separate numeric and
  272. ** text datatypes.
  273. **
  274. ** The sqlite.temp_store determines where temporary database files
  275. ** are stored. If 1, then a file is created to hold those tables. If
  276. ** 2, then they are held in memory. 0 means use the default value in
  277. ** the TEMP_STORE macro.
  278. */
  279. struct sqlite {
  280. int nDb; /* Number of backends currently in use */
  281. Db *aDb; /* All backends */
  282. Db aDbStatic[2]; /* Static space for the 2 default backends */
  283. int flags; /* Miscellanous flags. See below */
  284. u8 file_format; /* What file format version is this database? */
  285. u8 safety_level; /* How aggressive at synching data to disk */
  286. u8 want_to_close; /* Close after all VDBEs are deallocated */
  287. int next_cookie; /* Next value of aDb[0].schema_cookie */
  288. int cache_size; /* Number of pages to use in the cache */
  289. int temp_store; /* 1=file, 2=memory, 0=compile-time default */
  290. int nTable; /* Number of tables in the database */
  291. void *pBusyArg; /* 1st Argument to the busy callback */
  292. int (*xBusyCallback)(void *,const char*,int); /* The busy callback */
  293. Hash aFunc; /* All functions that can be in SQL exprs */
  294. int lastRowid; /* ROWID of most recent insert */
  295. int priorNewRowid; /* Last randomly generated ROWID */
  296. int onError; /* Default conflict algorithm */
  297. int magic; /* Magic number for detect library misuse */
  298. int nChange; /* Number of rows changed */
  299. struct Vdbe *pVdbe; /* List of active virtual machines */
  300. #ifndef SQLITE_OMIT_TRACE
  301. void (*xTrace)(void*,const char*); /* Trace function */
  302. void *pTraceArg; /* Argument to the trace function */
  303. #endif
  304. #ifndef SQLITE_OMIT_AUTHORIZATION
  305. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  306. /* Access authorization function */
  307. void *pAuthArg; /* 1st argument to the access auth function */
  308. #endif
  309. };
  310. /*
  311. ** Possible values for the sqlite.flags and or Db.flags fields.
  312. **
  313. ** On sqlite.flags, the SQLITE_InTrans value means that we have
  314. ** executed a BEGIN. On Db.flags, SQLITE_InTrans means a statement
  315. ** transaction is active on that particular database file.
  316. */
  317. #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
  318. #define SQLITE_Initialized 0x00000002 /* True after initialization */
  319. #define SQLITE_Interrupt 0x00000004 /* Cancel current operation */
  320. #define SQLITE_InTrans 0x00000008 /* True if in a transaction */
  321. #define SQLITE_InternChanges 0x00000010 /* Uncommitted Hash table changes */
  322. #define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
  323. #define SQLITE_CountRows 0x00000040 /* Count rows changed by INSERT, */
  324. /* DELETE, or UPDATE and return */
  325. /* the count using a callback. */
  326. #define SQLITE_NullCallback 0x00000080 /* Invoke the callback once if the */
  327. /* result set is empty */
  328. #define SQLITE_ReportTypes 0x00000200 /* Include information on datatypes */
  329. /* in 4th argument of callback */
  330. /*
  331. ** Possible values for the sqlite.magic field.
  332. ** The numbers are obtained at random and have no special meaning, other
  333. ** than being distinct from one another.
  334. */
  335. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  336. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  337. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  338. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  339. /*
  340. ** Each SQL function is defined by an instance of the following
  341. ** structure. A pointer to this structure is stored in the sqlite.aFunc
  342. ** hash table. When multiple functions have the same name, the hash table
  343. ** points to a linked list of these structures.
  344. */
  345. struct FuncDef {
  346. void (*xFunc)(sqlite_func*,int,const char**); /* Regular function */
  347. void (*xStep)(sqlite_func*,int,const char**); /* Aggregate function step */
  348. void (*xFinalize)(sqlite_func*); /* Aggregate function finializer */
  349. int nArg; /* Number of arguments */
  350. int dataType; /* Datatype of the result */
  351. void *pUserData; /* User data parameter */
  352. FuncDef *pNext; /* Next function with same name */
  353. };
  354. /*
  355. ** information about each column of an SQL table is held in an instance
  356. ** of this structure.
  357. */
  358. struct Column {
  359. char *zName; /* Name of this column */
  360. char *zDflt; /* Default value of this column */
  361. char *zType; /* Data type for this column */
  362. u8 notNull; /* True if there is a NOT NULL constraint */
  363. u8 isPrimKey; /* True if this column is an INTEGER PRIMARY KEY */
  364. u8 sortOrder; /* Some combination of SQLITE_SO_... values */
  365. };
  366. /*
  367. ** The allowed sort orders.
  368. **
  369. ** The TEXT and NUM values use bits that do not overlap with DESC and ASC.
  370. ** That way the two can be combined into a single number.
  371. */
  372. #define SQLITE_SO_UNK 0 /* Use the default collating type. (SCT_NUM) */
  373. #define SQLITE_SO_TEXT 2 /* Sort using memcmp() */
  374. #define SQLITE_SO_NUM 4 /* Sort using sqliteCompare() */
  375. #define SQLITE_SO_TYPEMASK 6 /* Mask to extract the collating sequence */
  376. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  377. #define SQLITE_SO_DESC 1 /* Sort in descending order */
  378. #define SQLITE_SO_DIRMASK 1 /* Mask to extract the sort direction */
  379. /*
  380. ** Each SQL table is represented in memory by an instance of the
  381. ** following structure.
  382. **
  383. ** Table.zName is the name of the table. The case of the original
  384. ** CREATE TABLE statement is stored, but case is not significant for
  385. ** comparisons.
  386. **
  387. ** Table.nCol is the number of columns in this table. Table.aCol is a
  388. ** pointer to an array of Column structures, one for each column.
  389. **
  390. ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
  391. ** the column that is that key. Otherwise Table.iPKey is negative. Note
  392. ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
  393. ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
  394. ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
  395. ** is generated for each row of the table. Table.hasPrimKey is true if
  396. ** the table has any PRIMARY KEY, INTEGER or otherwise.
  397. **
  398. ** Table.tnum is the page number for the root BTree page of the table in the
  399. ** database file. If Table.iDb is the index of the database table backend
  400. ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
  401. ** holds temporary tables and indices. If Table.isTransient
  402. ** is true, then the table is stored in a file that is automatically deleted
  403. ** when the VDBE cursor to the table is closed. In this case Table.tnum
  404. ** refers VDBE cursor number that holds the table open, not to the root
  405. ** page number. Transient tables are used to hold the results of a
  406. ** sub-query that appears instead of a real table name in the FROM clause
  407. ** of a SELECT statement.
  408. */
  409. struct Table {
  410. char *zName; /* Name of the table */
  411. int nCol; /* Number of columns in this table */
  412. Column *aCol; /* Information about each column */
  413. int iPKey; /* If not less then 0, use aCol[iPKey] as the primary key */
  414. Index *pIndex; /* List of SQL indexes on this table. */
  415. int tnum; /* Root BTree node for this table (see note above) */
  416. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  417. u8 readOnly; /* True if this table should not be written by the user */
  418. u8 iDb; /* Index into sqlite.aDb[] of the backend for this table */
  419. u8 isTransient; /* True if automatically deleted when VDBE finishes */
  420. u8 hasPrimKey; /* True if there exists a primary key */
  421. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  422. Trigger *pTrigger; /* List of SQL triggers on this table */
  423. FKey *pFKey; /* Linked list of all foreign keys in this table */
  424. };
  425. /*
  426. ** Each foreign key constraint is an instance of the following structure.
  427. **
  428. ** A foreign key is associated with two tables. The "from" table is
  429. ** the table that contains the REFERENCES clause that creates the foreign
  430. ** key. The "to" table is the table that is named in the REFERENCES clause.
  431. ** Consider this example:
  432. **
  433. ** CREATE TABLE ex1(
  434. ** a INTEGER PRIMARY KEY,
  435. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  436. ** );
  437. **
  438. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  439. **
  440. ** Each REFERENCES clause generates an instance of the following structure
  441. ** which is attached to the from-table. The to-table need not exist when
  442. ** the from-table is created. The existance of the to-table is not checked
  443. ** until an attempt is made to insert data into the from-table.
  444. **
  445. ** The sqlite.aFKey hash table stores pointers to this structure
  446. ** given the name of a to-table. For each to-table, all foreign keys
  447. ** associated with that table are on a linked list using the FKey.pNextTo
  448. ** field.
  449. */
  450. struct FKey {
  451. Table *pFrom; /* The table that constains the REFERENCES clause */
  452. FKey *pNextFrom; /* Next foreign key in pFrom */
  453. char *zTo; /* Name of table that the key points to */
  454. FKey *pNextTo; /* Next foreign key that points to zTo */
  455. int nCol; /* Number of columns in this key */
  456. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  457. int iFrom; /* Index of column in pFrom */
  458. char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
  459. } *aCol; /* One entry for each of nCol column s */
  460. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  461. u8 updateConf; /* How to resolve conflicts that occur on UPDATE */
  462. u8 deleteConf; /* How to resolve conflicts that occur on DELETE */
  463. u8 insertConf; /* How to resolve conflicts that occur on INSERT */
  464. };
  465. /*
  466. ** SQLite supports many different ways to resolve a contraint
  467. ** error. ROLLBACK processing means that a constraint violation
  468. ** causes the operation in process to fail and for the current transaction
  469. ** to be rolled back. ABORT processing means the operation in process
  470. ** fails and any prior changes from that one operation are backed out,
  471. ** but the transaction is not rolled back. FAIL processing means that
  472. ** the operation in progress stops and returns an error code. But prior
  473. ** changes due to the same operation are not backed out and no rollback
  474. ** occurs. IGNORE means that the particular row that caused the constraint
  475. ** error is not inserted or updated. Processing continues and no error
  476. ** is returned. REPLACE means that preexisting database rows that caused
  477. ** a UNIQUE constraint violation are removed so that the new insert or
  478. ** update can proceed. Processing continues and no error is reported.
  479. **
  480. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  481. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  482. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  483. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  484. ** referenced table row is propagated into the row that holds the
  485. ** foreign key.
  486. **
  487. ** The following symbolic values are used to record which type
  488. ** of action to take.
  489. */
  490. #define OE_None 0 /* There is no constraint to check */
  491. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  492. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  493. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  494. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  495. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  496. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  497. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  498. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  499. #define OE_Cascade 9 /* Cascade the changes */
  500. #define OE_Default 99 /* Do whatever the default action is */
  501. /*
  502. ** Each SQL index is represented in memory by an
  503. ** instance of the following structure.
  504. **
  505. ** The columns of the table that are to be indexed are described
  506. ** by the aiColumn[] field of this structure. For example, suppose
  507. ** we have the following table and index:
  508. **
  509. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  510. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  511. **
  512. ** In the Table structure describing Ex1, nCol==3 because there are
  513. ** three columns in the table. In the Index structure describing
  514. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  515. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  516. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  517. ** The second column to be indexed (c1) has an index of 0 in
  518. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  519. **
  520. ** The Index.onError field determines whether or not the indexed columns
  521. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  522. ** it means this is not a unique index. Otherwise it is a unique index
  523. ** and the value of Index.onError indicate the which conflict resolution
  524. ** algorithm to employ whenever an attempt is made to insert a non-unique
  525. ** element.
  526. */
  527. struct Index {
  528. char *zName; /* Name of this index */
  529. int nColumn; /* Number of columns in the table used by this index */
  530. int *aiColumn; /* Which columns are used by this index. 1st is 0 */
  531. Table *pTable; /* The SQL table being indexed */
  532. int tnum; /* Page containing root of this index in database file */
  533. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  534. u8 autoIndex; /* True if is automatically created (ex: by UNIQUE) */
  535. u8 iDb; /* Index in sqlite.aDb[] of where this index is stored */
  536. Index *pNext; /* The next index associated with the same table */
  537. };
  538. /*
  539. ** Each token coming out of the lexer is an instance of
  540. ** this structure. Tokens are also used as part of an expression.
  541. */
  542. struct Token {
  543. const char *z; /* Text of the token. Not NULL-terminated! */
  544. unsigned dyn : 1; /* True for malloced memory, false for static */
  545. unsigned n : 31; /* Number of characters in this token */
  546. };
  547. /*
  548. ** Each node of an expression in the parse tree is an instance
  549. ** of this structure.
  550. **
  551. ** Expr.op is the opcode. The integer parser token codes are reused
  552. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  553. ** code representing the ">=" operator. This same integer code is reused
  554. ** to represent the greater-than-or-equal-to operator in the expression
  555. ** tree.
  556. **
  557. ** Expr.pRight and Expr.pLeft are subexpressions. Expr.pList is a list
  558. ** of argument if the expression is a function.
  559. **
  560. ** Expr.token is the operator token for this node. For some expressions
  561. ** that have subexpressions, Expr.token can be the complete text that gave
  562. ** rise to the Expr. In the latter case, the token is marked as being
  563. ** a compound token.
  564. **
  565. ** An expression of the form ID or ID.ID refers to a column in a table.
  566. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  567. ** the integer cursor number of a VDBE cursor pointing to that table and
  568. ** Expr.iColumn is the column number for the specific column. If the
  569. ** expression is used as a result in an aggregate SELECT, then the
  570. ** value is also stored in the Expr.iAgg column in the aggregate so that
  571. ** it can be accessed after all aggregates are computed.
  572. **
  573. ** If the expression is a function, the Expr.iTable is an integer code
  574. ** representing which function.
  575. **
  576. ** The Expr.pSelect field points to a SELECT statement. The SELECT might
  577. ** be the right operand of an IN operator. Or, if a scalar SELECT appears
  578. ** in an expression the opcode is TK_SELECT and Expr.pSelect is the only
  579. ** operand.
  580. */
  581. struct Expr {
  582. u8 op; /* Operation performed by this node */
  583. u8 dataType; /* Either SQLITE_SO_TEXT or SQLITE_SO_NUM */
  584. u8 iDb; /* Database referenced by this expression */
  585. u8 flags; /* Various flags. See below */
  586. Expr *pLeft, *pRight; /* Left and right subnodes */
  587. ExprList *pList; /* A list of expressions used as function arguments
  588. ** or in "<expr> IN (<expr-list)" */
  589. Token token; /* An operand token */
  590. Token span; /* Complete text of the expression */
  591. int iTable, iColumn; /* When op==TK_COLUMN, then this expr node means the
  592. ** iColumn-th field of the iTable-th table. */
  593. int iAgg; /* When op==TK_COLUMN and pParse->useAgg==TRUE, pull
  594. ** result from the iAgg-th element of the aggregator */
  595. Select *pSelect; /* When the expression is a sub-select. Also the
  596. ** right side of "<expr> IN (<select>)" */
  597. };
  598. /*
  599. ** The following are the meanings of bits in the Expr.flags field.
  600. */
  601. #define EP_FromJoin 0x0001 /* Originated in ON or USING clause of a join */
  602. #define EP_Oracle8Join 0x0002 /* Carries the Oracle8 "(+)" join operator */
  603. /*
  604. ** These macros can be used to test, set, or clear bits in the
  605. ** Expr.flags field.
  606. */
  607. #define ExprHasProperty(E,P) (((E)->flags&(P))==(P))
  608. #define ExprHasAnyProperty(E,P) (((E)->flags&(P))!=0)
  609. #define ExprSetProperty(E,P) (E)->flags|=(P)
  610. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  611. /*
  612. ** A list of expressions. Each expression may optionally have a
  613. ** name. An expr/name combination can be used in several ways, such
  614. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  615. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  616. ** also be used as the argument to a function, in which case the a.zName
  617. ** field is not used.
  618. */
  619. struct ExprList {
  620. int nExpr; /* Number of expressions on the list */
  621. struct ExprList_item {
  622. Expr *pExpr; /* The list of expressions */
  623. char *zName; /* Token associated with this expression */
  624. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  625. u8 isAgg; /* True if this is an aggregate like count(*) */
  626. u8 done; /* A flag to indicate when processing is finished */
  627. } *a; /* One entry for each expression */
  628. };
  629. /*
  630. ** An instance of this structure can hold a simple list of identifiers,
  631. ** such as the list "a,b,c" in the following statements:
  632. **
  633. ** INSERT INTO t(a,b,c) VALUES ...;
  634. ** CREATE INDEX idx ON t(a,b,c);
  635. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  636. **
  637. ** The IdList.a.idx field is used when the IdList represents the list of
  638. ** column names after a table name in an INSERT statement. In the statement
  639. **
  640. ** INSERT INTO t(a,b,c) ...
  641. **
  642. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  643. */
  644. struct IdList {
  645. int nId; /* Number of identifiers on the list */
  646. struct IdList_item {
  647. char *zName; /* Name of the identifier */
  648. int idx; /* Index in some Table.aCol[] of a column named zName */
  649. } *a;
  650. };
  651. /*
  652. ** The following structure describes the FROM clause of a SELECT statement.
  653. ** Each table or subquery in the FROM clause is a separate element of
  654. ** the SrcList.a[] array.
  655. **
  656. ** With the addition of multiple database support, the following structure
  657. ** can also be used to describe a particular table such as the table that
  658. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  659. ** such a table must be a simple name: ID. But in SQLite, the table can
  660. ** now be identified by a database name, a dot, then the table name: ID.ID.
  661. */
  662. struct SrcList {
  663. int nSrc; /* Number of tables or subqueries in the FROM clause */
  664. struct SrcList_item {
  665. char *zDatabase; /* Name of database holding this table */
  666. char *zName; /* Name of the table */
  667. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  668. Table *pTab; /* An SQL table corresponding to zName */
  669. Select *pSelect; /* A SELECT statement used in place of a table name */
  670. int jointype; /* Type of join between this table and the next */
  671. int iCursor; /* The VDBE cursor number used to access this table */
  672. Expr *pOn; /* The ON clause of a join */
  673. IdList *pUsing; /* The USING clause of a join */
  674. } a[1]; /* One entry for each identifier on the list */
  675. };
  676. /*
  677. ** Permitted values of the SrcList.a.jointype field
  678. */
  679. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  680. #define JT_NATURAL 0x0002 /* True for a "natural" join */
  681. #define JT_LEFT 0x0004 /* Left outer join */
  682. #define JT_RIGHT 0x0008 /* Right outer join */
  683. #define JT_OUTER 0x0010 /* The "OUTER" keyword is present */
  684. #define JT_ERROR 0x0020 /* unknown or unsupported join type */
  685. /*
  686. ** For each nested loop in a WHERE clause implementation, the WhereInfo
  687. ** structure contains a single instance of this structure. This structure
  688. ** is intended to be private the the where.c module and should not be
  689. ** access or modified by other modules.
  690. */
  691. struct WhereLevel {
  692. int iMem; /* Memory cell used by this level */
  693. Index *pIdx; /* Index used */
  694. int iCur; /* Cursor number used for this index */
  695. int score; /* How well this indexed scored */
  696. int brk; /* Jump here to break out of the loop */
  697. int cont; /* Jump here to continue with the next loop cycle */
  698. int op, p1, p2; /* Opcode used to terminate the loop */
  699. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  700. int top; /* First instruction of interior of the loop */
  701. int inOp, inP1, inP2;/* Opcode used to implement an IN operator */
  702. int bRev; /* Do the scan in the reverse direction */
  703. };
  704. /*
  705. ** The WHERE clause processing routine has two halves. The
  706. ** first part does the start of the WHERE loop and the second
  707. ** half does the tail of the WHERE loop. An instance of
  708. ** this structure is returned by the first half and passed
  709. ** into the second half to give some continuity.
  710. */
  711. struct WhereInfo {
  712. Parse *pParse;
  713. SrcList *pTabList; /* List of tables in the join */
  714. int iContinue; /* Jump here to continue with next record */
  715. int iBreak; /* Jump here to break out of the loop */
  716. int nLevel; /* Number of nested loop */
  717. int savedNTab; /* Value of pParse->nTab before WhereBegin() */
  718. int peakNTab; /* Value of pParse->nTab after WhereBegin() */
  719. WhereLevel a[1]; /* Information about each nest loop in the WHERE */
  720. };
  721. /*
  722. ** An instance of the following structure contains all information
  723. ** needed to generate code for a single SELECT statement.
  724. **
  725. ** The zSelect field is used when the Select structure must be persistent.
  726. ** Normally, the expression tree points to tokens in the original input
  727. ** string that encodes the select. But if the Select structure must live
  728. ** longer than its input string (for example when it is used to describe
  729. ** a VIEW) we have to make a copy of the input string so that the nodes
  730. ** of the expression tree will have something to point to. zSelect is used
  731. ** to hold that copy.
  732. **
  733. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  734. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  735. ** limit and nOffset to the value of the offset (or 0 if there is not
  736. ** offset). But later on, nLimit and nOffset become the memory locations
  737. ** in the VDBE that record the limit and offset counters.
  738. */
  739. struct Select {
  740. int isDistinct; /* True if the DISTINCT keyword is present */
  741. ExprList *pEList; /* The fields of the result */
  742. SrcList *pSrc; /* The FROM clause */
  743. Expr *pWhere; /* The WHERE clause */
  744. ExprList *pGroupBy; /* The GROUP BY clause */
  745. Expr *pHaving; /* The HAVING clause */
  746. ExprList *pOrderBy; /* The ORDER BY clause */
  747. int op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  748. Select *pPrior; /* Prior select in a compound select statement */
  749. int nLimit, nOffset; /* LIMIT and OFFSET values. -1 means not used */
  750. char *zSelect; /* Complete text of the SELECT command */
  751. };
  752. /*
  753. ** The results of a select can be distributed in several ways.
  754. */
  755. #define SRT_Callback 1 /* Invoke a callback with each row of result */
  756. #define SRT_Mem 2 /* Store result in a memory cell */
  757. #define SRT_Set 3 /* Store result as unique keys in a table */
  758. #define SRT_Union 5 /* Store result as keys in a table */
  759. #define SRT_Except 6 /* Remove result from a UNION table */
  760. #define SRT_Table 7 /* Store result as data with a unique key */
  761. #define SRT_TempTable 8 /* Store result in a trasient table */
  762. #define SRT_Discard 9 /* Do not save the results anywhere */
  763. #define SRT_Sorter 10 /* Store results in the sorter */
  764. #define SRT_Subroutine 11 /* Call a subroutine to handle results */
  765. /*
  766. ** When a SELECT uses aggregate functions (like "count(*)" or "avg(f1)")
  767. ** we have to do some additional analysis of expressions. An instance
  768. ** of the following structure holds information about a single subexpression
  769. ** somewhere in the SELECT statement. An array of these structures holds
  770. ** all the information we need to generate code for aggregate
  771. ** expressions.
  772. **
  773. ** Note that when analyzing a SELECT containing aggregates, both
  774. ** non-aggregate field variables and aggregate functions are stored
  775. ** in the AggExpr array of the Parser structure.
  776. **
  777. ** The pExpr field points to an expression that is part of either the
  778. ** field list, the GROUP BY clause, the HAVING clause or the ORDER BY
  779. ** clause. The expression will be freed when those clauses are cleaned
  780. ** up. Do not try to delete the expression attached to AggExpr.pExpr.
  781. **
  782. ** If AggExpr.pExpr==0, that means the expression is "count(*)".
  783. */
  784. struct AggExpr {
  785. int isAgg; /* if TRUE contains an aggregate function */
  786. Expr *pExpr; /* The expression */
  787. FuncDef *pFunc; /* Information about the aggregate function */
  788. };
  789. /*
  790. ** An SQL parser context. A copy of this structure is passed through
  791. ** the parser and down into all the parser action routine in order to
  792. ** carry around information that is global to the entire parse.
  793. */
  794. struct Parse {
  795. sqlite *db; /* The main database structure */
  796. int rc; /* Return code from execution */
  797. sqlite_callback xCallback; /* The callback function */
  798. void *pArg; /* First argument to the callback function */
  799. char *zErrMsg; /* An error message */
  800. Token sErrToken; /* The token at which the error occurred */
  801. Token sFirstToken; /* The first token parsed */
  802. Token sLastToken; /* The last token parsed */
  803. const char *zTail; /* All SQL text past the last semicolon parsed */
  804. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  805. Vdbe *pVdbe; /* An engine for executing database bytecode */
  806. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  807. u8 explain; /* True if the EXPLAIN flag is found on the query */
  808. u8 initFlag; /* True if reparsing CREATE TABLEs */
  809. u8 nameClash; /* A permanent table name clashes with temp table name */
  810. u8 useAgg; /* If true, extract field values from the aggregator
  811. ** while generating expressions. Normally false */
  812. u8 iDb; /* Index of database whose schema is being parsed */
  813. u8 useCallback; /* True if callbacks should be used to report results */
  814. int newTnum; /* Table number to use when reparsing CREATE TABLEs */
  815. int nErr; /* Number of errors seen */
  816. int nTab; /* Number of previously allocated VDBE cursors */
  817. int nMem; /* Number of memory cells used so far */
  818. int nSet; /* Number of sets used so far */
  819. int nAgg; /* Number of aggregate expressions */
  820. AggExpr *aAgg; /* An array of aggregate expressions */
  821. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  822. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  823. TriggerStack *trigStack; /* Trigger actions being coded */
  824. };
  825. /*
  826. ** An instance of the following structure can be declared on a stack and used
  827. ** to save the Parse.zAuthContext value so that it can be restored later.
  828. */
  829. struct AuthContext {
  830. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  831. Parse *pParse; /* The Parse structure */
  832. };
  833. /*
  834. * Each trigger present in the database schema is stored as an instance of
  835. * struct Trigger.
  836. *
  837. * Pointers to instances of struct Trigger are stored in two ways.
  838. * 1. In the "trigHash" hash table (part of the sqlite* that represents the
  839. * database). This allows Trigger structures to be retrieved by name.
  840. * 2. All triggers associated with a single table form a linked list, using the
  841. * pNext member of struct Trigger. A pointer to the first element of the
  842. * linked list is stored as the "pTrigger" member of the associated
  843. * struct Table.
  844. *
  845. * The "step_list" member points to the first element of a linked list
  846. * containing the SQL statements specified as the trigger program.
  847. */
  848. struct Trigger {
  849. char *name; /* The name of the trigger */
  850. char *table; /* The table or view to which the trigger applies */
  851. u8 iDb; /* Database containing this trigger */
  852. u8 iTabDb; /* Database containing Trigger.table */
  853. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  854. u8 tr_tm; /* One of TK_BEFORE, TK_AFTER */
  855. Expr *pWhen; /* The WHEN clause of the expresion (may be NULL) */
  856. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  857. the <column-list> is stored here */
  858. int foreach; /* One of TK_ROW or TK_STATEMENT */
  859. Token nameToken; /* Token containing zName. Use during parsing only */
  860. TriggerStep *step_list; /* Link list of trigger program steps */
  861. Trigger *pNext; /* Next trigger associated with the table */
  862. };
  863. /*
  864. * An instance of struct TriggerStep is used to store a single SQL statement
  865. * that is a part of a trigger-program.
  866. *
  867. * Instances of struct TriggerStep are stored in a singly linked list (linked
  868. * using the "pNext" member) referenced by the "step_list" member of the
  869. * associated struct Trigger instance. The first element of the linked list is
  870. * the first step of the trigger-program.
  871. *
  872. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  873. * "SELECT" statement. The meanings of the other members is determined by the
  874. * value of "op" as follows:
  875. *
  876. * (op == TK_INSERT)
  877. * orconf -> stores the ON CONFLICT algorithm
  878. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  879. * this stores a pointer to the SELECT statement. Otherwise NULL.
  880. * target -> A token holding the name of the table to insert into.
  881. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  882. * this stores values to be inserted. Otherwise NULL.
  883. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  884. * statement, then this stores the column-names to be
  885. * inserted into.
  886. *
  887. * (op == TK_DELETE)
  888. * target -> A token holding the name of the table to delete from.
  889. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  890. * Otherwise NULL.
  891. *
  892. * (op == TK_UPDATE)
  893. * target -> A token holding the name of the table to update rows of.
  894. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  895. * Otherwise NULL.
  896. * pExprList -> A list of the columns to update and the expressions to update
  897. * them to. See sqliteUpdate() documentation of "pChanges"
  898. * argument.
  899. *
  900. */
  901. struct TriggerStep {
  902. int op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  903. int orconf; /* OE_Rollback etc. */
  904. Trigger *pTrig; /* The trigger that this step is a part of */
  905. Select *pSelect; /* Valid for SELECT and sometimes
  906. INSERT steps (when pExprList == 0) */
  907. Token target; /* Valid for DELETE, UPDATE, INSERT steps */
  908. Expr *pWhere; /* Valid for DELETE, UPDATE steps */
  909. ExprList *pExprList; /* Valid for UPDATE statements and sometimes
  910. INSERT steps (when pSelect == 0) */
  911. IdList *pIdList; /* Valid for INSERT statements only */
  912. TriggerStep * pNext; /* Next in the link-list */
  913. };
  914. /*
  915. * An instance of struct TriggerStack stores information required during code
  916. * generation of a single trigger program. While the trigger program is being
  917. * coded, its associated TriggerStack instance is pointed to by the
  918. * "pTriggerStack" member of the Parse structure.
  919. *
  920. * The pTab member points to the table that triggers are being coded on. The
  921. * newIdx member contains the index of the vdbe cursor that points at the temp
  922. * table that stores the new.* references. If new.* references are not valid
  923. * for the trigger being coded (for example an ON DELETE trigger), then newIdx
  924. * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
  925. *
  926. * The ON CONFLICT policy to be used for the trigger program steps is stored
  927. * as the orconf member. If this is OE_Default, then the ON CONFLICT clause
  928. * specified for individual triggers steps is used.
  929. *
  930. * struct TriggerStack has a "pNext" member, to allow linked lists to be
  931. * constructed. When coding nested triggers (triggers fired by other triggers)
  932. * each nested trigger stores its parent trigger's TriggerStack as the "pNext"
  933. * pointer. Once the nested trigger has been coded, the pNext value is restored
  934. * to the pTriggerStack member of the Parse stucture and coding of the parent
  935. * trigger continues.
  936. *
  937. * Before a nested trigger is coded, the linked list pointed to by the
  938. * pTriggerStack is scanned to ensure that the trigger is not about to be coded
  939. * recursively. If this condition is detected, the nested trigger is not coded.
  940. */
  941. struct TriggerStack {
  942. Table *pTab; /* Table that triggers are currently being coded on */
  943. int newIdx; /* Index of vdbe cursor to "new" temp table */
  944. int oldIdx; /* Index of vdbe cursor to "old" temp table */
  945. int orconf; /* Current orconf policy */
  946. int ignoreJump; /* where to jump to for a RAISE(IGNORE) */
  947. Trigger *pTrigger; /* The trigger currently being coded */
  948. TriggerStack *pNext; /* Next trigger down on the trigger stack */
  949. };
  950. /*
  951. ** The following structure contains information used by the sqliteFix...
  952. ** routines as they walk the parse tree to make database references
  953. ** explicit.
  954. */
  955. typedef struct DbFixer DbFixer;
  956. struct DbFixer {
  957. Parse *pParse; /* The parsing context. Error messages written here */
  958. const char *zDb; /* Make sure all objects are contained in this database */
  959. const char *zType; /* Type of the container - used for error messages */
  960. const Token *pName; /* Name of the container - used for error messages */
  961. };
  962. /*
  963. * This global flag is set for performance testing of triggers. When it is set
  964. * SQLite will perform the overhead of building new and old trigger references
  965. * even when no triggers exist
  966. */
  967. extern int always_code_trigger_setup;
  968. /*
  969. ** Internal function prototypes
  970. */
  971. int sqliteStrICmp(const char *, const char *);
  972. int sqliteStrNICmp(const char *, const char *, int);
  973. int sqliteHashNoCase(const char *, int);
  974. int sqliteIsNumber(const char*);
  975. int sqliteCompare(const char *, const char *);
  976. int sqliteSortCompare(const char *, const char *);
  977. void sqliteRealToSortable(double r, char *);
  978. #ifdef MEMORY_DEBUG
  979. void *sqliteMalloc_(int,int,char*,int);
  980. void sqliteFree_(void*,char*,int);
  981. void *sqliteRealloc_(void*,int,char*,int);
  982. char *sqliteStrDup_(const char*,char*,int);
  983. char *sqliteStrNDup_(const char*, int,char*,int);
  984. void sqliteCheckMemory(void*,int);
  985. #else
  986. void *sqliteMalloc(int);
  987. void *sqliteMallocRaw(int);
  988. void sqliteFree(void*);
  989. void *sqliteRealloc(void*,int);
  990. char *sqliteStrDup(const char*);
  991. char *sqliteStrNDup(const char*, int);
  992. # define sqliteCheckMemory(a,b)
  993. #endif
  994. char *sqliteMPrintf(const char *,...);
  995. void sqliteSetString(char **, const char *, ...);
  996. void sqliteSetNString(char **, ...);
  997. void sqliteErrorMsg(Parse*, const char*, ...);
  998. void sqliteDequote(char*);
  999. int sqliteKeywordCode(const char*, int);
  1000. int sqliteRunParser(Parse*, const char*, char **);
  1001. void sqliteExec(Parse*);
  1002. Expr *sqliteExpr(int, Expr*, Expr*, Token*);
  1003. void sqliteExprSpan(Expr*,Token*,Token*);
  1004. Expr *sqliteExprFunction(ExprList*, Token*);
  1005. void sqliteExprDelete(Expr*);
  1006. ExprList *sqliteExprListAppend(ExprList*,Expr*,Token*);
  1007. void sqliteExprListDelete(ExprList*);
  1008. int sqliteInit(sqlite*, char**);
  1009. void sqlitePragma(Parse*,Token*,Token*,int);
  1010. void sqliteResetInternalSchema(sqlite*, int);
  1011. void sqliteBeginParse(Parse*,int);
  1012. void sqliteRollbackInternalChanges(sqlite*);
  1013. void sqliteCommitInternalChanges(sqlite*);
  1014. Table *sqliteResultSetOfSelect(Parse*,char*,Select*);
  1015. void sqliteOpenMasterTable(Vdbe *v, int);
  1016. void sqliteStartTable(Parse*,Token*,Token*,int,int);
  1017. void sqliteAddColumn(Parse*,Token*);
  1018. void sqliteAddNotNull(Parse*, int);
  1019. void sqliteAddPrimaryKey(Parse*, IdList*, int);
  1020. void sqliteAddColumnType(Parse*,Token*,Token*);
  1021. void sqliteAddDefaultValue(Parse*,Token*,int);
  1022. int sqliteCollateType(const char*, int);
  1023. void sqliteAddCollateType(Parse*, int);
  1024. void sqliteEndTable(Parse*,Token*,Select*);
  1025. void sqliteCreateView(Parse*,Token*,Token*,Select*,int);
  1026. int sqliteViewGetColumnNames(Parse*,Table*);
  1027. void sqliteDropTable(Parse*, Token*, int);
  1028. void sqliteDeleteTable(sqlite*, Table*);
  1029. void sqliteInsert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
  1030. IdList *sqliteIdListAppend(IdList*, Token*);
  1031. int sqliteIdListIndex(IdList*,const char*);
  1032. SrcList *sqliteSrcListAppend(SrcList*, Token*, Token*);
  1033. void sqliteSrcListAddAlias(SrcList*, Token*);
  1034. void sqliteSrcListAssignCursors(Parse*, SrcList*);
  1035. void sqliteIdListDelete(IdList*);
  1036. void sqliteSrcListDelete(SrcList*);
  1037. void sqliteCreateIndex(Parse*,Token*,SrcList*,IdList*,int,int,Token*,Token*);
  1038. void sqliteDropIndex(Parse*, SrcList*);
  1039. void sqliteAddKeyType(Vdbe*, ExprList*);
  1040. void sqliteAddIdxKeyType(Vdbe*, Index*);
  1041. int sqliteSelect(Parse*, Select*, int, int, Select*, int, int*);
  1042. Select *sqliteSelectNew(ExprList*,SrcList*,Expr*,ExprList*,Expr*,ExprList*,
  1043. int,int,int);
  1044. void sqliteSelectDelete(Select*);
  1045. void sqliteSelectUnbind(Select*);
  1046. Table *sqliteSrcListLookup(Parse*, SrcList*);
  1047. int sqliteIsReadOnly(Parse*, Table*, int);
  1048. void sqliteDeleteFrom(Parse*, SrcList*, Expr*);
  1049. void sqliteUpdate(Parse*, SrcList*, ExprList*, Expr*, int);
  1050. WhereInfo *sqliteWhereBegin(Parse*, SrcList*, Expr*, int, ExprList**);
  1051. void sqliteWhereEnd(WhereInfo*);
  1052. void sqliteExprCode(Parse*, Expr*);
  1053. void sqliteExprIfTrue(Parse*, Expr*, int, int);
  1054. void sqliteExprIfFalse(Parse*, Expr*, int, int);
  1055. Table *sqliteFindTable(sqlite*,const char*, const char*);
  1056. Table *sqliteLocateTable(Parse*,const char*, const char*);
  1057. Index *sqliteFindIndex(sqlite*,const char*, const char*);
  1058. void sqliteUnlinkAndDeleteIndex(sqlite*,Index*);
  1059. void sqliteCopy(Parse*, SrcList*, Token*, Token*, int);
  1060. void sqliteVacuum(Parse*, Token*);
  1061. int sqliteGlobCompare(const unsigned char*,const unsigned char*);
  1062. int sqliteLikeCompare(const unsigned char*,const unsigned char*);
  1063. char *sqliteTableNameFromToken(Token*);
  1064. int sqliteExprCheck(Parse*, Expr*, int, int*);
  1065. int sqliteExprType(Expr*);
  1066. int sqliteExprCompare(Expr*, Expr*);
  1067. int sqliteFuncId(Token*);
  1068. int sqliteExprResolveIds(Parse*, SrcList*, ExprList*, Expr*);
  1069. int sqliteExprAnalyzeAggregates(Parse*, Expr*);
  1070. Vdbe *sqliteGetVdbe(Parse*);
  1071. int sqliteRandomByte(void);
  1072. int sqliteRandomInteger(void);
  1073. void sqliteRollbackAll(sqlite*);
  1074. void sqliteCodeVerifySchema(Parse*, int);
  1075. void sqliteBeginTransaction(Parse*, int);
  1076. void sqliteCommitTransaction(Parse*);
  1077. void sqliteRollbackTransaction(Parse*);
  1078. int sqliteExprIsConstant(Expr*);
  1079. int sqliteExprIsInteger(Expr*, int*);
  1080. int sqliteIsRowid(const char*);
  1081. void sqliteGenerateRowDelete(sqlite*, Vdbe*, Table*, int, int);
  1082. void sqliteGenerateRowIndexDelete(sqlite*, Vdbe*, Table*, int, char*);
  1083. void sqliteGenerateConstraintChecks(Parse*,Table*,int,char*,int,int,int,int);
  1084. void sqliteCompleteInsertion(Parse*, Table*, int, char*, int, int, int);
  1085. void sqliteBeginWriteOperation(Parse*, int, int);
  1086. void sqliteEndWriteOperation(Parse*);
  1087. Expr *sqliteExprDup(Expr*);
  1088. void sqliteTokenCopy(Token*, Token*);
  1089. ExprList *sqliteExprListDup(ExprList*);
  1090. SrcList *sqliteSrcListDup(SrcList*);
  1091. IdList *sqliteIdListDup(IdList*);
  1092. Select *sqliteSelectDup(Select*);
  1093. FuncDef *sqliteFindFunction(sqlite*,const char*,int,int,int);
  1094. void sqliteRegisterBuiltinFunctions(sqlite*);
  1095. int sqliteSafetyOn(sqlite*);
  1096. int sqliteSafetyOff(sqlite*);
  1097. int sqliteSafetyCheck(sqlite*);
  1098. void sqliteChangeCookie(sqlite*, Vdbe*);
  1099. void sqliteBeginTrigger(Parse*, Token*,int,int,IdList*,SrcList*,int,Expr*,int);
  1100. void sqliteFinishTrigger(Parse*, TriggerStep*, Token*);
  1101. void sqliteDropTrigger(Parse*, SrcList*);
  1102. void sqliteDropTriggerPtr(Parse*, Trigger*, int);
  1103. int sqliteTriggersExist(Parse* , Trigger* , int , int , int, ExprList*);
  1104. int sqliteCodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int,
  1105. int, int);
  1106. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  1107. void sqliteDeleteTriggerStep(TriggerStep*);
  1108. TriggerStep *sqliteTriggerSelectStep(Select*);
  1109. TriggerStep *sqliteTriggerInsertStep(Token*, IdList*, ExprList*, Select*, int);
  1110. TriggerStep *sqliteTriggerUpdateStep(Token*, ExprList*, Expr*, int);
  1111. TriggerStep *sqliteTriggerDeleteStep(Token*, Expr*);
  1112. void sqliteDeleteTrigger(Trigger*);
  1113. int sqliteJoinType(Parse*, Token*, Token*, Token*);
  1114. void sqliteCreateForeignKey(Parse*, IdList*, Token*, IdList*, int);
  1115. void sqliteDeferForeignKey(Parse*, int);
  1116. #ifndef SQLITE_OMIT_AUTHORIZATION
  1117. void sqliteAuthRead(Parse*,Expr*,SrcList*);
  1118. int sqliteAuthCheck(Parse*,int, const char*, const char*, const char*);
  1119. void sqliteAuthContextPush(Parse*, AuthContext*, const char*);
  1120. void sqliteAuthContextPop(AuthContext*);
  1121. #else
  1122. # define sqliteAuthRead(a,b,c)
  1123. # define sqliteAuthCheck(a,b,c,d) SQLITE_OK
  1124. # define sqliteAuthContextPush(a,b,c)
  1125. # define sqliteAuthContextPop(a)
  1126. #endif
  1127. void sqliteAttach(Parse*, Token*, Token*);
  1128. void sqliteDetach(Parse*, Token*);
  1129. int sqliteBtreeFactory(const sqlite *db, const char *zFilename,
  1130. int mode, int nPg, Btree **ppBtree);
  1131. int sqliteFixInit(DbFixer*, Parse*, int, const char*, const Token*);
  1132. int sqliteFixSrcList(DbFixer*, SrcList*);
  1133. int sqliteFixSelect(DbFixer*, Select*);
  1134. int sqliteFixExpr(DbFixer*, Expr*);
  1135. int sqliteFixExprList(DbFixer*, ExprList*);
  1136. int sqliteFixTriggerStep(DbFixer*, TriggerStep*);