comparison sqlite/sqliteInt.h @ 1434:b6b61becdf4e trunk

[svn] - add sqlite/ directory
author nenolod
date Thu, 27 Jul 2006 22:41:31 -0700
parents
children c3b203d258a7
comparison
equal deleted inserted replaced
1433:3cbe3d14ea68 1434:b6b61becdf4e
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.494 2006/05/25 12:17:31 drh Exp $
15 */
16 #ifndef _SQLITEINT_H_
17 #define _SQLITEINT_H_
18
19 #include "sqlite.h"
20
21 /*
22 ** Extra interface definitions for those who need them
23 */
24 #ifdef SQLITE_EXTRA
25 # include "sqliteExtra.h"
26 #endif
27
28 /*
29 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
30 ** Setting NDEBUG makes the code smaller and run faster. So the following
31 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
32 ** option is set. Thus NDEBUG becomes an opt-in rather than an opt-out
33 ** feature.
34 */
35 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
36 # define NDEBUG 1
37 #endif
38
39 /*
40 ** These #defines should enable >2GB file support on Posix if the
41 ** underlying operating system supports it. If the OS lacks
42 ** large file support, or if the OS is windows, these should be no-ops.
43 **
44 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
45 ** on the compiler command line. This is necessary if you are compiling
46 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
47 ** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
48 ** without this option, LFS is enable. But LFS does not exist in the kernel
49 ** in RedHat 6.0, so the code won't work. Hence, for maximum binary
50 ** portability you should omit LFS.
51 **
52 ** Similar is true for MacOS. LFS is only supported on MacOS 9 and later.
53 */
54 #ifndef SQLITE_DISABLE_LFS
55 # define _LARGE_FILE 1
56 # ifndef _FILE_OFFSET_BITS
57 # define _FILE_OFFSET_BITS 64
58 # endif
59 # define _LARGEFILE_SOURCE 1
60 #endif
61
62 #include "sqlite3.h"
63 #include "hash.h"
64 #include "parse.h"
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <assert.h>
69 #include <stddef.h>
70
71 /*
72 ** If compiling for a processor that lacks floating point support,
73 ** substitute integer for floating-point
74 */
75 #ifdef SQLITE_OMIT_FLOATING_POINT
76 # define double sqlite_int64
77 # define LONGDOUBLE_TYPE sqlite_int64
78 # ifndef SQLITE_BIG_DBL
79 # define SQLITE_BIG_DBL (0x7fffffffffffffff)
80 # endif
81 # define SQLITE_OMIT_DATETIME_FUNCS 1
82 # define SQLITE_OMIT_TRACE 1
83 #endif
84 #ifndef SQLITE_BIG_DBL
85 # define SQLITE_BIG_DBL (1e99)
86 #endif
87
88 /*
89 ** The maximum number of in-memory pages to use for the main database
90 ** table and for temporary tables. Internally, the MAX_PAGES and
91 ** TEMP_PAGES macros are used. To override the default values at
92 ** compilation time, the SQLITE_DEFAULT_CACHE_SIZE and
93 ** SQLITE_DEFAULT_TEMP_CACHE_SIZE macros should be set.
94 */
95 #ifdef SQLITE_DEFAULT_CACHE_SIZE
96 # define MAX_PAGES SQLITE_DEFAULT_CACHE_SIZE
97 #else
98 # define MAX_PAGES 2000
99 #endif
100 #ifdef SQLITE_DEFAULT_TEMP_CACHE_SIZE
101 # define TEMP_PAGES SQLITE_DEFAULT_TEMP_CACHE_SIZE
102 #else
103 # define TEMP_PAGES 500
104 #endif
105
106 /*
107 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
108 ** afterward. Having this macro allows us to cause the C compiler
109 ** to omit code used by TEMP tables without messy #ifndef statements.
110 */
111 #ifdef SQLITE_OMIT_TEMPDB
112 #define OMIT_TEMPDB 1
113 #else
114 #define OMIT_TEMPDB 0
115 #endif
116
117 /*
118 ** If the following macro is set to 1, then NULL values are considered
119 ** distinct when determining whether or not two entries are the same
120 ** in a UNIQUE index. This is the way PostgreSQL, Oracle, DB2, MySQL,
121 ** OCELOT, and Firebird all work. The SQL92 spec explicitly says this
122 ** is the way things are suppose to work.
123 **
124 ** If the following macro is set to 0, the NULLs are indistinct for
125 ** a UNIQUE index. In this mode, you can only have a single NULL entry
126 ** for a column declared UNIQUE. This is the way Informix and SQL Server
127 ** work.
128 */
129 #define NULL_DISTINCT_FOR_UNIQUE 1
130
131 /*
132 ** The maximum number of attached databases. This must be at least 2
133 ** in order to support the main database file (0) and the file used to
134 ** hold temporary tables (1). And it must be less than 32 because
135 ** we use a bitmask of databases with a u32 in places (for example
136 ** the Parse.cookieMask field).
137 */
138 #define MAX_ATTACHED 10
139
140 /*
141 ** The maximum value of a ?nnn wildcard that the parser will accept.
142 */
143 #define SQLITE_MAX_VARIABLE_NUMBER 999
144
145 /*
146 ** The "file format" number is an integer that is incremented whenever
147 ** the VDBE-level file format changes. The following macros define the
148 ** the default file format for new databases and the maximum file format
149 ** that the library can read.
150 */
151 #define SQLITE_MAX_FILE_FORMAT 4
152 #ifndef SQLITE_DEFAULT_FILE_FORMAT
153 # define SQLITE_DEFAULT_FILE_FORMAT 4
154 #endif
155
156 /*
157 ** Provide a default value for TEMP_STORE in case it is not specified
158 ** on the command-line
159 */
160 #ifndef TEMP_STORE
161 # define TEMP_STORE 1
162 #endif
163
164 /*
165 ** GCC does not define the offsetof() macro so we'll have to do it
166 ** ourselves.
167 */
168 #ifndef offsetof
169 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
170 #endif
171
172 /*
173 ** Check to see if this machine uses EBCDIC. (Yes, believe it or
174 ** not, there are still machines out there that use EBCDIC.)
175 */
176 #if 'A' == '\301'
177 # define SQLITE_EBCDIC 1
178 #else
179 # define SQLITE_ASCII 1
180 #endif
181
182 /*
183 ** Integers of known sizes. These typedefs might change for architectures
184 ** where the sizes very. Preprocessor macros are available so that the
185 ** types can be conveniently redefined at compile-type. Like this:
186 **
187 ** cc '-DUINTPTR_TYPE=long long int' ...
188 */
189 #ifndef UINT32_TYPE
190 # define UINT32_TYPE unsigned int
191 #endif
192 #ifndef UINT16_TYPE
193 # define UINT16_TYPE unsigned short int
194 #endif
195 #ifndef INT16_TYPE
196 # define INT16_TYPE short int
197 #endif
198 #ifndef UINT8_TYPE
199 # define UINT8_TYPE unsigned char
200 #endif
201 #ifndef INT8_TYPE
202 # define INT8_TYPE signed char
203 #endif
204 #ifndef LONGDOUBLE_TYPE
205 # define LONGDOUBLE_TYPE long double
206 #endif
207 typedef sqlite_int64 i64; /* 8-byte signed integer */
208 typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
209 typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
210 typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
211 typedef INT16_TYPE i16; /* 2-byte signed integer */
212 typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
213 typedef UINT8_TYPE i8; /* 1-byte signed integer */
214
215 /*
216 ** Macros to determine whether the machine is big or little endian,
217 ** evaluated at runtime.
218 */
219 extern const int sqlite3one;
220 #define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
221 #define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
222
223 /*
224 ** An instance of the following structure is used to store the busy-handler
225 ** callback for a given sqlite handle.
226 **
227 ** The sqlite.busyHandler member of the sqlite struct contains the busy
228 ** callback for the database handle. Each pager opened via the sqlite
229 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
230 ** callback is currently invoked only from within pager.c.
231 */
232 typedef struct BusyHandler BusyHandler;
233 struct BusyHandler {
234 int (*xFunc)(void *,int); /* The busy callback */
235 void *pArg; /* First arg to busy callback */
236 int nBusy; /* Incremented with each busy call */
237 };
238
239 /*
240 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
241 ** "BusyHandler typedefs.
242 */
243 #include "vdbe.h"
244 #include "btree.h"
245 #include "pager.h"
246
247 #ifdef SQLITE_MEMDEBUG
248 /*
249 ** The following global variables are used for testing and debugging
250 ** only. They only work if SQLITE_MEMDEBUG is defined.
251 */
252 extern int sqlite3_nMalloc; /* Number of sqliteMalloc() calls */
253 extern int sqlite3_nFree; /* Number of sqliteFree() calls */
254 extern int sqlite3_iMallocFail; /* Fail sqliteMalloc() after this many calls */
255 extern int sqlite3_iMallocReset; /* Set iMallocFail to this when it reaches 0 */
256
257 extern void *sqlite3_pFirst; /* Pointer to linked list of allocations */
258 extern int sqlite3_nMaxAlloc; /* High water mark of ThreadData.nAlloc */
259 extern int sqlite3_mallocDisallowed; /* assert() in sqlite3Malloc() if set */
260 extern int sqlite3_isFail; /* True if all malloc calls should fail */
261 extern const char *sqlite3_zFile; /* Filename to associate debug info with */
262 extern int sqlite3_iLine; /* Line number for debug info */
263
264 #define ENTER_MALLOC (sqlite3_zFile = __FILE__, sqlite3_iLine = __LINE__)
265 #define sqliteMalloc(x) (ENTER_MALLOC, sqlite3Malloc(x,1))
266 #define sqliteMallocRaw(x) (ENTER_MALLOC, sqlite3MallocRaw(x,1))
267 #define sqliteRealloc(x,y) (ENTER_MALLOC, sqlite3Realloc(x,y))
268 #define sqliteStrDup(x) (ENTER_MALLOC, sqlite3StrDup(x))
269 #define sqliteStrNDup(x,y) (ENTER_MALLOC, sqlite3StrNDup(x,y))
270 #define sqliteReallocOrFree(x,y) (ENTER_MALLOC, sqlite3ReallocOrFree(x,y))
271
272 #else
273
274 #define ENTER_MALLOC 0
275 #define sqliteMalloc(x) sqlite3Malloc(x,1)
276 #define sqliteMallocRaw(x) sqlite3MallocRaw(x,1)
277 #define sqliteRealloc(x,y) sqlite3Realloc(x,y)
278 #define sqliteStrDup(x) sqlite3StrDup(x)
279 #define sqliteStrNDup(x,y) sqlite3StrNDup(x,y)
280 #define sqliteReallocOrFree(x,y) sqlite3ReallocOrFree(x,y)
281
282 #endif
283
284 #define sqliteFree(x) sqlite3FreeX(x)
285 #define sqliteAllocSize(x) sqlite3AllocSize(x)
286
287
288 /*
289 ** An instance of this structure might be allocated to store information
290 ** specific to a single thread.
291 */
292 struct ThreadData {
293 int dummy; /* So that this structure is never empty */
294
295 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
296 int nSoftHeapLimit; /* Suggested max mem allocation. No limit if <0 */
297 int nAlloc; /* Number of bytes currently allocated */
298 Pager *pPager; /* Linked list of all pagers in this thread */
299 #endif
300
301 #ifndef SQLITE_OMIT_SHARED_CACHE
302 u8 useSharedData; /* True if shared pagers and schemas are enabled */
303 BtShared *pBtree; /* Linked list of all currently open BTrees */
304 #endif
305 };
306
307 /*
308 ** Name of the master database table. The master database table
309 ** is a special table that holds the names and attributes of all
310 ** user tables and indices.
311 */
312 #define MASTER_NAME "sqlite_master"
313 #define TEMP_MASTER_NAME "sqlite_temp_master"
314
315 /*
316 ** The root-page of the master database table.
317 */
318 #define MASTER_ROOT 1
319
320 /*
321 ** The name of the schema table.
322 */
323 #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
324
325 /*
326 ** A convenience macro that returns the number of elements in
327 ** an array.
328 */
329 #define ArraySize(X) (sizeof(X)/sizeof(X[0]))
330
331 /*
332 ** Forward references to structures
333 */
334 typedef struct AggInfo AggInfo;
335 typedef struct AuthContext AuthContext;
336 typedef struct CollSeq CollSeq;
337 typedef struct Column Column;
338 typedef struct Db Db;
339 typedef struct Schema Schema;
340 typedef struct Expr Expr;
341 typedef struct ExprList ExprList;
342 typedef struct FKey FKey;
343 typedef struct FuncDef FuncDef;
344 typedef struct IdList IdList;
345 typedef struct Index Index;
346 typedef struct KeyClass KeyClass;
347 typedef struct KeyInfo KeyInfo;
348 typedef struct NameContext NameContext;
349 typedef struct Parse Parse;
350 typedef struct Select Select;
351 typedef struct SrcList SrcList;
352 typedef struct ThreadData ThreadData;
353 typedef struct Table Table;
354 typedef struct TableLock TableLock;
355 typedef struct Token Token;
356 typedef struct TriggerStack TriggerStack;
357 typedef struct TriggerStep TriggerStep;
358 typedef struct Trigger Trigger;
359 typedef struct WhereInfo WhereInfo;
360 typedef struct WhereLevel WhereLevel;
361
362 /*
363 ** Each database file to be accessed by the system is an instance
364 ** of the following structure. There are normally two of these structures
365 ** in the sqlite.aDb[] array. aDb[0] is the main database file and
366 ** aDb[1] is the database file used to hold temporary tables. Additional
367 ** databases may be attached.
368 */
369 struct Db {
370 char *zName; /* Name of this database */
371 Btree *pBt; /* The B*Tree structure for this database file */
372 u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */
373 u8 safety_level; /* How aggressive at synching data to disk */
374 void *pAux; /* Auxiliary data. Usually NULL */
375 void (*xFreeAux)(void*); /* Routine to free pAux */
376 Schema *pSchema; /* Pointer to database schema (possibly shared) */
377 };
378
379 /*
380 ** An instance of the following structure stores a database schema.
381 */
382 struct Schema {
383 int schema_cookie; /* Database schema version number for this file */
384 Hash tblHash; /* All tables indexed by name */
385 Hash idxHash; /* All (named) indices indexed by name */
386 Hash trigHash; /* All triggers indexed by name */
387 Hash aFKey; /* Foreign keys indexed by to-table */
388 Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
389 u8 file_format; /* Schema format version for this file */
390 u8 enc; /* Text encoding used by this database */
391 u16 flags; /* Flags associated with this schema */
392 int cache_size; /* Number of pages to use in the cache */
393 };
394
395 /*
396 ** These macros can be used to test, set, or clear bits in the
397 ** Db.flags field.
398 */
399 #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P))
400 #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0)
401 #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P)
402 #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P)
403
404 /*
405 ** Allowed values for the DB.flags field.
406 **
407 ** The DB_SchemaLoaded flag is set after the database schema has been
408 ** read into internal hash tables.
409 **
410 ** DB_UnresetViews means that one or more views have column names that
411 ** have been filled out. If the schema changes, these column names might
412 ** changes and so the view will need to be reset.
413 */
414 #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
415 #define DB_UnresetViews 0x0002 /* Some views have defined column names */
416 #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
417
418 #define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
419
420 /*
421 ** Each database is an instance of the following structure.
422 **
423 ** The sqlite.lastRowid records the last insert rowid generated by an
424 ** insert statement. Inserts on views do not affect its value. Each
425 ** trigger has its own context, so that lastRowid can be updated inside
426 ** triggers as usual. The previous value will be restored once the trigger
427 ** exits. Upon entering a before or instead of trigger, lastRowid is no
428 ** longer (since after version 2.8.12) reset to -1.
429 **
430 ** The sqlite.nChange does not count changes within triggers and keeps no
431 ** context. It is reset at start of sqlite3_exec.
432 ** The sqlite.lsChange represents the number of changes made by the last
433 ** insert, update, or delete statement. It remains constant throughout the
434 ** length of a statement and is then updated by OP_SetCounts. It keeps a
435 ** context stack just like lastRowid so that the count of changes
436 ** within a trigger is not seen outside the trigger. Changes to views do not
437 ** affect the value of lsChange.
438 ** The sqlite.csChange keeps track of the number of current changes (since
439 ** the last statement) and is used to update sqlite_lsChange.
440 **
441 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
442 ** store the most recent error code and, if applicable, string. The
443 ** internal function sqlite3Error() is used to set these variables
444 ** consistently.
445 */
446 struct sqlite3 {
447 int nDb; /* Number of backends currently in use */
448 Db *aDb; /* All backends */
449 int flags; /* Miscellanous flags. See below */
450 int errCode; /* Most recent error code (SQLITE_*) */
451 u8 autoCommit; /* The auto-commit flag. */
452 u8 temp_store; /* 1: file 2: memory 0: default */
453 int nTable; /* Number of tables in the database */
454 CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
455 i64 lastRowid; /* ROWID of most recent insert (see above) */
456 i64 priorNewRowid; /* Last randomly generated ROWID */
457 int magic; /* Magic number for detect library misuse */
458 int nChange; /* Value returned by sqlite3_changes() */
459 int nTotalChange; /* Value returned by sqlite3_total_changes() */
460 struct sqlite3InitInfo { /* Information used during initialization */
461 int iDb; /* When back is being initialized */
462 int newTnum; /* Rootpage of table being initialized */
463 u8 busy; /* TRUE if currently initializing */
464 } init;
465 struct Vdbe *pVdbe; /* List of active virtual machines */
466 int activeVdbeCnt; /* Number of vdbes currently executing */
467 void (*xTrace)(void*,const char*); /* Trace function */
468 void *pTraceArg; /* Argument to the trace function */
469 void (*xProfile)(void*,const char*,u64); /* Profiling function */
470 void *pProfileArg; /* Argument to profile function */
471 void *pCommitArg; /* Argument to xCommitCallback() */
472 int (*xCommitCallback)(void*); /* Invoked at every commit. */
473 void *pRollbackArg; /* Argument to xRollbackCallback() */
474 void (*xRollbackCallback)(void*); /* Invoked at every commit. */
475 void *pUpdateArg;
476 void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
477 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
478 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
479 void *pCollNeededArg;
480 sqlite3_value *pErr; /* Most recent error message */
481 char *zErrMsg; /* Most recent error message (UTF-8 encoded) */
482 char *zErrMsg16; /* Most recent error message (UTF-16 encoded) */
483 #ifndef SQLITE_OMIT_AUTHORIZATION
484 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
485 /* Access authorization function */
486 void *pAuthArg; /* 1st argument to the access auth function */
487 #endif
488 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
489 int (*xProgress)(void *); /* The progress callback */
490 void *pProgressArg; /* Argument to the progress callback */
491 int nProgressOps; /* Number of opcodes for progress callback */
492 #endif
493 #ifndef SQLITE_OMIT_GLOBALRECOVER
494 sqlite3 *pNext; /* Linked list of open db handles. */
495 #endif
496 Hash aFunc; /* All functions that can be in SQL exprs */
497 Hash aCollSeq; /* All collating sequences */
498 BusyHandler busyHandler; /* Busy callback */
499 int busyTimeout; /* Busy handler timeout, in msec */
500 Db aDbStatic[2]; /* Static space for the 2 default backends */
501 #ifdef SQLITE_SSE
502 sqlite3_stmt *pFetch; /* Used by SSE to fetch stored statements */
503 #endif
504 };
505
506 /*
507 ** A macro to discover the encoding of a database.
508 */
509 #define ENC(db) ((db)->aDb[0].pSchema->enc)
510
511 /*
512 ** Possible values for the sqlite.flags and or Db.flags fields.
513 **
514 ** On sqlite.flags, the SQLITE_InTrans value means that we have
515 ** executed a BEGIN. On Db.flags, SQLITE_InTrans means a statement
516 ** transaction is active on that particular database file.
517 */
518 #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
519 #define SQLITE_Interrupt 0x00000004 /* Cancel current operation */
520 #define SQLITE_InTrans 0x00000008 /* True if in a transaction */
521 #define SQLITE_InternChanges 0x00000010 /* Uncommitted Hash table changes */
522 #define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
523 #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
524 #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
525 /* DELETE, or UPDATE and return */
526 /* the count using a callback. */
527 #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
528 /* result set is empty */
529 #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
530 #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
531 #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
532 #define SQLITE_NoReadlock 0x00001000 /* Readlocks are omitted when
533 ** accessing read-only databases */
534 #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
535 #define SQLITE_ReadUncommitted 0x00004000 /* For shared-cache mode */
536 #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
537 #define SQLITE_FullFSync 0x00010000 /* Use full fsync on the backend */
538
539 /*
540 ** Possible values for the sqlite.magic field.
541 ** The numbers are obtained at random and have no special meaning, other
542 ** than being distinct from one another.
543 */
544 #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
545 #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
546 #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
547 #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
548
549 /*
550 ** Each SQL function is defined by an instance of the following
551 ** structure. A pointer to this structure is stored in the sqlite.aFunc
552 ** hash table. When multiple functions have the same name, the hash table
553 ** points to a linked list of these structures.
554 */
555 struct FuncDef {
556 i16 nArg; /* Number of arguments. -1 means unlimited */
557 u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
558 u8 needCollSeq; /* True if sqlite3GetFuncCollSeq() might be called */
559 u8 flags; /* Some combination of SQLITE_FUNC_* */
560 void *pUserData; /* User data parameter */
561 FuncDef *pNext; /* Next function with same name */
562 void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
563 void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
564 void (*xFinalize)(sqlite3_context*); /* Aggregate finializer */
565 char zName[1]; /* SQL name of the function. MUST BE LAST */
566 };
567
568 /*
569 ** Possible values for FuncDef.flags
570 */
571 #define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */
572 #define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */
573
574 /*
575 ** information about each column of an SQL table is held in an instance
576 ** of this structure.
577 */
578 struct Column {
579 char *zName; /* Name of this column */
580 Expr *pDflt; /* Default value of this column */
581 char *zType; /* Data type for this column */
582 char *zColl; /* Collating sequence. If NULL, use the default */
583 u8 notNull; /* True if there is a NOT NULL constraint */
584 u8 isPrimKey; /* True if this column is part of the PRIMARY KEY */
585 char affinity; /* One of the SQLITE_AFF_... values */
586 };
587
588 /*
589 ** A "Collating Sequence" is defined by an instance of the following
590 ** structure. Conceptually, a collating sequence consists of a name and
591 ** a comparison routine that defines the order of that sequence.
592 **
593 ** There may two seperate implementations of the collation function, one
594 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
595 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
596 ** native byte order. When a collation sequence is invoked, SQLite selects
597 ** the version that will require the least expensive encoding
598 ** translations, if any.
599 **
600 ** The CollSeq.pUser member variable is an extra parameter that passed in
601 ** as the first argument to the UTF-8 comparison function, xCmp.
602 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
603 ** xCmp16.
604 **
605 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
606 ** collating sequence is undefined. Indices built on an undefined
607 ** collating sequence may not be read or written.
608 */
609 struct CollSeq {
610 char *zName; /* Name of the collating sequence, UTF-8 encoded */
611 u8 enc; /* Text encoding handled by xCmp() */
612 u8 type; /* One of the SQLITE_COLL_... values below */
613 void *pUser; /* First argument to xCmp() */
614 int (*xCmp)(void*,int, const void*, int, const void*);
615 };
616
617 /*
618 ** Allowed values of CollSeq flags:
619 */
620 #define SQLITE_COLL_BINARY 1 /* The default memcmp() collating sequence */
621 #define SQLITE_COLL_NOCASE 2 /* The built-in NOCASE collating sequence */
622 #define SQLITE_COLL_REVERSE 3 /* The built-in REVERSE collating sequence */
623 #define SQLITE_COLL_USER 0 /* Any other user-defined collating sequence */
624
625 /*
626 ** A sort order can be either ASC or DESC.
627 */
628 #define SQLITE_SO_ASC 0 /* Sort in ascending order */
629 #define SQLITE_SO_DESC 1 /* Sort in ascending order */
630
631 /*
632 ** Column affinity types.
633 **
634 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
635 ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
636 ** the speed a little by number the values consecutively.
637 **
638 ** But rather than start with 0 or 1, we begin with 'a'. That way,
639 ** when multiple affinity types are concatenated into a string and
640 ** used as the P3 operand, they will be more readable.
641 **
642 ** Note also that the numeric types are grouped together so that testing
643 ** for a numeric type is a single comparison.
644 */
645 #define SQLITE_AFF_TEXT 'a'
646 #define SQLITE_AFF_NONE 'b'
647 #define SQLITE_AFF_NUMERIC 'c'
648 #define SQLITE_AFF_INTEGER 'd'
649 #define SQLITE_AFF_REAL 'e'
650
651 #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
652
653 /*
654 ** Each SQL table is represented in memory by an instance of the
655 ** following structure.
656 **
657 ** Table.zName is the name of the table. The case of the original
658 ** CREATE TABLE statement is stored, but case is not significant for
659 ** comparisons.
660 **
661 ** Table.nCol is the number of columns in this table. Table.aCol is a
662 ** pointer to an array of Column structures, one for each column.
663 **
664 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
665 ** the column that is that key. Otherwise Table.iPKey is negative. Note
666 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
667 ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
668 ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
669 ** is generated for each row of the table. Table.hasPrimKey is true if
670 ** the table has any PRIMARY KEY, INTEGER or otherwise.
671 **
672 ** Table.tnum is the page number for the root BTree page of the table in the
673 ** database file. If Table.iDb is the index of the database table backend
674 ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
675 ** holds temporary tables and indices. If Table.isTransient
676 ** is true, then the table is stored in a file that is automatically deleted
677 ** when the VDBE cursor to the table is closed. In this case Table.tnum
678 ** refers VDBE cursor number that holds the table open, not to the root
679 ** page number. Transient tables are used to hold the results of a
680 ** sub-query that appears instead of a real table name in the FROM clause
681 ** of a SELECT statement.
682 */
683 struct Table {
684 char *zName; /* Name of the table */
685 int nCol; /* Number of columns in this table */
686 Column *aCol; /* Information about each column */
687 int iPKey; /* If not less then 0, use aCol[iPKey] as the primary key */
688 Index *pIndex; /* List of SQL indexes on this table. */
689 int tnum; /* Root BTree node for this table (see note above) */
690 Select *pSelect; /* NULL for tables. Points to definition if a view. */
691 u8 readOnly; /* True if this table should not be written by the user */
692 u8 isTransient; /* True if automatically deleted when VDBE finishes */
693 u8 hasPrimKey; /* True if there exists a primary key */
694 u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
695 u8 autoInc; /* True if the integer primary key is autoincrement */
696 int nRef; /* Number of pointers to this Table */
697 Trigger *pTrigger; /* List of SQL triggers on this table */
698 FKey *pFKey; /* Linked list of all foreign keys in this table */
699 char *zColAff; /* String defining the affinity of each column */
700 #ifndef SQLITE_OMIT_CHECK
701 Expr *pCheck; /* The AND of all CHECK constraints */
702 #endif
703 #ifndef SQLITE_OMIT_ALTERTABLE
704 int addColOffset; /* Offset in CREATE TABLE statement to add a new column */
705 #endif
706 Schema *pSchema;
707 };
708
709 /*
710 ** Each foreign key constraint is an instance of the following structure.
711 **
712 ** A foreign key is associated with two tables. The "from" table is
713 ** the table that contains the REFERENCES clause that creates the foreign
714 ** key. The "to" table is the table that is named in the REFERENCES clause.
715 ** Consider this example:
716 **
717 ** CREATE TABLE ex1(
718 ** a INTEGER PRIMARY KEY,
719 ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
720 ** );
721 **
722 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
723 **
724 ** Each REFERENCES clause generates an instance of the following structure
725 ** which is attached to the from-table. The to-table need not exist when
726 ** the from-table is created. The existance of the to-table is not checked
727 ** until an attempt is made to insert data into the from-table.
728 **
729 ** The sqlite.aFKey hash table stores pointers to this structure
730 ** given the name of a to-table. For each to-table, all foreign keys
731 ** associated with that table are on a linked list using the FKey.pNextTo
732 ** field.
733 */
734 struct FKey {
735 Table *pFrom; /* The table that constains the REFERENCES clause */
736 FKey *pNextFrom; /* Next foreign key in pFrom */
737 char *zTo; /* Name of table that the key points to */
738 FKey *pNextTo; /* Next foreign key that points to zTo */
739 int nCol; /* Number of columns in this key */
740 struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
741 int iFrom; /* Index of column in pFrom */
742 char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
743 } *aCol; /* One entry for each of nCol column s */
744 u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
745 u8 updateConf; /* How to resolve conflicts that occur on UPDATE */
746 u8 deleteConf; /* How to resolve conflicts that occur on DELETE */
747 u8 insertConf; /* How to resolve conflicts that occur on INSERT */
748 };
749
750 /*
751 ** SQLite supports many different ways to resolve a contraint
752 ** error. ROLLBACK processing means that a constraint violation
753 ** causes the operation in process to fail and for the current transaction
754 ** to be rolled back. ABORT processing means the operation in process
755 ** fails and any prior changes from that one operation are backed out,
756 ** but the transaction is not rolled back. FAIL processing means that
757 ** the operation in progress stops and returns an error code. But prior
758 ** changes due to the same operation are not backed out and no rollback
759 ** occurs. IGNORE means that the particular row that caused the constraint
760 ** error is not inserted or updated. Processing continues and no error
761 ** is returned. REPLACE means that preexisting database rows that caused
762 ** a UNIQUE constraint violation are removed so that the new insert or
763 ** update can proceed. Processing continues and no error is reported.
764 **
765 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
766 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
767 ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
768 ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
769 ** referenced table row is propagated into the row that holds the
770 ** foreign key.
771 **
772 ** The following symbolic values are used to record which type
773 ** of action to take.
774 */
775 #define OE_None 0 /* There is no constraint to check */
776 #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
777 #define OE_Abort 2 /* Back out changes but do no rollback transaction */
778 #define OE_Fail 3 /* Stop the operation but leave all prior changes */
779 #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
780 #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
781
782 #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
783 #define OE_SetNull 7 /* Set the foreign key value to NULL */
784 #define OE_SetDflt 8 /* Set the foreign key value to its default */
785 #define OE_Cascade 9 /* Cascade the changes */
786
787 #define OE_Default 99 /* Do whatever the default action is */
788
789
790 /*
791 ** An instance of the following structure is passed as the first
792 ** argument to sqlite3VdbeKeyCompare and is used to control the
793 ** comparison of the two index keys.
794 **
795 ** If the KeyInfo.incrKey value is true and the comparison would
796 ** otherwise be equal, then return a result as if the second key
797 ** were larger.
798 */
799 struct KeyInfo {
800 u8 enc; /* Text encoding - one of the TEXT_Utf* values */
801 u8 incrKey; /* Increase 2nd key by epsilon before comparison */
802 int nField; /* Number of entries in aColl[] */
803 u8 *aSortOrder; /* If defined an aSortOrder[i] is true, sort DESC */
804 CollSeq *aColl[1]; /* Collating sequence for each term of the key */
805 };
806
807 /*
808 ** Each SQL index is represented in memory by an
809 ** instance of the following structure.
810 **
811 ** The columns of the table that are to be indexed are described
812 ** by the aiColumn[] field of this structure. For example, suppose
813 ** we have the following table and index:
814 **
815 ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
816 ** CREATE INDEX Ex2 ON Ex1(c3,c1);
817 **
818 ** In the Table structure describing Ex1, nCol==3 because there are
819 ** three columns in the table. In the Index structure describing
820 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
821 ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
822 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
823 ** The second column to be indexed (c1) has an index of 0 in
824 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
825 **
826 ** The Index.onError field determines whether or not the indexed columns
827 ** must be unique and what to do if they are not. When Index.onError=OE_None,
828 ** it means this is not a unique index. Otherwise it is a unique index
829 ** and the value of Index.onError indicate the which conflict resolution
830 ** algorithm to employ whenever an attempt is made to insert a non-unique
831 ** element.
832 */
833 struct Index {
834 char *zName; /* Name of this index */
835 int nColumn; /* Number of columns in the table used by this index */
836 int *aiColumn; /* Which columns are used by this index. 1st is 0 */
837 unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
838 Table *pTable; /* The SQL table being indexed */
839 int tnum; /* Page containing root of this index in database file */
840 u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
841 u8 autoIndex; /* True if is automatically created (ex: by UNIQUE) */
842 char *zColAff; /* String defining the affinity of each column */
843 Index *pNext; /* The next index associated with the same table */
844 Schema *pSchema; /* Schema containing this index */
845 u8 *aSortOrder; /* Array of size Index.nColumn. True==DESC, False==ASC */
846 char **azColl; /* Array of collation sequence names for index */
847 };
848
849 /*
850 ** Each token coming out of the lexer is an instance of
851 ** this structure. Tokens are also used as part of an expression.
852 **
853 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
854 ** may contain random values. Do not make any assuptions about Token.dyn
855 ** and Token.n when Token.z==0.
856 */
857 struct Token {
858 const unsigned char *z; /* Text of the token. Not NULL-terminated! */
859 unsigned dyn : 1; /* True for malloced memory, false for static */
860 unsigned n : 31; /* Number of characters in this token */
861 };
862
863 /*
864 ** An instance of this structure contains information needed to generate
865 ** code for a SELECT that contains aggregate functions.
866 **
867 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
868 ** pointer to this structure. The Expr.iColumn field is the index in
869 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
870 ** code for that node.
871 **
872 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
873 ** original Select structure that describes the SELECT statement. These
874 ** fields do not need to be freed when deallocating the AggInfo structure.
875 */
876 struct AggInfo {
877 u8 directMode; /* Direct rendering mode means take data directly
878 ** from source tables rather than from accumulators */
879 u8 useSortingIdx; /* In direct mode, reference the sorting index rather
880 ** than the source table */
881 int sortingIdx; /* Cursor number of the sorting index */
882 ExprList *pGroupBy; /* The group by clause */
883 int nSortingColumn; /* Number of columns in the sorting index */
884 struct AggInfo_col { /* For each column used in source tables */
885 int iTable; /* Cursor number of the source table */
886 int iColumn; /* Column number within the source table */
887 int iSorterColumn; /* Column number in the sorting index */
888 int iMem; /* Memory location that acts as accumulator */
889 Expr *pExpr; /* The original expression */
890 } *aCol;
891 int nColumn; /* Number of used entries in aCol[] */
892 int nColumnAlloc; /* Number of slots allocated for aCol[] */
893 int nAccumulator; /* Number of columns that show through to the output.
894 ** Additional columns are used only as parameters to
895 ** aggregate functions */
896 struct AggInfo_func { /* For each aggregate function */
897 Expr *pExpr; /* Expression encoding the function */
898 FuncDef *pFunc; /* The aggregate function implementation */
899 int iMem; /* Memory location that acts as accumulator */
900 int iDistinct; /* Virtual table used to enforce DISTINCT */
901 } *aFunc;
902 int nFunc; /* Number of entries in aFunc[] */
903 int nFuncAlloc; /* Number of slots allocated for aFunc[] */
904 };
905
906 /*
907 ** Each node of an expression in the parse tree is an instance
908 ** of this structure.
909 **
910 ** Expr.op is the opcode. The integer parser token codes are reused
911 ** as opcodes here. For example, the parser defines TK_GE to be an integer
912 ** code representing the ">=" operator. This same integer code is reused
913 ** to represent the greater-than-or-equal-to operator in the expression
914 ** tree.
915 **
916 ** Expr.pRight and Expr.pLeft are subexpressions. Expr.pList is a list
917 ** of argument if the expression is a function.
918 **
919 ** Expr.token is the operator token for this node. For some expressions
920 ** that have subexpressions, Expr.token can be the complete text that gave
921 ** rise to the Expr. In the latter case, the token is marked as being
922 ** a compound token.
923 **
924 ** An expression of the form ID or ID.ID refers to a column in a table.
925 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
926 ** the integer cursor number of a VDBE cursor pointing to that table and
927 ** Expr.iColumn is the column number for the specific column. If the
928 ** expression is used as a result in an aggregate SELECT, then the
929 ** value is also stored in the Expr.iAgg column in the aggregate so that
930 ** it can be accessed after all aggregates are computed.
931 **
932 ** If the expression is a function, the Expr.iTable is an integer code
933 ** representing which function. If the expression is an unbound variable
934 ** marker (a question mark character '?' in the original SQL) then the
935 ** Expr.iTable holds the index number for that variable.
936 **
937 ** If the expression is a subquery then Expr.iColumn holds an integer
938 ** register number containing the result of the subquery. If the
939 ** subquery gives a constant result, then iTable is -1. If the subquery
940 ** gives a different answer at different times during statement processing
941 ** then iTable is the address of a subroutine that computes the subquery.
942 **
943 ** The Expr.pSelect field points to a SELECT statement. The SELECT might
944 ** be the right operand of an IN operator. Or, if a scalar SELECT appears
945 ** in an expression the opcode is TK_SELECT and Expr.pSelect is the only
946 ** operand.
947 **
948 ** If the Expr is of type OP_Column, and the table it is selecting from
949 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
950 ** corresponding table definition.
951 */
952 struct Expr {
953 u8 op; /* Operation performed by this node */
954 char affinity; /* The affinity of the column or 0 if not a column */
955 u8 flags; /* Various flags. See below */
956 CollSeq *pColl; /* The collation type of the column or 0 */
957 Expr *pLeft, *pRight; /* Left and right subnodes */
958 ExprList *pList; /* A list of expressions used as function arguments
959 ** or in "<expr> IN (<expr-list)" */
960 Token token; /* An operand token */
961 Token span; /* Complete text of the expression */
962 int iTable, iColumn; /* When op==TK_COLUMN, then this expr node means the
963 ** iColumn-th field of the iTable-th table. */
964 AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
965 int iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
966 int iRightJoinTable; /* If EP_FromJoin, the right table of the join */
967 Select *pSelect; /* When the expression is a sub-select. Also the
968 ** right side of "<expr> IN (<select>)" */
969 Table *pTab; /* Table for OP_Column expressions. */
970 Schema *pSchema;
971 };
972
973 /*
974 ** The following are the meanings of bits in the Expr.flags field.
975 */
976 #define EP_FromJoin 0x01 /* Originated in ON or USING clause of a join */
977 #define EP_Agg 0x02 /* Contains one or more aggregate functions */
978 #define EP_Resolved 0x04 /* IDs have been resolved to COLUMNs */
979 #define EP_Error 0x08 /* Expression contains one or more errors */
980 #define EP_Distinct 0x10 /* Aggregate function with DISTINCT keyword */
981 #define EP_VarSelect 0x20 /* pSelect is correlated, not constant */
982 #define EP_Dequoted 0x40 /* True if the string has been dequoted */
983
984 /*
985 ** These macros can be used to test, set, or clear bits in the
986 ** Expr.flags field.
987 */
988 #define ExprHasProperty(E,P) (((E)->flags&(P))==(P))
989 #define ExprHasAnyProperty(E,P) (((E)->flags&(P))!=0)
990 #define ExprSetProperty(E,P) (E)->flags|=(P)
991 #define ExprClearProperty(E,P) (E)->flags&=~(P)
992
993 /*
994 ** A list of expressions. Each expression may optionally have a
995 ** name. An expr/name combination can be used in several ways, such
996 ** as the list of "expr AS ID" fields following a "SELECT" or in the
997 ** list of "ID = expr" items in an UPDATE. A list of expressions can
998 ** also be used as the argument to a function, in which case the a.zName
999 ** field is not used.
1000 */
1001 struct ExprList {
1002 int nExpr; /* Number of expressions on the list */
1003 int nAlloc; /* Number of entries allocated below */
1004 int iECursor; /* VDBE Cursor associated with this ExprList */
1005 struct ExprList_item {
1006 Expr *pExpr; /* The list of expressions */
1007 char *zName; /* Token associated with this expression */
1008 u8 sortOrder; /* 1 for DESC or 0 for ASC */
1009 u8 isAgg; /* True if this is an aggregate like count(*) */
1010 u8 done; /* A flag to indicate when processing is finished */
1011 } *a; /* One entry for each expression */
1012 };
1013
1014 /*
1015 ** An instance of this structure can hold a simple list of identifiers,
1016 ** such as the list "a,b,c" in the following statements:
1017 **
1018 ** INSERT INTO t(a,b,c) VALUES ...;
1019 ** CREATE INDEX idx ON t(a,b,c);
1020 ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
1021 **
1022 ** The IdList.a.idx field is used when the IdList represents the list of
1023 ** column names after a table name in an INSERT statement. In the statement
1024 **
1025 ** INSERT INTO t(a,b,c) ...
1026 **
1027 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
1028 */
1029 struct IdList {
1030 struct IdList_item {
1031 char *zName; /* Name of the identifier */
1032 int idx; /* Index in some Table.aCol[] of a column named zName */
1033 } *a;
1034 int nId; /* Number of identifiers on the list */
1035 int nAlloc; /* Number of entries allocated for a[] below */
1036 };
1037
1038 /*
1039 ** The bitmask datatype defined below is used for various optimizations.
1040 */
1041 typedef unsigned int Bitmask;
1042
1043 /*
1044 ** The following structure describes the FROM clause of a SELECT statement.
1045 ** Each table or subquery in the FROM clause is a separate element of
1046 ** the SrcList.a[] array.
1047 **
1048 ** With the addition of multiple database support, the following structure
1049 ** can also be used to describe a particular table such as the table that
1050 ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
1051 ** such a table must be a simple name: ID. But in SQLite, the table can
1052 ** now be identified by a database name, a dot, then the table name: ID.ID.
1053 */
1054 struct SrcList {
1055 i16 nSrc; /* Number of tables or subqueries in the FROM clause */
1056 i16 nAlloc; /* Number of entries allocated in a[] below */
1057 struct SrcList_item {
1058 char *zDatabase; /* Name of database holding this table */
1059 char *zName; /* Name of the table */
1060 char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
1061 Table *pTab; /* An SQL table corresponding to zName */
1062 Select *pSelect; /* A SELECT statement used in place of a table name */
1063 u8 isPopulated; /* Temporary table associated with SELECT is populated */
1064 u8 jointype; /* Type of join between this table and the next */
1065 i16 iCursor; /* The VDBE cursor number used to access this table */
1066 Expr *pOn; /* The ON clause of a join */
1067 IdList *pUsing; /* The USING clause of a join */
1068 Bitmask colUsed; /* Bit N (1<<N) set if column N or pTab is used */
1069 } a[1]; /* One entry for each identifier on the list */
1070 };
1071
1072 /*
1073 ** Permitted values of the SrcList.a.jointype field
1074 */
1075 #define JT_INNER 0x0001 /* Any kind of inner or cross join */
1076 #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
1077 #define JT_NATURAL 0x0004 /* True for a "natural" join */
1078 #define JT_LEFT 0x0008 /* Left outer join */
1079 #define JT_RIGHT 0x0010 /* Right outer join */
1080 #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
1081 #define JT_ERROR 0x0040 /* unknown or unsupported join type */
1082
1083 /*
1084 ** For each nested loop in a WHERE clause implementation, the WhereInfo
1085 ** structure contains a single instance of this structure. This structure
1086 ** is intended to be private the the where.c module and should not be
1087 ** access or modified by other modules.
1088 */
1089 struct WhereLevel {
1090 int iFrom; /* Which entry in the FROM clause */
1091 int flags; /* Flags associated with this level */
1092 int iMem; /* First memory cell used by this level */
1093 int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
1094 Index *pIdx; /* Index used. NULL if no index */
1095 int iTabCur; /* The VDBE cursor used to access the table */
1096 int iIdxCur; /* The VDBE cursor used to acesss pIdx */
1097 int brk; /* Jump here to break out of the loop */
1098 int cont; /* Jump here to continue with the next loop cycle */
1099 int top; /* First instruction of interior of the loop */
1100 int op, p1, p2; /* Opcode used to terminate the loop */
1101 int nEq; /* Number of == or IN constraints on this loop */
1102 int nIn; /* Number of IN operators constraining this loop */
1103 int *aInLoop; /* Loop terminators for IN operators */
1104 };
1105
1106 /*
1107 ** The WHERE clause processing routine has two halves. The
1108 ** first part does the start of the WHERE loop and the second
1109 ** half does the tail of the WHERE loop. An instance of
1110 ** this structure is returned by the first half and passed
1111 ** into the second half to give some continuity.
1112 */
1113 struct WhereInfo {
1114 Parse *pParse;
1115 SrcList *pTabList; /* List of tables in the join */
1116 int iTop; /* The very beginning of the WHERE loop */
1117 int iContinue; /* Jump here to continue with next record */
1118 int iBreak; /* Jump here to break out of the loop */
1119 int nLevel; /* Number of nested loop */
1120 WhereLevel a[1]; /* Information about each nest loop in the WHERE */
1121 };
1122
1123 /*
1124 ** A NameContext defines a context in which to resolve table and column
1125 ** names. The context consists of a list of tables (the pSrcList) field and
1126 ** a list of named expression (pEList). The named expression list may
1127 ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
1128 ** to the table being operated on by INSERT, UPDATE, or DELETE. The
1129 ** pEList corresponds to the result set of a SELECT and is NULL for
1130 ** other statements.
1131 **
1132 ** NameContexts can be nested. When resolving names, the inner-most
1133 ** context is searched first. If no match is found, the next outer
1134 ** context is checked. If there is still no match, the next context
1135 ** is checked. This process continues until either a match is found
1136 ** or all contexts are check. When a match is found, the nRef member of
1137 ** the context containing the match is incremented.
1138 **
1139 ** Each subquery gets a new NameContext. The pNext field points to the
1140 ** NameContext in the parent query. Thus the process of scanning the
1141 ** NameContext list corresponds to searching through successively outer
1142 ** subqueries looking for a match.
1143 */
1144 struct NameContext {
1145 Parse *pParse; /* The parser */
1146 SrcList *pSrcList; /* One or more tables used to resolve names */
1147 ExprList *pEList; /* Optional list of named expressions */
1148 int nRef; /* Number of names resolved by this context */
1149 int nErr; /* Number of errors encountered while resolving names */
1150 u8 allowAgg; /* Aggregate functions allowed here */
1151 u8 hasAgg; /* True if aggregates are seen */
1152 u8 isCheck; /* True if resolving names in a CHECK constraint */
1153 int nDepth; /* Depth of subquery recursion. 1 for no recursion */
1154 AggInfo *pAggInfo; /* Information about aggregates at this level */
1155 NameContext *pNext; /* Next outer name context. NULL for outermost */
1156 };
1157
1158 /*
1159 ** An instance of the following structure contains all information
1160 ** needed to generate code for a single SELECT statement.
1161 **
1162 ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
1163 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
1164 ** limit and nOffset to the value of the offset (or 0 if there is not
1165 ** offset). But later on, nLimit and nOffset become the memory locations
1166 ** in the VDBE that record the limit and offset counters.
1167 **
1168 ** addrOpenVirt[] entries contain the address of OP_OpenVirtual opcodes.
1169 ** These addresses must be stored so that we can go back and fill in
1170 ** the P3_KEYINFO and P2 parameters later. Neither the KeyInfo nor
1171 ** the number of columns in P2 can be computed at the same time
1172 ** as the OP_OpenVirtual instruction is coded because not
1173 ** enough information about the compound query is known at that point.
1174 ** The KeyInfo for addrOpenVirt[0] and [1] contains collating sequences
1175 ** for the result set. The KeyInfo for addrOpenVirt[2] contains collating
1176 ** sequences for the ORDER BY clause.
1177 */
1178 struct Select {
1179 ExprList *pEList; /* The fields of the result */
1180 u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
1181 u8 isDistinct; /* True if the DISTINCT keyword is present */
1182 u8 isResolved; /* True once sqlite3SelectResolve() has run. */
1183 u8 isAgg; /* True if this is an aggregate query */
1184 u8 usesVirt; /* True if uses an OpenVirtual opcode */
1185 u8 disallowOrderBy; /* Do not allow an ORDER BY to be attached if TRUE */
1186 SrcList *pSrc; /* The FROM clause */
1187 Expr *pWhere; /* The WHERE clause */
1188 ExprList *pGroupBy; /* The GROUP BY clause */
1189 Expr *pHaving; /* The HAVING clause */
1190 ExprList *pOrderBy; /* The ORDER BY clause */
1191 Select *pPrior; /* Prior select in a compound select statement */
1192 Select *pRightmost; /* Right-most select in a compound select statement */
1193 Expr *pLimit; /* LIMIT expression. NULL means not used. */
1194 Expr *pOffset; /* OFFSET expression. NULL means not used. */
1195 int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
1196 int addrOpenVirt[3]; /* OP_OpenVirtual opcodes related to this select */
1197 };
1198
1199 /*
1200 ** The results of a select can be distributed in several ways.
1201 */
1202 #define SRT_Union 1 /* Store result as keys in an index */
1203 #define SRT_Except 2 /* Remove result from a UNION index */
1204 #define SRT_Discard 3 /* Do not save the results anywhere */
1205
1206 /* The ORDER BY clause is ignored for all of the above */
1207 #define IgnorableOrderby(X) (X<=SRT_Discard)
1208
1209 #define SRT_Callback 4 /* Invoke a callback with each row of result */
1210 #define SRT_Mem 5 /* Store result in a memory cell */
1211 #define SRT_Set 6 /* Store non-null results as keys in an index */
1212 #define SRT_Table 7 /* Store result as data with an automatic rowid */
1213 #define SRT_VirtualTab 8 /* Create virtual table and store like SRT_Table */
1214 #define SRT_Subroutine 9 /* Call a subroutine to handle results */
1215 #define SRT_Exists 10 /* Store 1 if the result is not empty */
1216
1217 /*
1218 ** An SQL parser context. A copy of this structure is passed through
1219 ** the parser and down into all the parser action routine in order to
1220 ** carry around information that is global to the entire parse.
1221 **
1222 ** The structure is divided into two parts. When the parser and code
1223 ** generate call themselves recursively, the first part of the structure
1224 ** is constant but the second part is reset at the beginning and end of
1225 ** each recursion.
1226 **
1227 ** The nTableLock and aTableLock variables are only used if the shared-cache
1228 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
1229 ** used to store the set of table-locks required by the statement being
1230 ** compiled. Function sqlite3TableLock() is used to add entries to the
1231 ** list.
1232 */
1233 struct Parse {
1234 sqlite3 *db; /* The main database structure */
1235 int rc; /* Return code from execution */
1236 char *zErrMsg; /* An error message */
1237 Vdbe *pVdbe; /* An engine for executing database bytecode */
1238 u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
1239 u8 nameClash; /* A permanent table name clashes with temp table name */
1240 u8 checkSchema; /* Causes schema cookie check after an error */
1241 u8 nested; /* Number of nested calls to the parser/code generator */
1242 u8 parseError; /* True if a parsing error has been seen */
1243 int nErr; /* Number of errors seen */
1244 int nTab; /* Number of previously allocated VDBE cursors */
1245 int nMem; /* Number of memory cells used so far */
1246 int nSet; /* Number of sets used so far */
1247 int ckOffset; /* Stack offset to data used by CHECK constraints */
1248 u32 writeMask; /* Start a write transaction on these databases */
1249 u32 cookieMask; /* Bitmask of schema verified databases */
1250 int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
1251 int cookieValue[MAX_ATTACHED+2]; /* Values of cookies to verify */
1252 #ifndef SQLITE_OMIT_SHARED_CACHE
1253 int nTableLock; /* Number of locks in aTableLock */
1254 TableLock *aTableLock; /* Required table locks for shared-cache mode */
1255 #endif
1256
1257 /* Above is constant between recursions. Below is reset before and after
1258 ** each recursion */
1259
1260 int nVar; /* Number of '?' variables seen in the SQL so far */
1261 int nVarExpr; /* Number of used slots in apVarExpr[] */
1262 int nVarExprAlloc; /* Number of allocated slots in apVarExpr[] */
1263 Expr **apVarExpr; /* Pointers to :aaa and $aaaa wildcard expressions */
1264 u8 explain; /* True if the EXPLAIN flag is found on the query */
1265 Token sErrToken; /* The token at which the error occurred */
1266 Token sNameToken; /* Token with unqualified schema object name */
1267 Token sLastToken; /* The last token parsed */
1268 const char *zSql; /* All SQL text */
1269 const char *zTail; /* All SQL text past the last semicolon parsed */
1270 Table *pNewTable; /* A table being constructed by CREATE TABLE */
1271 Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
1272 TriggerStack *trigStack; /* Trigger actions being coded */
1273 const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
1274 };
1275
1276 /*
1277 ** An instance of the following structure can be declared on a stack and used
1278 ** to save the Parse.zAuthContext value so that it can be restored later.
1279 */
1280 struct AuthContext {
1281 const char *zAuthContext; /* Put saved Parse.zAuthContext here */
1282 Parse *pParse; /* The Parse structure */
1283 };
1284
1285 /*
1286 ** Bitfield flags for P2 value in OP_Insert and OP_Delete
1287 */
1288 #define OPFLAG_NCHANGE 1 /* Set to update db->nChange */
1289 #define OPFLAG_LASTROWID 2 /* Set to update db->lastRowid */
1290 #define OPFLAG_ISUPDATE 4 /* This OP_Insert is an sql UPDATE */
1291
1292 /*
1293 * Each trigger present in the database schema is stored as an instance of
1294 * struct Trigger.
1295 *
1296 * Pointers to instances of struct Trigger are stored in two ways.
1297 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
1298 * database). This allows Trigger structures to be retrieved by name.
1299 * 2. All triggers associated with a single table form a linked list, using the
1300 * pNext member of struct Trigger. A pointer to the first element of the
1301 * linked list is stored as the "pTrigger" member of the associated
1302 * struct Table.
1303 *
1304 * The "step_list" member points to the first element of a linked list
1305 * containing the SQL statements specified as the trigger program.
1306 */
1307 struct Trigger {
1308 char *name; /* The name of the trigger */
1309 char *table; /* The table or view to which the trigger applies */
1310 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
1311 u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
1312 Expr *pWhen; /* The WHEN clause of the expresion (may be NULL) */
1313 IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
1314 the <column-list> is stored here */
1315 int foreach; /* One of TK_ROW or TK_STATEMENT */
1316 Token nameToken; /* Token containing zName. Use during parsing only */
1317 Schema *pSchema; /* Schema containing the trigger */
1318 Schema *pTabSchema; /* Schema containing the table */
1319 TriggerStep *step_list; /* Link list of trigger program steps */
1320 Trigger *pNext; /* Next trigger associated with the table */
1321 };
1322
1323 /*
1324 ** A trigger is either a BEFORE or an AFTER trigger. The following constants
1325 ** determine which.
1326 **
1327 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
1328 ** In that cases, the constants below can be ORed together.
1329 */
1330 #define TRIGGER_BEFORE 1
1331 #define TRIGGER_AFTER 2
1332
1333 /*
1334 * An instance of struct TriggerStep is used to store a single SQL statement
1335 * that is a part of a trigger-program.
1336 *
1337 * Instances of struct TriggerStep are stored in a singly linked list (linked
1338 * using the "pNext" member) referenced by the "step_list" member of the
1339 * associated struct Trigger instance. The first element of the linked list is
1340 * the first step of the trigger-program.
1341 *
1342 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
1343 * "SELECT" statement. The meanings of the other members is determined by the
1344 * value of "op" as follows:
1345 *
1346 * (op == TK_INSERT)
1347 * orconf -> stores the ON CONFLICT algorithm
1348 * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
1349 * this stores a pointer to the SELECT statement. Otherwise NULL.
1350 * target -> A token holding the name of the table to insert into.
1351 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
1352 * this stores values to be inserted. Otherwise NULL.
1353 * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
1354 * statement, then this stores the column-names to be
1355 * inserted into.
1356 *
1357 * (op == TK_DELETE)
1358 * target -> A token holding the name of the table to delete from.
1359 * pWhere -> The WHERE clause of the DELETE statement if one is specified.
1360 * Otherwise NULL.
1361 *
1362 * (op == TK_UPDATE)
1363 * target -> A token holding the name of the table to update rows of.
1364 * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
1365 * Otherwise NULL.
1366 * pExprList -> A list of the columns to update and the expressions to update
1367 * them to. See sqlite3Update() documentation of "pChanges"
1368 * argument.
1369 *
1370 */
1371 struct TriggerStep {
1372 int op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
1373 int orconf; /* OE_Rollback etc. */
1374 Trigger *pTrig; /* The trigger that this step is a part of */
1375
1376 Select *pSelect; /* Valid for SELECT and sometimes
1377 INSERT steps (when pExprList == 0) */
1378 Token target; /* Valid for DELETE, UPDATE, INSERT steps */
1379 Expr *pWhere; /* Valid for DELETE, UPDATE steps */
1380 ExprList *pExprList; /* Valid for UPDATE statements and sometimes
1381 INSERT steps (when pSelect == 0) */
1382 IdList *pIdList; /* Valid for INSERT statements only */
1383 TriggerStep *pNext; /* Next in the link-list */
1384 TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
1385 };
1386
1387 /*
1388 * An instance of struct TriggerStack stores information required during code
1389 * generation of a single trigger program. While the trigger program is being
1390 * coded, its associated TriggerStack instance is pointed to by the
1391 * "pTriggerStack" member of the Parse structure.
1392 *
1393 * The pTab member points to the table that triggers are being coded on. The
1394 * newIdx member contains the index of the vdbe cursor that points at the temp
1395 * table that stores the new.* references. If new.* references are not valid
1396 * for the trigger being coded (for example an ON DELETE trigger), then newIdx
1397 * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
1398 *
1399 * The ON CONFLICT policy to be used for the trigger program steps is stored
1400 * as the orconf member. If this is OE_Default, then the ON CONFLICT clause
1401 * specified for individual triggers steps is used.
1402 *
1403 * struct TriggerStack has a "pNext" member, to allow linked lists to be
1404 * constructed. When coding nested triggers (triggers fired by other triggers)
1405 * each nested trigger stores its parent trigger's TriggerStack as the "pNext"
1406 * pointer. Once the nested trigger has been coded, the pNext value is restored
1407 * to the pTriggerStack member of the Parse stucture and coding of the parent
1408 * trigger continues.
1409 *
1410 * Before a nested trigger is coded, the linked list pointed to by the
1411 * pTriggerStack is scanned to ensure that the trigger is not about to be coded
1412 * recursively. If this condition is detected, the nested trigger is not coded.
1413 */
1414 struct TriggerStack {
1415 Table *pTab; /* Table that triggers are currently being coded on */
1416 int newIdx; /* Index of vdbe cursor to "new" temp table */
1417 int oldIdx; /* Index of vdbe cursor to "old" temp table */
1418 int orconf; /* Current orconf policy */
1419 int ignoreJump; /* where to jump to for a RAISE(IGNORE) */
1420 Trigger *pTrigger; /* The trigger currently being coded */
1421 TriggerStack *pNext; /* Next trigger down on the trigger stack */
1422 };
1423
1424 /*
1425 ** The following structure contains information used by the sqliteFix...
1426 ** routines as they walk the parse tree to make database references
1427 ** explicit.
1428 */
1429 typedef struct DbFixer DbFixer;
1430 struct DbFixer {
1431 Parse *pParse; /* The parsing context. Error messages written here */
1432 const char *zDb; /* Make sure all objects are contained in this database */
1433 const char *zType; /* Type of the container - used for error messages */
1434 const Token *pName; /* Name of the container - used for error messages */
1435 };
1436
1437 /*
1438 ** A pointer to this structure is used to communicate information
1439 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
1440 */
1441 typedef struct {
1442 sqlite3 *db; /* The database being initialized */
1443 char **pzErrMsg; /* Error message stored here */
1444 } InitData;
1445
1446 /*
1447 * This global flag is set for performance testing of triggers. When it is set
1448 * SQLite will perform the overhead of building new and old trigger references
1449 * even when no triggers exist
1450 */
1451 extern int sqlite3_always_code_trigger_setup;
1452
1453 /*
1454 ** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production
1455 ** builds) or a function call (for debugging). If it is a function call,
1456 ** it allows the operator to set a breakpoint at the spot where database
1457 ** corruption is first detected.
1458 */
1459 #ifdef SQLITE_DEBUG
1460 extern int sqlite3Corrupt(void);
1461 # define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
1462 #else
1463 # define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
1464 #endif
1465
1466 /*
1467 ** Internal function prototypes
1468 */
1469 int sqlite3StrICmp(const char *, const char *);
1470 int sqlite3StrNICmp(const char *, const char *, int);
1471 int sqlite3HashNoCase(const char *, int);
1472 int sqlite3IsNumber(const char*, int*, u8);
1473 int sqlite3Compare(const char *, const char *);
1474 int sqlite3SortCompare(const char *, const char *);
1475 void sqlite3RealToSortable(double r, char *);
1476
1477 void *sqlite3Malloc(int,int);
1478 void *sqlite3MallocRaw(int,int);
1479 void sqlite3Free(void*);
1480 void *sqlite3Realloc(void*,int);
1481 char *sqlite3StrDup(const char*);
1482 char *sqlite3StrNDup(const char*, int);
1483 # define sqlite3CheckMemory(a,b)
1484 void sqlite3ReallocOrFree(void**,int);
1485 void sqlite3FreeX(void*);
1486 void *sqlite3MallocX(int);
1487 int sqlite3AllocSize(void *);
1488
1489 char *sqlite3MPrintf(const char*, ...);
1490 char *sqlite3VMPrintf(const char*, va_list);
1491 void sqlite3DebugPrintf(const char*, ...);
1492 void *sqlite3TextToPtr(const char*);
1493 void sqlite3SetString(char **, ...);
1494 void sqlite3ErrorMsg(Parse*, const char*, ...);
1495 void sqlite3ErrorClear(Parse*);
1496 void sqlite3Dequote(char*);
1497 void sqlite3DequoteExpr(Expr*);
1498 int sqlite3KeywordCode(const unsigned char*, int);
1499 int sqlite3RunParser(Parse*, const char*, char **);
1500 void sqlite3FinishCoding(Parse*);
1501 Expr *sqlite3Expr(int, Expr*, Expr*, const Token*);
1502 Expr *sqlite3RegisterExpr(Parse*,Token*);
1503 Expr *sqlite3ExprAnd(Expr*, Expr*);
1504 void sqlite3ExprSpan(Expr*,Token*,Token*);
1505 Expr *sqlite3ExprFunction(ExprList*, Token*);
1506 void sqlite3ExprAssignVarNumber(Parse*, Expr*);
1507 void sqlite3ExprDelete(Expr*);
1508 ExprList *sqlite3ExprListAppend(ExprList*,Expr*,Token*);
1509 void sqlite3ExprListDelete(ExprList*);
1510 int sqlite3Init(sqlite3*, char**);
1511 int sqlite3InitCallback(void*, int, char**, char**);
1512 void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
1513 void sqlite3ResetInternalSchema(sqlite3*, int);
1514 void sqlite3BeginParse(Parse*,int);
1515 void sqlite3RollbackInternalChanges(sqlite3*);
1516 void sqlite3CommitInternalChanges(sqlite3*);
1517 Table *sqlite3ResultSetOfSelect(Parse*,char*,Select*);
1518 void sqlite3OpenMasterTable(Parse *, int);
1519 void sqlite3StartTable(Parse*,Token*,Token*,int,int,int);
1520 void sqlite3AddColumn(Parse*,Token*);
1521 void sqlite3AddNotNull(Parse*, int);
1522 void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
1523 void sqlite3AddCheckConstraint(Parse*, Expr*);
1524 void sqlite3AddColumnType(Parse*,Token*);
1525 void sqlite3AddDefaultValue(Parse*,Expr*);
1526 void sqlite3AddCollateType(Parse*, const char*, int);
1527 void sqlite3EndTable(Parse*,Token*,Token*,Select*);
1528
1529 #ifndef SQLITE_OMIT_VIEW
1530 void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int);
1531 int sqlite3ViewGetColumnNames(Parse*,Table*);
1532 #else
1533 # define sqlite3ViewGetColumnNames(A,B) 0
1534 #endif
1535
1536 void sqlite3DropTable(Parse*, SrcList*, int, int);
1537 void sqlite3DeleteTable(sqlite3*, Table*);
1538 void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
1539 int sqlite3ArrayAllocate(void**,int,int);
1540 IdList *sqlite3IdListAppend(IdList*, Token*);
1541 int sqlite3IdListIndex(IdList*,const char*);
1542 SrcList *sqlite3SrcListAppend(SrcList*, Token*, Token*);
1543 void sqlite3SrcListAddAlias(SrcList*, Token*);
1544 void sqlite3SrcListAssignCursors(Parse*, SrcList*);
1545 void sqlite3IdListDelete(IdList*);
1546 void sqlite3SrcListDelete(SrcList*);
1547 void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
1548 Token*, int, int);
1549 void sqlite3DropIndex(Parse*, SrcList*, int);
1550 void sqlite3AddKeyType(Vdbe*, ExprList*);
1551 void sqlite3AddIdxKeyType(Vdbe*, Index*);
1552 int sqlite3Select(Parse*, Select*, int, int, Select*, int, int*, char *aff);
1553 Select *sqlite3SelectNew(ExprList*,SrcList*,Expr*,ExprList*,Expr*,ExprList*,
1554 int,Expr*,Expr*);
1555 void sqlite3SelectDelete(Select*);
1556 void sqlite3SelectUnbind(Select*);
1557 Table *sqlite3SrcListLookup(Parse*, SrcList*);
1558 int sqlite3IsReadOnly(Parse*, Table*, int);
1559 void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
1560 void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
1561 void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
1562 WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**);
1563 void sqlite3WhereEnd(WhereInfo*);
1564 void sqlite3ExprCode(Parse*, Expr*);
1565 void sqlite3ExprCodeAndCache(Parse*, Expr*);
1566 int sqlite3ExprCodeExprList(Parse*, ExprList*);
1567 void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
1568 void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
1569 void sqlite3NextedParse(Parse*, const char*, ...);
1570 Table *sqlite3FindTable(sqlite3*,const char*, const char*);
1571 Table *sqlite3LocateTable(Parse*,const char*, const char*);
1572 Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
1573 void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
1574 void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
1575 void sqlite3Vacuum(Parse*);
1576 int sqlite3RunVacuum(char**, sqlite3*);
1577 char *sqlite3NameFromToken(Token*);
1578 int sqlite3ExprCheck(Parse*, Expr*, int, int*);
1579 int sqlite3ExprCompare(Expr*, Expr*);
1580 int sqliteFuncId(Token*);
1581 int sqlite3ExprResolveNames(NameContext *, Expr *);
1582 int sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
1583 int sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
1584 Vdbe *sqlite3GetVdbe(Parse*);
1585 void sqlite3Randomness(int, void*);
1586 void sqlite3RollbackAll(sqlite3*);
1587 void sqlite3CodeVerifySchema(Parse*, int);
1588 void sqlite3BeginTransaction(Parse*, int);
1589 void sqlite3CommitTransaction(Parse*);
1590 void sqlite3RollbackTransaction(Parse*);
1591 int sqlite3ExprIsConstant(Expr*);
1592 int sqlite3ExprIsConstantOrFunction(Expr*);
1593 int sqlite3ExprIsInteger(Expr*, int*);
1594 int sqlite3IsRowid(const char*);
1595 void sqlite3GenerateRowDelete(sqlite3*, Vdbe*, Table*, int, int);
1596 void sqlite3GenerateRowIndexDelete(Vdbe*, Table*, int, char*);
1597 void sqlite3GenerateIndexKey(Vdbe*, Index*, int);
1598 void sqlite3GenerateConstraintChecks(Parse*,Table*,int,char*,int,int,int,int);
1599 void sqlite3CompleteInsertion(Parse*, Table*, int, char*, int, int, int);
1600 void sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
1601 void sqlite3BeginWriteOperation(Parse*, int, int);
1602 Expr *sqlite3ExprDup(Expr*);
1603 void sqlite3TokenCopy(Token*, Token*);
1604 ExprList *sqlite3ExprListDup(ExprList*);
1605 SrcList *sqlite3SrcListDup(SrcList*);
1606 IdList *sqlite3IdListDup(IdList*);
1607 Select *sqlite3SelectDup(Select*);
1608 FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
1609 void sqlite3RegisterBuiltinFunctions(sqlite3*);
1610 void sqlite3RegisterDateTimeFunctions(sqlite3*);
1611 int sqlite3SafetyOn(sqlite3*);
1612 int sqlite3SafetyOff(sqlite3*);
1613 int sqlite3SafetyCheck(sqlite3*);
1614 void sqlite3ChangeCookie(sqlite3*, Vdbe*, int);
1615
1616 #ifndef SQLITE_OMIT_TRIGGER
1617 void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
1618 int,Expr*,int);
1619 void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
1620 void sqlite3DropTrigger(Parse*, SrcList*);
1621 void sqlite3DropTriggerPtr(Parse*, Trigger*);
1622 int sqlite3TriggersExist(Parse*, Table*, int, ExprList*);
1623 int sqlite3CodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int,
1624 int, int);
1625 void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
1626 void sqlite3DeleteTriggerStep(TriggerStep*);
1627 TriggerStep *sqlite3TriggerSelectStep(Select*);
1628 TriggerStep *sqlite3TriggerInsertStep(Token*, IdList*, ExprList*,Select*,int);
1629 TriggerStep *sqlite3TriggerUpdateStep(Token*, ExprList*, Expr*, int);
1630 TriggerStep *sqlite3TriggerDeleteStep(Token*, Expr*);
1631 void sqlite3DeleteTrigger(Trigger*);
1632 void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
1633 #else
1634 # define sqlite3TriggersExist(A,B,C,D,E,F) 0
1635 # define sqlite3DeleteTrigger(A)
1636 # define sqlite3DropTriggerPtr(A,B)
1637 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
1638 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I) 0
1639 #endif
1640
1641 int sqlite3JoinType(Parse*, Token*, Token*, Token*);
1642 void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
1643 void sqlite3DeferForeignKey(Parse*, int);
1644 #ifndef SQLITE_OMIT_AUTHORIZATION
1645 void sqlite3AuthRead(Parse*,Expr*,SrcList*);
1646 int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
1647 void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
1648 void sqlite3AuthContextPop(AuthContext*);
1649 #else
1650 # define sqlite3AuthRead(a,b,c)
1651 # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
1652 # define sqlite3AuthContextPush(a,b,c)
1653 # define sqlite3AuthContextPop(a) ((void)(a))
1654 #endif
1655 void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
1656 void sqlite3Detach(Parse*, Expr*);
1657 int sqlite3BtreeFactory(const sqlite3 *db, const char *zFilename,
1658 int omitJournal, int nCache, Btree **ppBtree);
1659 int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
1660 int sqlite3FixSrcList(DbFixer*, SrcList*);
1661 int sqlite3FixSelect(DbFixer*, Select*);
1662 int sqlite3FixExpr(DbFixer*, Expr*);
1663 int sqlite3FixExprList(DbFixer*, ExprList*);
1664 int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
1665 int sqlite3AtoF(const char *z, double*);
1666 char *sqlite3_snprintf(int,char*,const char*,...);
1667 int sqlite3GetInt32(const char *, int*);
1668 int sqlite3FitsIn64Bits(const char *);
1669 int sqlite3utf16ByteLen(const void *pData, int nChar);
1670 int sqlite3utf8CharLen(const char *pData, int nByte);
1671 int sqlite3ReadUtf8(const unsigned char *);
1672 int sqlite3PutVarint(unsigned char *, u64);
1673 int sqlite3GetVarint(const unsigned char *, u64 *);
1674 int sqlite3GetVarint32(const unsigned char *, u32 *);
1675 int sqlite3VarintLen(u64 v);
1676 void sqlite3IndexAffinityStr(Vdbe *, Index *);
1677 void sqlite3TableAffinityStr(Vdbe *, Table *);
1678 char sqlite3CompareAffinity(Expr *pExpr, char aff2);
1679 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
1680 char sqlite3ExprAffinity(Expr *pExpr);
1681 int sqlite3atoi64(const char*, i64*);
1682 void sqlite3Error(sqlite3*, int, const char*,...);
1683 void *sqlite3HexToBlob(const char *z);
1684 int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
1685 const char *sqlite3ErrStr(int);
1686 int sqlite3ReadUniChar(const char *zStr, int *pOffset, u8 *pEnc, int fold);
1687 int sqlite3ReadSchema(Parse *pParse);
1688 CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char *,int,int);
1689 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName);
1690 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
1691 int sqlite3CheckCollSeq(Parse *, CollSeq *);
1692 int sqlite3CheckIndexCollSeq(Parse *, Index *);
1693 int sqlite3CheckObjectName(Parse *, const char *);
1694 void sqlite3VdbeSetChanges(sqlite3 *, int);
1695 void sqlite3utf16Substr(sqlite3_context *,int,sqlite3_value **);
1696
1697 const void *sqlite3ValueText(sqlite3_value*, u8);
1698 int sqlite3ValueBytes(sqlite3_value*, u8);
1699 void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, void(*)(void*));
1700 void sqlite3ValueFree(sqlite3_value*);
1701 sqlite3_value *sqlite3ValueNew(void);
1702 char *sqlite3utf16to8(const void*, int);
1703 int sqlite3ValueFromExpr(Expr *, u8, u8, sqlite3_value **);
1704 void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
1705 extern const unsigned char sqlite3UpperToLower[];
1706 void sqlite3RootPageMoved(Db*, int, int);
1707 void sqlite3Reindex(Parse*, Token*, Token*);
1708 void sqlite3AlterFunctions(sqlite3*);
1709 void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
1710 int sqlite3GetToken(const unsigned char *, int *);
1711 void sqlite3NestedParse(Parse*, const char*, ...);
1712 void sqlite3ExpirePreparedStatements(sqlite3*);
1713 void sqlite3CodeSubselect(Parse *, Expr *);
1714 int sqlite3SelectResolve(Parse *, Select *, NameContext *);
1715 void sqlite3ColumnDefault(Vdbe *, Table *, int);
1716 void sqlite3AlterFinishAddColumn(Parse *, Token *);
1717 void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
1718 const char *sqlite3TestErrorName(int);
1719 CollSeq *sqlite3GetCollSeq(sqlite3*, CollSeq *, const char *, int);
1720 char sqlite3AffinityType(const Token*);
1721 void sqlite3Analyze(Parse*, Token*, Token*);
1722 int sqlite3InvokeBusyHandler(BusyHandler*);
1723 int sqlite3FindDb(sqlite3*, Token*);
1724 void sqlite3AnalysisLoad(sqlite3*,int iDB);
1725 void sqlite3DefaultRowEst(Index*);
1726 void sqlite3RegisterLikeFunctions(sqlite3*, int);
1727 int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
1728 ThreadData *sqlite3ThreadData(void);
1729 const ThreadData *sqlite3ThreadDataReadOnly(void);
1730 void sqlite3ReleaseThreadData(void);
1731 void sqlite3AttachFunctions(sqlite3 *);
1732 void sqlite3MinimumFileFormat(Parse*, int, int);
1733 void sqlite3SchemaFree(void *);
1734 Schema *sqlite3SchemaGet(Btree *);
1735 int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
1736 KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
1737 int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
1738 void (*)(sqlite3_context*,int,sqlite3_value **),
1739 void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
1740 int sqlite3ApiExit(sqlite3 *db, int);
1741 int sqlite3MallocFailed(void);
1742 void sqlite3FailedMalloc(void);
1743 void sqlite3AbortOtherActiveVdbes(sqlite3 *, Vdbe *);
1744 int sqlite3OpenTempDatabase(Parse *);
1745
1746 #ifndef SQLITE_OMIT_SHARED_CACHE
1747 void sqlite3TableLock(Parse *, int, int, u8, const char *);
1748 #else
1749 #define sqlite3TableLock(v,w,x,y,z)
1750 #endif
1751
1752 #ifdef SQLITE_MEMDEBUG
1753 void sqlite3MallocDisallow(void);
1754 void sqlite3MallocAllow(void);
1755 int sqlite3TestMallocFail(void);
1756 #else
1757 #define sqlite3TestMallocFail() 0
1758 #define sqlite3MallocDisallow()
1759 #define sqlite3MallocAllow()
1760 #endif
1761
1762 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
1763 void *sqlite3ThreadSafeMalloc(int);
1764 void sqlite3ThreadSafeFree(void *);
1765 #else
1766 #define sqlite3ThreadSafeMalloc sqlite3MallocX
1767 #define sqlite3ThreadSafeFree sqlite3FreeX
1768 #endif
1769
1770 #ifdef SQLITE_SSE
1771 #include "sseInt.h"
1772 #endif
1773
1774 #endif