Annotation of embedaddon/sqlite3/src/sqliteInt.h, revision 1.1.1.1
1.1 misho 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: */
15: #ifndef _SQLITEINT_H_
16: #define _SQLITEINT_H_
17:
18: /*
19: ** These #defines should enable >2GB file support on POSIX if the
20: ** underlying operating system supports it. If the OS lacks
21: ** large file support, or if the OS is windows, these should be no-ops.
22: **
23: ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
24: ** system #includes. Hence, this block of code must be the very first
25: ** code in all source files.
26: **
27: ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
28: ** on the compiler command line. This is necessary if you are compiling
29: ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
30: ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
31: ** without this option, LFS is enable. But LFS does not exist in the kernel
32: ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
33: ** portability you should omit LFS.
34: **
35: ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
36: */
37: #ifndef SQLITE_DISABLE_LFS
38: # define _LARGE_FILE 1
39: # ifndef _FILE_OFFSET_BITS
40: # define _FILE_OFFSET_BITS 64
41: # endif
42: # define _LARGEFILE_SOURCE 1
43: #endif
44:
45: /*
46: ** Include the configuration header output by 'configure' if we're using the
47: ** autoconf-based build
48: */
49: #ifdef _HAVE_SQLITE_CONFIG_H
50: #include "config.h"
51: #endif
52:
53: #include "sqliteLimit.h"
54:
55: /* Disable nuisance warnings on Borland compilers */
56: #if defined(__BORLANDC__)
57: #pragma warn -rch /* unreachable code */
58: #pragma warn -ccc /* Condition is always true or false */
59: #pragma warn -aus /* Assigned value is never used */
60: #pragma warn -csu /* Comparing signed and unsigned */
61: #pragma warn -spa /* Suspicious pointer arithmetic */
62: #endif
63:
64: /* Needed for various definitions... */
65: #ifndef _GNU_SOURCE
66: # define _GNU_SOURCE
67: #endif
68:
69: /*
70: ** Include standard header files as necessary
71: */
72: #ifdef HAVE_STDINT_H
73: #include <stdint.h>
74: #endif
75: #ifdef HAVE_INTTYPES_H
76: #include <inttypes.h>
77: #endif
78:
79: /*
80: ** The following macros are used to cast pointers to integers and
81: ** integers to pointers. The way you do this varies from one compiler
82: ** to the next, so we have developed the following set of #if statements
83: ** to generate appropriate macros for a wide range of compilers.
84: **
85: ** The correct "ANSI" way to do this is to use the intptr_t type.
86: ** Unfortunately, that typedef is not available on all compilers, or
87: ** if it is available, it requires an #include of specific headers
88: ** that vary from one machine to the next.
89: **
90: ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
91: ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
92: ** So we have to define the macros in different ways depending on the
93: ** compiler.
94: */
95: #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
96: # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
97: # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
98: #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
99: # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
100: # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
101: #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
102: # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
103: # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
104: #else /* Generates a warning - but it always works */
105: # define SQLITE_INT_TO_PTR(X) ((void*)(X))
106: # define SQLITE_PTR_TO_INT(X) ((int)(X))
107: #endif
108:
109: /*
110: ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
111: ** 0 means mutexes are permanently disable and the library is never
112: ** threadsafe. 1 means the library is serialized which is the highest
113: ** level of threadsafety. 2 means the libary is multithreaded - multiple
114: ** threads can use SQLite as long as no two threads try to use the same
115: ** database connection at the same time.
116: **
117: ** Older versions of SQLite used an optional THREADSAFE macro.
118: ** We support that for legacy.
119: */
120: #if !defined(SQLITE_THREADSAFE)
121: #if defined(THREADSAFE)
122: # define SQLITE_THREADSAFE THREADSAFE
123: #else
124: # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
125: #endif
126: #endif
127:
128: /*
129: ** Powersafe overwrite is on by default. But can be turned off using
130: ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
131: */
132: #ifndef SQLITE_POWERSAFE_OVERWRITE
133: # define SQLITE_POWERSAFE_OVERWRITE 1
134: #endif
135:
136: /*
137: ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
138: ** It determines whether or not the features related to
139: ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
140: ** be overridden at runtime using the sqlite3_config() API.
141: */
142: #if !defined(SQLITE_DEFAULT_MEMSTATUS)
143: # define SQLITE_DEFAULT_MEMSTATUS 1
144: #endif
145:
146: /*
147: ** Exactly one of the following macros must be defined in order to
148: ** specify which memory allocation subsystem to use.
149: **
150: ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
151: ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
152: ** SQLITE_MEMDEBUG // Debugging version of system malloc()
153: **
154: ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
155: ** assert() macro is enabled, each call into the Win32 native heap subsystem
156: ** will cause HeapValidate to be called. If heap validation should fail, an
157: ** assertion will be triggered.
158: **
159: ** (Historical note: There used to be several other options, but we've
160: ** pared it down to just these three.)
161: **
162: ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
163: ** the default.
164: */
165: #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_WIN32_MALLOC)+defined(SQLITE_MEMDEBUG)>1
166: # error "At most one of the following compile-time configuration options\
167: is allows: SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG"
168: #endif
169: #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_WIN32_MALLOC)+defined(SQLITE_MEMDEBUG)==0
170: # define SQLITE_SYSTEM_MALLOC 1
171: #endif
172:
173: /*
174: ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
175: ** sizes of memory allocations below this value where possible.
176: */
177: #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
178: # define SQLITE_MALLOC_SOFT_LIMIT 1024
179: #endif
180:
181: /*
182: ** We need to define _XOPEN_SOURCE as follows in order to enable
183: ** recursive mutexes on most Unix systems. But Mac OS X is different.
184: ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
185: ** so it is omitted there. See ticket #2673.
186: **
187: ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
188: ** implemented on some systems. So we avoid defining it at all
189: ** if it is already defined or if it is unneeded because we are
190: ** not doing a threadsafe build. Ticket #2681.
191: **
192: ** See also ticket #2741.
193: */
194: #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
195: # define _XOPEN_SOURCE 500 /* Needed to enable pthread recursive mutexes */
196: #endif
197:
198: /*
199: ** The TCL headers are only needed when compiling the TCL bindings.
200: */
201: #if defined(SQLITE_TCL) || defined(TCLSH)
202: # include <tcl.h>
203: #endif
204:
205: /*
206: ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
207: ** Setting NDEBUG makes the code smaller and run faster. So the following
208: ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
209: ** option is set. Thus NDEBUG becomes an opt-in rather than an opt-out
210: ** feature.
211: */
212: #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
213: # define NDEBUG 1
214: #endif
215:
216: /*
217: ** The testcase() macro is used to aid in coverage testing. When
218: ** doing coverage testing, the condition inside the argument to
219: ** testcase() must be evaluated both true and false in order to
220: ** get full branch coverage. The testcase() macro is inserted
221: ** to help ensure adequate test coverage in places where simple
222: ** condition/decision coverage is inadequate. For example, testcase()
223: ** can be used to make sure boundary values are tested. For
224: ** bitmask tests, testcase() can be used to make sure each bit
225: ** is significant and used at least once. On switch statements
226: ** where multiple cases go to the same block of code, testcase()
227: ** can insure that all cases are evaluated.
228: **
229: */
230: #ifdef SQLITE_COVERAGE_TEST
231: void sqlite3Coverage(int);
232: # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
233: #else
234: # define testcase(X)
235: #endif
236:
237: /*
238: ** The TESTONLY macro is used to enclose variable declarations or
239: ** other bits of code that are needed to support the arguments
240: ** within testcase() and assert() macros.
241: */
242: #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
243: # define TESTONLY(X) X
244: #else
245: # define TESTONLY(X)
246: #endif
247:
248: /*
249: ** Sometimes we need a small amount of code such as a variable initialization
250: ** to setup for a later assert() statement. We do not want this code to
251: ** appear when assert() is disabled. The following macro is therefore
252: ** used to contain that setup code. The "VVA" acronym stands for
253: ** "Verification, Validation, and Accreditation". In other words, the
254: ** code within VVA_ONLY() will only run during verification processes.
255: */
256: #ifndef NDEBUG
257: # define VVA_ONLY(X) X
258: #else
259: # define VVA_ONLY(X)
260: #endif
261:
262: /*
263: ** The ALWAYS and NEVER macros surround boolean expressions which
264: ** are intended to always be true or false, respectively. Such
265: ** expressions could be omitted from the code completely. But they
266: ** are included in a few cases in order to enhance the resilience
267: ** of SQLite to unexpected behavior - to make the code "self-healing"
268: ** or "ductile" rather than being "brittle" and crashing at the first
269: ** hint of unplanned behavior.
270: **
271: ** In other words, ALWAYS and NEVER are added for defensive code.
272: **
273: ** When doing coverage testing ALWAYS and NEVER are hard-coded to
274: ** be true and false so that the unreachable code then specify will
275: ** not be counted as untested code.
276: */
277: #if defined(SQLITE_COVERAGE_TEST)
278: # define ALWAYS(X) (1)
279: # define NEVER(X) (0)
280: #elif !defined(NDEBUG)
281: # define ALWAYS(X) ((X)?1:(assert(0),0))
282: # define NEVER(X) ((X)?(assert(0),1):0)
283: #else
284: # define ALWAYS(X) (X)
285: # define NEVER(X) (X)
286: #endif
287:
288: /*
289: ** Return true (non-zero) if the input is a integer that is too large
290: ** to fit in 32-bits. This macro is used inside of various testcase()
291: ** macros to verify that we have tested SQLite for large-file support.
292: */
293: #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
294:
295: /*
296: ** The macro unlikely() is a hint that surrounds a boolean
297: ** expression that is usually false. Macro likely() surrounds
298: ** a boolean expression that is usually true. GCC is able to
299: ** use these hints to generate better code, sometimes.
300: */
301: #if defined(__GNUC__) && 0
302: # define likely(X) __builtin_expect((X),1)
303: # define unlikely(X) __builtin_expect((X),0)
304: #else
305: # define likely(X) !!(X)
306: # define unlikely(X) !!(X)
307: #endif
308:
309: #include "sqlite3.h"
310: #include "hash.h"
311: #include "parse.h"
312: #include <stdio.h>
313: #include <stdlib.h>
314: #include <string.h>
315: #include <assert.h>
316: #include <stddef.h>
317:
318: /*
319: ** If compiling for a processor that lacks floating point support,
320: ** substitute integer for floating-point
321: */
322: #ifdef SQLITE_OMIT_FLOATING_POINT
323: # define double sqlite_int64
324: # define float sqlite_int64
325: # define LONGDOUBLE_TYPE sqlite_int64
326: # ifndef SQLITE_BIG_DBL
327: # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
328: # endif
329: # define SQLITE_OMIT_DATETIME_FUNCS 1
330: # define SQLITE_OMIT_TRACE 1
331: # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
332: # undef SQLITE_HAVE_ISNAN
333: #endif
334: #ifndef SQLITE_BIG_DBL
335: # define SQLITE_BIG_DBL (1e99)
336: #endif
337:
338: /*
339: ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
340: ** afterward. Having this macro allows us to cause the C compiler
341: ** to omit code used by TEMP tables without messy #ifndef statements.
342: */
343: #ifdef SQLITE_OMIT_TEMPDB
344: #define OMIT_TEMPDB 1
345: #else
346: #define OMIT_TEMPDB 0
347: #endif
348:
349: /*
350: ** The "file format" number is an integer that is incremented whenever
351: ** the VDBE-level file format changes. The following macros define the
352: ** the default file format for new databases and the maximum file format
353: ** that the library can read.
354: */
355: #define SQLITE_MAX_FILE_FORMAT 4
356: #ifndef SQLITE_DEFAULT_FILE_FORMAT
357: # define SQLITE_DEFAULT_FILE_FORMAT 4
358: #endif
359:
360: /*
361: ** Determine whether triggers are recursive by default. This can be
362: ** changed at run-time using a pragma.
363: */
364: #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
365: # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
366: #endif
367:
368: /*
369: ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
370: ** on the command-line
371: */
372: #ifndef SQLITE_TEMP_STORE
373: # define SQLITE_TEMP_STORE 1
374: #endif
375:
376: /*
377: ** GCC does not define the offsetof() macro so we'll have to do it
378: ** ourselves.
379: */
380: #ifndef offsetof
381: #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
382: #endif
383:
384: /*
385: ** Check to see if this machine uses EBCDIC. (Yes, believe it or
386: ** not, there are still machines out there that use EBCDIC.)
387: */
388: #if 'A' == '\301'
389: # define SQLITE_EBCDIC 1
390: #else
391: # define SQLITE_ASCII 1
392: #endif
393:
394: /*
395: ** Integers of known sizes. These typedefs might change for architectures
396: ** where the sizes very. Preprocessor macros are available so that the
397: ** types can be conveniently redefined at compile-type. Like this:
398: **
399: ** cc '-DUINTPTR_TYPE=long long int' ...
400: */
401: #ifndef UINT32_TYPE
402: # ifdef HAVE_UINT32_T
403: # define UINT32_TYPE uint32_t
404: # else
405: # define UINT32_TYPE unsigned int
406: # endif
407: #endif
408: #ifndef UINT16_TYPE
409: # ifdef HAVE_UINT16_T
410: # define UINT16_TYPE uint16_t
411: # else
412: # define UINT16_TYPE unsigned short int
413: # endif
414: #endif
415: #ifndef INT16_TYPE
416: # ifdef HAVE_INT16_T
417: # define INT16_TYPE int16_t
418: # else
419: # define INT16_TYPE short int
420: # endif
421: #endif
422: #ifndef UINT8_TYPE
423: # ifdef HAVE_UINT8_T
424: # define UINT8_TYPE uint8_t
425: # else
426: # define UINT8_TYPE unsigned char
427: # endif
428: #endif
429: #ifndef INT8_TYPE
430: # ifdef HAVE_INT8_T
431: # define INT8_TYPE int8_t
432: # else
433: # define INT8_TYPE signed char
434: # endif
435: #endif
436: #ifndef LONGDOUBLE_TYPE
437: # define LONGDOUBLE_TYPE long double
438: #endif
439: typedef sqlite_int64 i64; /* 8-byte signed integer */
440: typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
441: typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
442: typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
443: typedef INT16_TYPE i16; /* 2-byte signed integer */
444: typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
445: typedef INT8_TYPE i8; /* 1-byte signed integer */
446:
447: /*
448: ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
449: ** that can be stored in a u32 without loss of data. The value
450: ** is 0x00000000ffffffff. But because of quirks of some compilers, we
451: ** have to specify the value in the less intuitive manner shown:
452: */
453: #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
454:
455: /*
456: ** The datatype used to store estimates of the number of rows in a
457: ** table or index. This is an unsigned integer type. For 99.9% of
458: ** the world, a 32-bit integer is sufficient. But a 64-bit integer
459: ** can be used at compile-time if desired.
460: */
461: #ifdef SQLITE_64BIT_STATS
462: typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
463: #else
464: typedef u32 tRowcnt; /* 32-bit is the default */
465: #endif
466:
467: /*
468: ** Macros to determine whether the machine is big or little endian,
469: ** evaluated at runtime.
470: */
471: #ifdef SQLITE_AMALGAMATION
472: const int sqlite3one = 1;
473: #else
474: extern const int sqlite3one;
475: #endif
476: #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
477: || defined(__x86_64) || defined(__x86_64__)
478: # define SQLITE_BIGENDIAN 0
479: # define SQLITE_LITTLEENDIAN 1
480: # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
481: #else
482: # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
483: # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
484: # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
485: #endif
486:
487: /*
488: ** Constants for the largest and smallest possible 64-bit signed integers.
489: ** These macros are designed to work correctly on both 32-bit and 64-bit
490: ** compilers.
491: */
492: #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
493: #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
494:
495: /*
496: ** Round up a number to the next larger multiple of 8. This is used
497: ** to force 8-byte alignment on 64-bit architectures.
498: */
499: #define ROUND8(x) (((x)+7)&~7)
500:
501: /*
502: ** Round down to the nearest multiple of 8
503: */
504: #define ROUNDDOWN8(x) ((x)&~7)
505:
506: /*
507: ** Assert that the pointer X is aligned to an 8-byte boundary. This
508: ** macro is used only within assert() to verify that the code gets
509: ** all alignment restrictions correct.
510: **
511: ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
512: ** underlying malloc() implemention might return us 4-byte aligned
513: ** pointers. In that case, only verify 4-byte alignment.
514: */
515: #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
516: # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
517: #else
518: # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
519: #endif
520:
521:
522: /*
523: ** An instance of the following structure is used to store the busy-handler
524: ** callback for a given sqlite handle.
525: **
526: ** The sqlite.busyHandler member of the sqlite struct contains the busy
527: ** callback for the database handle. Each pager opened via the sqlite
528: ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
529: ** callback is currently invoked only from within pager.c.
530: */
531: typedef struct BusyHandler BusyHandler;
532: struct BusyHandler {
533: int (*xFunc)(void *,int); /* The busy callback */
534: void *pArg; /* First arg to busy callback */
535: int nBusy; /* Incremented with each busy call */
536: };
537:
538: /*
539: ** Name of the master database table. The master database table
540: ** is a special table that holds the names and attributes of all
541: ** user tables and indices.
542: */
543: #define MASTER_NAME "sqlite_master"
544: #define TEMP_MASTER_NAME "sqlite_temp_master"
545:
546: /*
547: ** The root-page of the master database table.
548: */
549: #define MASTER_ROOT 1
550:
551: /*
552: ** The name of the schema table.
553: */
554: #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
555:
556: /*
557: ** A convenience macro that returns the number of elements in
558: ** an array.
559: */
560: #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
561:
562: /*
563: ** The following value as a destructor means to use sqlite3DbFree().
564: ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
565: */
566: #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3DbFree)
567:
568: /*
569: ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
570: ** not support Writable Static Data (WSD) such as global and static variables.
571: ** All variables must either be on the stack or dynamically allocated from
572: ** the heap. When WSD is unsupported, the variable declarations scattered
573: ** throughout the SQLite code must become constants instead. The SQLITE_WSD
574: ** macro is used for this purpose. And instead of referencing the variable
575: ** directly, we use its constant as a key to lookup the run-time allocated
576: ** buffer that holds real variable. The constant is also the initializer
577: ** for the run-time allocated buffer.
578: **
579: ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
580: ** macros become no-ops and have zero performance impact.
581: */
582: #ifdef SQLITE_OMIT_WSD
583: #define SQLITE_WSD const
584: #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
585: #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
586: int sqlite3_wsd_init(int N, int J);
587: void *sqlite3_wsd_find(void *K, int L);
588: #else
589: #define SQLITE_WSD
590: #define GLOBAL(t,v) v
591: #define sqlite3GlobalConfig sqlite3Config
592: #endif
593:
594: /*
595: ** The following macros are used to suppress compiler warnings and to
596: ** make it clear to human readers when a function parameter is deliberately
597: ** left unused within the body of a function. This usually happens when
598: ** a function is called via a function pointer. For example the
599: ** implementation of an SQL aggregate step callback may not use the
600: ** parameter indicating the number of arguments passed to the aggregate,
601: ** if it knows that this is enforced elsewhere.
602: **
603: ** When a function parameter is not used at all within the body of a function,
604: ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
605: ** However, these macros may also be used to suppress warnings related to
606: ** parameters that may or may not be used depending on compilation options.
607: ** For example those parameters only used in assert() statements. In these
608: ** cases the parameters are named as per the usual conventions.
609: */
610: #define UNUSED_PARAMETER(x) (void)(x)
611: #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
612:
613: /*
614: ** Forward references to structures
615: */
616: typedef struct AggInfo AggInfo;
617: typedef struct AuthContext AuthContext;
618: typedef struct AutoincInfo AutoincInfo;
619: typedef struct Bitvec Bitvec;
620: typedef struct CollSeq CollSeq;
621: typedef struct Column Column;
622: typedef struct Db Db;
623: typedef struct Schema Schema;
624: typedef struct Expr Expr;
625: typedef struct ExprList ExprList;
626: typedef struct ExprSpan ExprSpan;
627: typedef struct FKey FKey;
628: typedef struct FuncDestructor FuncDestructor;
629: typedef struct FuncDef FuncDef;
630: typedef struct FuncDefHash FuncDefHash;
631: typedef struct IdList IdList;
632: typedef struct Index Index;
633: typedef struct IndexSample IndexSample;
634: typedef struct KeyClass KeyClass;
635: typedef struct KeyInfo KeyInfo;
636: typedef struct Lookaside Lookaside;
637: typedef struct LookasideSlot LookasideSlot;
638: typedef struct Module Module;
639: typedef struct NameContext NameContext;
640: typedef struct Parse Parse;
641: typedef struct RowSet RowSet;
642: typedef struct Savepoint Savepoint;
643: typedef struct Select Select;
644: typedef struct SrcList SrcList;
645: typedef struct StrAccum StrAccum;
646: typedef struct Table Table;
647: typedef struct TableLock TableLock;
648: typedef struct Token Token;
649: typedef struct Trigger Trigger;
650: typedef struct TriggerPrg TriggerPrg;
651: typedef struct TriggerStep TriggerStep;
652: typedef struct UnpackedRecord UnpackedRecord;
653: typedef struct VTable VTable;
654: typedef struct VtabCtx VtabCtx;
655: typedef struct Walker Walker;
656: typedef struct WherePlan WherePlan;
657: typedef struct WhereInfo WhereInfo;
658: typedef struct WhereLevel WhereLevel;
659:
660: /*
661: ** Defer sourcing vdbe.h and btree.h until after the "u8" and
662: ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
663: ** pointer types (i.e. FuncDef) defined above.
664: */
665: #include "btree.h"
666: #include "vdbe.h"
667: #include "pager.h"
668: #include "pcache.h"
669:
670: #include "os.h"
671: #include "mutex.h"
672:
673:
674: /*
675: ** Each database file to be accessed by the system is an instance
676: ** of the following structure. There are normally two of these structures
677: ** in the sqlite.aDb[] array. aDb[0] is the main database file and
678: ** aDb[1] is the database file used to hold temporary tables. Additional
679: ** databases may be attached.
680: */
681: struct Db {
682: char *zName; /* Name of this database */
683: Btree *pBt; /* The B*Tree structure for this database file */
684: u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */
685: u8 safety_level; /* How aggressive at syncing data to disk */
686: Schema *pSchema; /* Pointer to database schema (possibly shared) */
687: };
688:
689: /*
690: ** An instance of the following structure stores a database schema.
691: **
692: ** Most Schema objects are associated with a Btree. The exception is
693: ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
694: ** In shared cache mode, a single Schema object can be shared by multiple
695: ** Btrees that refer to the same underlying BtShared object.
696: **
697: ** Schema objects are automatically deallocated when the last Btree that
698: ** references them is destroyed. The TEMP Schema is manually freed by
699: ** sqlite3_close().
700: *
701: ** A thread must be holding a mutex on the corresponding Btree in order
702: ** to access Schema content. This implies that the thread must also be
703: ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
704: ** For a TEMP Schema, only the connection mutex is required.
705: */
706: struct Schema {
707: int schema_cookie; /* Database schema version number for this file */
708: int iGeneration; /* Generation counter. Incremented with each change */
709: Hash tblHash; /* All tables indexed by name */
710: Hash idxHash; /* All (named) indices indexed by name */
711: Hash trigHash; /* All triggers indexed by name */
712: Hash fkeyHash; /* All foreign keys by referenced table name */
713: Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
714: u8 file_format; /* Schema format version for this file */
715: u8 enc; /* Text encoding used by this database */
716: u16 flags; /* Flags associated with this schema */
717: int cache_size; /* Number of pages to use in the cache */
718: };
719:
720: /*
721: ** These macros can be used to test, set, or clear bits in the
722: ** Db.pSchema->flags field.
723: */
724: #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P))
725: #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0)
726: #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P)
727: #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P)
728:
729: /*
730: ** Allowed values for the DB.pSchema->flags field.
731: **
732: ** The DB_SchemaLoaded flag is set after the database schema has been
733: ** read into internal hash tables.
734: **
735: ** DB_UnresetViews means that one or more views have column names that
736: ** have been filled out. If the schema changes, these column names might
737: ** changes and so the view will need to be reset.
738: */
739: #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
740: #define DB_UnresetViews 0x0002 /* Some views have defined column names */
741: #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
742:
743: /*
744: ** The number of different kinds of things that can be limited
745: ** using the sqlite3_limit() interface.
746: */
747: #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
748:
749: /*
750: ** Lookaside malloc is a set of fixed-size buffers that can be used
751: ** to satisfy small transient memory allocation requests for objects
752: ** associated with a particular database connection. The use of
753: ** lookaside malloc provides a significant performance enhancement
754: ** (approx 10%) by avoiding numerous malloc/free requests while parsing
755: ** SQL statements.
756: **
757: ** The Lookaside structure holds configuration information about the
758: ** lookaside malloc subsystem. Each available memory allocation in
759: ** the lookaside subsystem is stored on a linked list of LookasideSlot
760: ** objects.
761: **
762: ** Lookaside allocations are only allowed for objects that are associated
763: ** with a particular database connection. Hence, schema information cannot
764: ** be stored in lookaside because in shared cache mode the schema information
765: ** is shared by multiple database connections. Therefore, while parsing
766: ** schema information, the Lookaside.bEnabled flag is cleared so that
767: ** lookaside allocations are not used to construct the schema objects.
768: */
769: struct Lookaside {
770: u16 sz; /* Size of each buffer in bytes */
771: u8 bEnabled; /* False to disable new lookaside allocations */
772: u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
773: int nOut; /* Number of buffers currently checked out */
774: int mxOut; /* Highwater mark for nOut */
775: int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
776: LookasideSlot *pFree; /* List of available buffers */
777: void *pStart; /* First byte of available memory space */
778: void *pEnd; /* First byte past end of available space */
779: };
780: struct LookasideSlot {
781: LookasideSlot *pNext; /* Next buffer in the list of free buffers */
782: };
783:
784: /*
785: ** A hash table for function definitions.
786: **
787: ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
788: ** Collisions are on the FuncDef.pHash chain.
789: */
790: struct FuncDefHash {
791: FuncDef *a[23]; /* Hash table for functions */
792: };
793:
794: /*
795: ** Each database connection is an instance of the following structure.
796: **
797: ** The sqlite.lastRowid records the last insert rowid generated by an
798: ** insert statement. Inserts on views do not affect its value. Each
799: ** trigger has its own context, so that lastRowid can be updated inside
800: ** triggers as usual. The previous value will be restored once the trigger
801: ** exits. Upon entering a before or instead of trigger, lastRowid is no
802: ** longer (since after version 2.8.12) reset to -1.
803: **
804: ** The sqlite.nChange does not count changes within triggers and keeps no
805: ** context. It is reset at start of sqlite3_exec.
806: ** The sqlite.lsChange represents the number of changes made by the last
807: ** insert, update, or delete statement. It remains constant throughout the
808: ** length of a statement and is then updated by OP_SetCounts. It keeps a
809: ** context stack just like lastRowid so that the count of changes
810: ** within a trigger is not seen outside the trigger. Changes to views do not
811: ** affect the value of lsChange.
812: ** The sqlite.csChange keeps track of the number of current changes (since
813: ** the last statement) and is used to update sqlite_lsChange.
814: **
815: ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
816: ** store the most recent error code and, if applicable, string. The
817: ** internal function sqlite3Error() is used to set these variables
818: ** consistently.
819: */
820: struct sqlite3 {
821: sqlite3_vfs *pVfs; /* OS Interface */
822: int nDb; /* Number of backends currently in use */
823: Db *aDb; /* All backends */
824: int flags; /* Miscellaneous flags. See below */
825: unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
826: int errCode; /* Most recent error code (SQLITE_*) */
827: int errMask; /* & result codes with this before returning */
828: u8 autoCommit; /* The auto-commit flag. */
829: u8 temp_store; /* 1: file 2: memory 0: default */
830: u8 mallocFailed; /* True if we have seen a malloc failure */
831: u8 dfltLockMode; /* Default locking-mode for attached dbs */
832: signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
833: u8 suppressErr; /* Do not issue error messages if true */
834: u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
835: int nextPagesize; /* Pagesize after VACUUM if >0 */
836: int nTable; /* Number of tables in the database */
837: CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
838: i64 lastRowid; /* ROWID of most recent insert (see above) */
839: u32 magic; /* Magic number for detect library misuse */
840: int nChange; /* Value returned by sqlite3_changes() */
841: int nTotalChange; /* Value returned by sqlite3_total_changes() */
842: sqlite3_mutex *mutex; /* Connection mutex */
843: int aLimit[SQLITE_N_LIMIT]; /* Limits */
844: struct sqlite3InitInfo { /* Information used during initialization */
845: int iDb; /* When back is being initialized */
846: int newTnum; /* Rootpage of table being initialized */
847: u8 busy; /* TRUE if currently initializing */
848: u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
849: } init;
850: int nExtension; /* Number of loaded extensions */
851: void **aExtension; /* Array of shared library handles */
852: struct Vdbe *pVdbe; /* List of active virtual machines */
853: int activeVdbeCnt; /* Number of VDBEs currently executing */
854: int writeVdbeCnt; /* Number of active VDBEs that are writing */
855: int vdbeExecCnt; /* Number of nested calls to VdbeExec() */
856: void (*xTrace)(void*,const char*); /* Trace function */
857: void *pTraceArg; /* Argument to the trace function */
858: void (*xProfile)(void*,const char*,u64); /* Profiling function */
859: void *pProfileArg; /* Argument to profile function */
860: void *pCommitArg; /* Argument to xCommitCallback() */
861: int (*xCommitCallback)(void*); /* Invoked at every commit. */
862: void *pRollbackArg; /* Argument to xRollbackCallback() */
863: void (*xRollbackCallback)(void*); /* Invoked at every commit. */
864: void *pUpdateArg;
865: void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
866: #ifndef SQLITE_OMIT_WAL
867: int (*xWalCallback)(void *, sqlite3 *, const char *, int);
868: void *pWalArg;
869: #endif
870: void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
871: void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
872: void *pCollNeededArg;
873: sqlite3_value *pErr; /* Most recent error message */
874: char *zErrMsg; /* Most recent error message (UTF-8 encoded) */
875: char *zErrMsg16; /* Most recent error message (UTF-16 encoded) */
876: union {
877: volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
878: double notUsed1; /* Spacer */
879: } u1;
880: Lookaside lookaside; /* Lookaside malloc configuration */
881: #ifndef SQLITE_OMIT_AUTHORIZATION
882: int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
883: /* Access authorization function */
884: void *pAuthArg; /* 1st argument to the access auth function */
885: #endif
886: #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
887: int (*xProgress)(void *); /* The progress callback */
888: void *pProgressArg; /* Argument to the progress callback */
889: int nProgressOps; /* Number of opcodes for progress callback */
890: #endif
891: #ifndef SQLITE_OMIT_VIRTUALTABLE
892: Hash aModule; /* populated by sqlite3_create_module() */
893: VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
894: VTable **aVTrans; /* Virtual tables with open transactions */
895: int nVTrans; /* Allocated size of aVTrans */
896: VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
897: #endif
898: FuncDefHash aFunc; /* Hash table of connection functions */
899: Hash aCollSeq; /* All collating sequences */
900: BusyHandler busyHandler; /* Busy callback */
901: int busyTimeout; /* Busy handler timeout, in msec */
902: Db aDbStatic[2]; /* Static space for the 2 default backends */
903: Savepoint *pSavepoint; /* List of active savepoints */
904: int nSavepoint; /* Number of non-transaction savepoints */
905: int nStatement; /* Number of nested statement-transactions */
906: u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
907: i64 nDeferredCons; /* Net deferred constraints this transaction. */
908: int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
909:
910: #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
911: /* The following variables are all protected by the STATIC_MASTER
912: ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
913: **
914: ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
915: ** unlock so that it can proceed.
916: **
917: ** When X.pBlockingConnection==Y, that means that something that X tried
918: ** tried to do recently failed with an SQLITE_LOCKED error due to locks
919: ** held by Y.
920: */
921: sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
922: sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
923: void *pUnlockArg; /* Argument to xUnlockNotify */
924: void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
925: sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
926: #endif
927: };
928:
929: /*
930: ** A macro to discover the encoding of a database.
931: */
932: #define ENC(db) ((db)->aDb[0].pSchema->enc)
933:
934: /*
935: ** Possible values for the sqlite3.flags.
936: */
937: #define SQLITE_VdbeTrace 0x00000100 /* True to trace VDBE execution */
938: #define SQLITE_InternChanges 0x00000200 /* Uncommitted Hash table changes */
939: #define SQLITE_FullColNames 0x00000400 /* Show full column names on SELECT */
940: #define SQLITE_ShortColNames 0x00000800 /* Show short columns names */
941: #define SQLITE_CountRows 0x00001000 /* Count rows changed by INSERT, */
942: /* DELETE, or UPDATE and return */
943: /* the count using a callback. */
944: #define SQLITE_NullCallback 0x00002000 /* Invoke the callback once if the */
945: /* result set is empty */
946: #define SQLITE_SqlTrace 0x00004000 /* Debug print SQL as it executes */
947: #define SQLITE_VdbeListing 0x00008000 /* Debug listings of VDBE programs */
948: #define SQLITE_WriteSchema 0x00010000 /* OK to update SQLITE_MASTER */
949: #define SQLITE_NoReadlock 0x00020000 /* Readlocks are omitted when
950: ** accessing read-only databases */
951: #define SQLITE_IgnoreChecks 0x00040000 /* Do not enforce check constraints */
952: #define SQLITE_ReadUncommitted 0x0080000 /* For shared-cache mode */
953: #define SQLITE_LegacyFileFmt 0x00100000 /* Create new databases in format 1 */
954: #define SQLITE_FullFSync 0x00200000 /* Use full fsync on the backend */
955: #define SQLITE_CkptFullFSync 0x00400000 /* Use full fsync for checkpoint */
956: #define SQLITE_RecoveryMode 0x00800000 /* Ignore schema errors */
957: #define SQLITE_ReverseOrder 0x01000000 /* Reverse unordered SELECTs */
958: #define SQLITE_RecTriggers 0x02000000 /* Enable recursive triggers */
959: #define SQLITE_ForeignKeys 0x04000000 /* Enforce foreign key constraints */
960: #define SQLITE_AutoIndex 0x08000000 /* Enable automatic indexes */
961: #define SQLITE_PreferBuiltin 0x10000000 /* Preference to built-in funcs */
962: #define SQLITE_LoadExtension 0x20000000 /* Enable load_extension */
963: #define SQLITE_EnableTrigger 0x40000000 /* True to enable triggers */
964:
965: /*
966: ** Bits of the sqlite3.flags field that are used by the
967: ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
968: ** These must be the low-order bits of the flags field.
969: */
970: #define SQLITE_QueryFlattener 0x01 /* Disable query flattening */
971: #define SQLITE_ColumnCache 0x02 /* Disable the column cache */
972: #define SQLITE_IndexSort 0x04 /* Disable indexes for sorting */
973: #define SQLITE_IndexSearch 0x08 /* Disable indexes for searching */
974: #define SQLITE_IndexCover 0x10 /* Disable index covering table */
975: #define SQLITE_GroupByOrder 0x20 /* Disable GROUPBY cover of ORDERBY */
976: #define SQLITE_FactorOutConst 0x40 /* Disable factoring out constants */
977: #define SQLITE_IdxRealAsInt 0x80 /* Store REAL as INT in indices */
978: #define SQLITE_DistinctOpt 0x80 /* DISTINCT using indexes */
979: #define SQLITE_OptMask 0xff /* Mask of all disablable opts */
980:
981: /*
982: ** Possible values for the sqlite.magic field.
983: ** The numbers are obtained at random and have no special meaning, other
984: ** than being distinct from one another.
985: */
986: #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
987: #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
988: #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
989: #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
990: #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
991:
992: /*
993: ** Each SQL function is defined by an instance of the following
994: ** structure. A pointer to this structure is stored in the sqlite.aFunc
995: ** hash table. When multiple functions have the same name, the hash table
996: ** points to a linked list of these structures.
997: */
998: struct FuncDef {
999: i16 nArg; /* Number of arguments. -1 means unlimited */
1000: u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
1001: u8 flags; /* Some combination of SQLITE_FUNC_* */
1002: void *pUserData; /* User data parameter */
1003: FuncDef *pNext; /* Next function with same name */
1004: void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
1005: void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
1006: void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
1007: char *zName; /* SQL name of the function. */
1008: FuncDef *pHash; /* Next with a different name but the same hash */
1009: FuncDestructor *pDestructor; /* Reference counted destructor function */
1010: };
1011:
1012: /*
1013: ** This structure encapsulates a user-function destructor callback (as
1014: ** configured using create_function_v2()) and a reference counter. When
1015: ** create_function_v2() is called to create a function with a destructor,
1016: ** a single object of this type is allocated. FuncDestructor.nRef is set to
1017: ** the number of FuncDef objects created (either 1 or 3, depending on whether
1018: ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
1019: ** member of each of the new FuncDef objects is set to point to the allocated
1020: ** FuncDestructor.
1021: **
1022: ** Thereafter, when one of the FuncDef objects is deleted, the reference
1023: ** count on this object is decremented. When it reaches 0, the destructor
1024: ** is invoked and the FuncDestructor structure freed.
1025: */
1026: struct FuncDestructor {
1027: int nRef;
1028: void (*xDestroy)(void *);
1029: void *pUserData;
1030: };
1031:
1032: /*
1033: ** Possible values for FuncDef.flags
1034: */
1035: #define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */
1036: #define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */
1037: #define SQLITE_FUNC_EPHEM 0x04 /* Ephemeral. Delete with VDBE */
1038: #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
1039: #define SQLITE_FUNC_PRIVATE 0x10 /* Allowed for internal use only */
1040: #define SQLITE_FUNC_COUNT 0x20 /* Built-in count(*) aggregate */
1041: #define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
1042:
1043: /*
1044: ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
1045: ** used to create the initializers for the FuncDef structures.
1046: **
1047: ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
1048: ** Used to create a scalar function definition of a function zName
1049: ** implemented by C function xFunc that accepts nArg arguments. The
1050: ** value passed as iArg is cast to a (void*) and made available
1051: ** as the user-data (sqlite3_user_data()) for the function. If
1052: ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
1053: **
1054: ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
1055: ** Used to create an aggregate function definition implemented by
1056: ** the C functions xStep and xFinal. The first four parameters
1057: ** are interpreted in the same way as the first 4 parameters to
1058: ** FUNCTION().
1059: **
1060: ** LIKEFUNC(zName, nArg, pArg, flags)
1061: ** Used to create a scalar function definition of a function zName
1062: ** that accepts nArg arguments and is implemented by a call to C
1063: ** function likeFunc. Argument pArg is cast to a (void *) and made
1064: ** available as the function user-data (sqlite3_user_data()). The
1065: ** FuncDef.flags variable is set to the value passed as the flags
1066: ** parameter.
1067: */
1068: #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
1069: {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
1070: SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
1071: #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
1072: {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
1073: pArg, 0, xFunc, 0, 0, #zName, 0, 0}
1074: #define LIKEFUNC(zName, nArg, arg, flags) \
1075: {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
1076: #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
1077: {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
1078: SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
1079:
1080: /*
1081: ** All current savepoints are stored in a linked list starting at
1082: ** sqlite3.pSavepoint. The first element in the list is the most recently
1083: ** opened savepoint. Savepoints are added to the list by the vdbe
1084: ** OP_Savepoint instruction.
1085: */
1086: struct Savepoint {
1087: char *zName; /* Savepoint name (nul-terminated) */
1088: i64 nDeferredCons; /* Number of deferred fk violations */
1089: Savepoint *pNext; /* Parent savepoint (if any) */
1090: };
1091:
1092: /*
1093: ** The following are used as the second parameter to sqlite3Savepoint(),
1094: ** and as the P1 argument to the OP_Savepoint instruction.
1095: */
1096: #define SAVEPOINT_BEGIN 0
1097: #define SAVEPOINT_RELEASE 1
1098: #define SAVEPOINT_ROLLBACK 2
1099:
1100:
1101: /*
1102: ** Each SQLite module (virtual table definition) is defined by an
1103: ** instance of the following structure, stored in the sqlite3.aModule
1104: ** hash table.
1105: */
1106: struct Module {
1107: const sqlite3_module *pModule; /* Callback pointers */
1108: const char *zName; /* Name passed to create_module() */
1109: void *pAux; /* pAux passed to create_module() */
1110: void (*xDestroy)(void *); /* Module destructor function */
1111: };
1112:
1113: /*
1114: ** information about each column of an SQL table is held in an instance
1115: ** of this structure.
1116: */
1117: struct Column {
1118: char *zName; /* Name of this column */
1119: Expr *pDflt; /* Default value of this column */
1120: char *zDflt; /* Original text of the default value */
1121: char *zType; /* Data type for this column */
1122: char *zColl; /* Collating sequence. If NULL, use the default */
1123: u8 notNull; /* True if there is a NOT NULL constraint */
1124: u8 isPrimKey; /* True if this column is part of the PRIMARY KEY */
1125: char affinity; /* One of the SQLITE_AFF_... values */
1126: #ifndef SQLITE_OMIT_VIRTUALTABLE
1127: u8 isHidden; /* True if this column is 'hidden' */
1128: #endif
1129: };
1130:
1131: /*
1132: ** A "Collating Sequence" is defined by an instance of the following
1133: ** structure. Conceptually, a collating sequence consists of a name and
1134: ** a comparison routine that defines the order of that sequence.
1135: **
1136: ** There may two separate implementations of the collation function, one
1137: ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
1138: ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
1139: ** native byte order. When a collation sequence is invoked, SQLite selects
1140: ** the version that will require the least expensive encoding
1141: ** translations, if any.
1142: **
1143: ** The CollSeq.pUser member variable is an extra parameter that passed in
1144: ** as the first argument to the UTF-8 comparison function, xCmp.
1145: ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
1146: ** xCmp16.
1147: **
1148: ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
1149: ** collating sequence is undefined. Indices built on an undefined
1150: ** collating sequence may not be read or written.
1151: */
1152: struct CollSeq {
1153: char *zName; /* Name of the collating sequence, UTF-8 encoded */
1154: u8 enc; /* Text encoding handled by xCmp() */
1155: void *pUser; /* First argument to xCmp() */
1156: int (*xCmp)(void*,int, const void*, int, const void*);
1157: void (*xDel)(void*); /* Destructor for pUser */
1158: };
1159:
1160: /*
1161: ** A sort order can be either ASC or DESC.
1162: */
1163: #define SQLITE_SO_ASC 0 /* Sort in ascending order */
1164: #define SQLITE_SO_DESC 1 /* Sort in ascending order */
1165:
1166: /*
1167: ** Column affinity types.
1168: **
1169: ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
1170: ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
1171: ** the speed a little by numbering the values consecutively.
1172: **
1173: ** But rather than start with 0 or 1, we begin with 'a'. That way,
1174: ** when multiple affinity types are concatenated into a string and
1175: ** used as the P4 operand, they will be more readable.
1176: **
1177: ** Note also that the numeric types are grouped together so that testing
1178: ** for a numeric type is a single comparison.
1179: */
1180: #define SQLITE_AFF_TEXT 'a'
1181: #define SQLITE_AFF_NONE 'b'
1182: #define SQLITE_AFF_NUMERIC 'c'
1183: #define SQLITE_AFF_INTEGER 'd'
1184: #define SQLITE_AFF_REAL 'e'
1185:
1186: #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
1187:
1188: /*
1189: ** The SQLITE_AFF_MASK values masks off the significant bits of an
1190: ** affinity value.
1191: */
1192: #define SQLITE_AFF_MASK 0x67
1193:
1194: /*
1195: ** Additional bit values that can be ORed with an affinity without
1196: ** changing the affinity.
1197: */
1198: #define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */
1199: #define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */
1200: #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
1201:
1202: /*
1203: ** An object of this type is created for each virtual table present in
1204: ** the database schema.
1205: **
1206: ** If the database schema is shared, then there is one instance of this
1207: ** structure for each database connection (sqlite3*) that uses the shared
1208: ** schema. This is because each database connection requires its own unique
1209: ** instance of the sqlite3_vtab* handle used to access the virtual table
1210: ** implementation. sqlite3_vtab* handles can not be shared between
1211: ** database connections, even when the rest of the in-memory database
1212: ** schema is shared, as the implementation often stores the database
1213: ** connection handle passed to it via the xConnect() or xCreate() method
1214: ** during initialization internally. This database connection handle may
1215: ** then be used by the virtual table implementation to access real tables
1216: ** within the database. So that they appear as part of the callers
1217: ** transaction, these accesses need to be made via the same database
1218: ** connection as that used to execute SQL operations on the virtual table.
1219: **
1220: ** All VTable objects that correspond to a single table in a shared
1221: ** database schema are initially stored in a linked-list pointed to by
1222: ** the Table.pVTable member variable of the corresponding Table object.
1223: ** When an sqlite3_prepare() operation is required to access the virtual
1224: ** table, it searches the list for the VTable that corresponds to the
1225: ** database connection doing the preparing so as to use the correct
1226: ** sqlite3_vtab* handle in the compiled query.
1227: **
1228: ** When an in-memory Table object is deleted (for example when the
1229: ** schema is being reloaded for some reason), the VTable objects are not
1230: ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
1231: ** immediately. Instead, they are moved from the Table.pVTable list to
1232: ** another linked list headed by the sqlite3.pDisconnect member of the
1233: ** corresponding sqlite3 structure. They are then deleted/xDisconnected
1234: ** next time a statement is prepared using said sqlite3*. This is done
1235: ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
1236: ** Refer to comments above function sqlite3VtabUnlockList() for an
1237: ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
1238: ** list without holding the corresponding sqlite3.mutex mutex.
1239: **
1240: ** The memory for objects of this type is always allocated by
1241: ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
1242: ** the first argument.
1243: */
1244: struct VTable {
1245: sqlite3 *db; /* Database connection associated with this table */
1246: Module *pMod; /* Pointer to module implementation */
1247: sqlite3_vtab *pVtab; /* Pointer to vtab instance */
1248: int nRef; /* Number of pointers to this structure */
1249: u8 bConstraint; /* True if constraints are supported */
1250: int iSavepoint; /* Depth of the SAVEPOINT stack */
1251: VTable *pNext; /* Next in linked list (see above) */
1252: };
1253:
1254: /*
1255: ** Each SQL table is represented in memory by an instance of the
1256: ** following structure.
1257: **
1258: ** Table.zName is the name of the table. The case of the original
1259: ** CREATE TABLE statement is stored, but case is not significant for
1260: ** comparisons.
1261: **
1262: ** Table.nCol is the number of columns in this table. Table.aCol is a
1263: ** pointer to an array of Column structures, one for each column.
1264: **
1265: ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
1266: ** the column that is that key. Otherwise Table.iPKey is negative. Note
1267: ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
1268: ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
1269: ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
1270: ** is generated for each row of the table. TF_HasPrimaryKey is set if
1271: ** the table has any PRIMARY KEY, INTEGER or otherwise.
1272: **
1273: ** Table.tnum is the page number for the root BTree page of the table in the
1274: ** database file. If Table.iDb is the index of the database table backend
1275: ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
1276: ** holds temporary tables and indices. If TF_Ephemeral is set
1277: ** then the table is stored in a file that is automatically deleted
1278: ** when the VDBE cursor to the table is closed. In this case Table.tnum
1279: ** refers VDBE cursor number that holds the table open, not to the root
1280: ** page number. Transient tables are used to hold the results of a
1281: ** sub-query that appears instead of a real table name in the FROM clause
1282: ** of a SELECT statement.
1283: */
1284: struct Table {
1285: char *zName; /* Name of the table or view */
1286: int iPKey; /* If not negative, use aCol[iPKey] as the primary key */
1287: int nCol; /* Number of columns in this table */
1288: Column *aCol; /* Information about each column */
1289: Index *pIndex; /* List of SQL indexes on this table. */
1290: int tnum; /* Root BTree node for this table (see note above) */
1291: tRowcnt nRowEst; /* Estimated rows in table - from sqlite_stat1 table */
1292: Select *pSelect; /* NULL for tables. Points to definition if a view. */
1293: u16 nRef; /* Number of pointers to this Table */
1294: u8 tabFlags; /* Mask of TF_* values */
1295: u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
1296: FKey *pFKey; /* Linked list of all foreign keys in this table */
1297: char *zColAff; /* String defining the affinity of each column */
1298: #ifndef SQLITE_OMIT_CHECK
1299: Expr *pCheck; /* The AND of all CHECK constraints */
1300: #endif
1301: #ifndef SQLITE_OMIT_ALTERTABLE
1302: int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
1303: #endif
1304: #ifndef SQLITE_OMIT_VIRTUALTABLE
1305: VTable *pVTable; /* List of VTable objects. */
1306: int nModuleArg; /* Number of arguments to the module */
1307: char **azModuleArg; /* Text of all module args. [0] is module name */
1308: #endif
1309: Trigger *pTrigger; /* List of triggers stored in pSchema */
1310: Schema *pSchema; /* Schema that contains this table */
1311: Table *pNextZombie; /* Next on the Parse.pZombieTab list */
1312: };
1313:
1314: /*
1315: ** Allowed values for Tabe.tabFlags.
1316: */
1317: #define TF_Readonly 0x01 /* Read-only system table */
1318: #define TF_Ephemeral 0x02 /* An ephemeral table */
1319: #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
1320: #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
1321: #define TF_Virtual 0x10 /* Is a virtual table */
1322: #define TF_NeedMetadata 0x20 /* aCol[].zType and aCol[].pColl missing */
1323:
1324:
1325:
1326: /*
1327: ** Test to see whether or not a table is a virtual table. This is
1328: ** done as a macro so that it will be optimized out when virtual
1329: ** table support is omitted from the build.
1330: */
1331: #ifndef SQLITE_OMIT_VIRTUALTABLE
1332: # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
1333: # define IsHiddenColumn(X) ((X)->isHidden)
1334: #else
1335: # define IsVirtual(X) 0
1336: # define IsHiddenColumn(X) 0
1337: #endif
1338:
1339: /*
1340: ** Each foreign key constraint is an instance of the following structure.
1341: **
1342: ** A foreign key is associated with two tables. The "from" table is
1343: ** the table that contains the REFERENCES clause that creates the foreign
1344: ** key. The "to" table is the table that is named in the REFERENCES clause.
1345: ** Consider this example:
1346: **
1347: ** CREATE TABLE ex1(
1348: ** a INTEGER PRIMARY KEY,
1349: ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
1350: ** );
1351: **
1352: ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
1353: **
1354: ** Each REFERENCES clause generates an instance of the following structure
1355: ** which is attached to the from-table. The to-table need not exist when
1356: ** the from-table is created. The existence of the to-table is not checked.
1357: */
1358: struct FKey {
1359: Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
1360: FKey *pNextFrom; /* Next foreign key in pFrom */
1361: char *zTo; /* Name of table that the key points to (aka: Parent) */
1362: FKey *pNextTo; /* Next foreign key on table named zTo */
1363: FKey *pPrevTo; /* Previous foreign key on table named zTo */
1364: int nCol; /* Number of columns in this key */
1365: /* EV: R-30323-21917 */
1366: u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
1367: u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
1368: Trigger *apTrigger[2]; /* Triggers for aAction[] actions */
1369: struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
1370: int iFrom; /* Index of column in pFrom */
1371: char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
1372: } aCol[1]; /* One entry for each of nCol column s */
1373: };
1374:
1375: /*
1376: ** SQLite supports many different ways to resolve a constraint
1377: ** error. ROLLBACK processing means that a constraint violation
1378: ** causes the operation in process to fail and for the current transaction
1379: ** to be rolled back. ABORT processing means the operation in process
1380: ** fails and any prior changes from that one operation are backed out,
1381: ** but the transaction is not rolled back. FAIL processing means that
1382: ** the operation in progress stops and returns an error code. But prior
1383: ** changes due to the same operation are not backed out and no rollback
1384: ** occurs. IGNORE means that the particular row that caused the constraint
1385: ** error is not inserted or updated. Processing continues and no error
1386: ** is returned. REPLACE means that preexisting database rows that caused
1387: ** a UNIQUE constraint violation are removed so that the new insert or
1388: ** update can proceed. Processing continues and no error is reported.
1389: **
1390: ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
1391: ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
1392: ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
1393: ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
1394: ** referenced table row is propagated into the row that holds the
1395: ** foreign key.
1396: **
1397: ** The following symbolic values are used to record which type
1398: ** of action to take.
1399: */
1400: #define OE_None 0 /* There is no constraint to check */
1401: #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
1402: #define OE_Abort 2 /* Back out changes but do no rollback transaction */
1403: #define OE_Fail 3 /* Stop the operation but leave all prior changes */
1404: #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
1405: #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
1406:
1407: #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
1408: #define OE_SetNull 7 /* Set the foreign key value to NULL */
1409: #define OE_SetDflt 8 /* Set the foreign key value to its default */
1410: #define OE_Cascade 9 /* Cascade the changes */
1411:
1412: #define OE_Default 99 /* Do whatever the default action is */
1413:
1414:
1415: /*
1416: ** An instance of the following structure is passed as the first
1417: ** argument to sqlite3VdbeKeyCompare and is used to control the
1418: ** comparison of the two index keys.
1419: */
1420: struct KeyInfo {
1421: sqlite3 *db; /* The database connection */
1422: u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
1423: u16 nField; /* Number of entries in aColl[] */
1424: u8 *aSortOrder; /* Sort order for each column. May be NULL */
1425: CollSeq *aColl[1]; /* Collating sequence for each term of the key */
1426: };
1427:
1428: /*
1429: ** An instance of the following structure holds information about a
1430: ** single index record that has already been parsed out into individual
1431: ** values.
1432: **
1433: ** A record is an object that contains one or more fields of data.
1434: ** Records are used to store the content of a table row and to store
1435: ** the key of an index. A blob encoding of a record is created by
1436: ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
1437: ** OP_Column opcode.
1438: **
1439: ** This structure holds a record that has already been disassembled
1440: ** into its constituent fields.
1441: */
1442: struct UnpackedRecord {
1443: KeyInfo *pKeyInfo; /* Collation and sort-order information */
1444: u16 nField; /* Number of entries in apMem[] */
1445: u8 flags; /* Boolean settings. UNPACKED_... below */
1446: i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */
1447: Mem *aMem; /* Values */
1448: };
1449:
1450: /*
1451: ** Allowed values of UnpackedRecord.flags
1452: */
1453: #define UNPACKED_INCRKEY 0x01 /* Make this key an epsilon larger */
1454: #define UNPACKED_PREFIX_MATCH 0x02 /* A prefix match is considered OK */
1455: #define UNPACKED_PREFIX_SEARCH 0x04 /* Ignore final (rowid) field */
1456:
1457: /*
1458: ** Each SQL index is represented in memory by an
1459: ** instance of the following structure.
1460: **
1461: ** The columns of the table that are to be indexed are described
1462: ** by the aiColumn[] field of this structure. For example, suppose
1463: ** we have the following table and index:
1464: **
1465: ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
1466: ** CREATE INDEX Ex2 ON Ex1(c3,c1);
1467: **
1468: ** In the Table structure describing Ex1, nCol==3 because there are
1469: ** three columns in the table. In the Index structure describing
1470: ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
1471: ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
1472: ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
1473: ** The second column to be indexed (c1) has an index of 0 in
1474: ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
1475: **
1476: ** The Index.onError field determines whether or not the indexed columns
1477: ** must be unique and what to do if they are not. When Index.onError=OE_None,
1478: ** it means this is not a unique index. Otherwise it is a unique index
1479: ** and the value of Index.onError indicate the which conflict resolution
1480: ** algorithm to employ whenever an attempt is made to insert a non-unique
1481: ** element.
1482: */
1483: struct Index {
1484: char *zName; /* Name of this index */
1485: int nColumn; /* Number of columns in the table used by this index */
1486: int *aiColumn; /* Which columns are used by this index. 1st is 0 */
1487: tRowcnt *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
1488: Table *pTable; /* The SQL table being indexed */
1489: int tnum; /* Page containing root of this index in database file */
1490: u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
1491: u8 autoIndex; /* True if is automatically created (ex: by UNIQUE) */
1492: u8 bUnordered; /* Use this index for == or IN queries only */
1493: char *zColAff; /* String defining the affinity of each column */
1494: Index *pNext; /* The next index associated with the same table */
1495: Schema *pSchema; /* Schema containing this index */
1496: u8 *aSortOrder; /* Array of size Index.nColumn. True==DESC, False==ASC */
1497: char **azColl; /* Array of collation sequence names for index */
1498: #ifdef SQLITE_ENABLE_STAT3
1499: int nSample; /* Number of elements in aSample[] */
1500: tRowcnt avgEq; /* Average nEq value for key values not in aSample */
1501: IndexSample *aSample; /* Samples of the left-most key */
1502: #endif
1503: };
1504:
1505: /*
1506: ** Each sample stored in the sqlite_stat3 table is represented in memory
1507: ** using a structure of this type. See documentation at the top of the
1508: ** analyze.c source file for additional information.
1509: */
1510: struct IndexSample {
1511: union {
1512: char *z; /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
1513: double r; /* Value if eType is SQLITE_FLOAT */
1514: i64 i; /* Value if eType is SQLITE_INTEGER */
1515: } u;
1516: u8 eType; /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
1517: int nByte; /* Size in byte of text or blob. */
1518: tRowcnt nEq; /* Est. number of rows where the key equals this sample */
1519: tRowcnt nLt; /* Est. number of rows where key is less than this sample */
1520: tRowcnt nDLt; /* Est. number of distinct keys less than this sample */
1521: };
1522:
1523: /*
1524: ** Each token coming out of the lexer is an instance of
1525: ** this structure. Tokens are also used as part of an expression.
1526: **
1527: ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
1528: ** may contain random values. Do not make any assumptions about Token.dyn
1529: ** and Token.n when Token.z==0.
1530: */
1531: struct Token {
1532: const char *z; /* Text of the token. Not NULL-terminated! */
1533: unsigned int n; /* Number of characters in this token */
1534: };
1535:
1536: /*
1537: ** An instance of this structure contains information needed to generate
1538: ** code for a SELECT that contains aggregate functions.
1539: **
1540: ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
1541: ** pointer to this structure. The Expr.iColumn field is the index in
1542: ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
1543: ** code for that node.
1544: **
1545: ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
1546: ** original Select structure that describes the SELECT statement. These
1547: ** fields do not need to be freed when deallocating the AggInfo structure.
1548: */
1549: struct AggInfo {
1550: u8 directMode; /* Direct rendering mode means take data directly
1551: ** from source tables rather than from accumulators */
1552: u8 useSortingIdx; /* In direct mode, reference the sorting index rather
1553: ** than the source table */
1554: int sortingIdx; /* Cursor number of the sorting index */
1555: int sortingIdxPTab; /* Cursor number of pseudo-table */
1556: ExprList *pGroupBy; /* The group by clause */
1557: int nSortingColumn; /* Number of columns in the sorting index */
1558: struct AggInfo_col { /* For each column used in source tables */
1559: Table *pTab; /* Source table */
1560: int iTable; /* Cursor number of the source table */
1561: int iColumn; /* Column number within the source table */
1562: int iSorterColumn; /* Column number in the sorting index */
1563: int iMem; /* Memory location that acts as accumulator */
1564: Expr *pExpr; /* The original expression */
1565: } *aCol;
1566: int nColumn; /* Number of used entries in aCol[] */
1567: int nColumnAlloc; /* Number of slots allocated for aCol[] */
1568: int nAccumulator; /* Number of columns that show through to the output.
1569: ** Additional columns are used only as parameters to
1570: ** aggregate functions */
1571: struct AggInfo_func { /* For each aggregate function */
1572: Expr *pExpr; /* Expression encoding the function */
1573: FuncDef *pFunc; /* The aggregate function implementation */
1574: int iMem; /* Memory location that acts as accumulator */
1575: int iDistinct; /* Ephemeral table used to enforce DISTINCT */
1576: } *aFunc;
1577: int nFunc; /* Number of entries in aFunc[] */
1578: int nFuncAlloc; /* Number of slots allocated for aFunc[] */
1579: };
1580:
1581: /*
1582: ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
1583: ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
1584: ** than 32767 we have to make it 32-bit. 16-bit is preferred because
1585: ** it uses less memory in the Expr object, which is a big memory user
1586: ** in systems with lots of prepared statements. And few applications
1587: ** need more than about 10 or 20 variables. But some extreme users want
1588: ** to have prepared statements with over 32767 variables, and for them
1589: ** the option is available (at compile-time).
1590: */
1591: #if SQLITE_MAX_VARIABLE_NUMBER<=32767
1592: typedef i16 ynVar;
1593: #else
1594: typedef int ynVar;
1595: #endif
1596:
1597: /*
1598: ** Each node of an expression in the parse tree is an instance
1599: ** of this structure.
1600: **
1601: ** Expr.op is the opcode. The integer parser token codes are reused
1602: ** as opcodes here. For example, the parser defines TK_GE to be an integer
1603: ** code representing the ">=" operator. This same integer code is reused
1604: ** to represent the greater-than-or-equal-to operator in the expression
1605: ** tree.
1606: **
1607: ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
1608: ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
1609: ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
1610: ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
1611: ** then Expr.token contains the name of the function.
1612: **
1613: ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
1614: ** binary operator. Either or both may be NULL.
1615: **
1616: ** Expr.x.pList is a list of arguments if the expression is an SQL function,
1617: ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
1618: ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
1619: ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
1620: ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
1621: ** valid.
1622: **
1623: ** An expression of the form ID or ID.ID refers to a column in a table.
1624: ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
1625: ** the integer cursor number of a VDBE cursor pointing to that table and
1626: ** Expr.iColumn is the column number for the specific column. If the
1627: ** expression is used as a result in an aggregate SELECT, then the
1628: ** value is also stored in the Expr.iAgg column in the aggregate so that
1629: ** it can be accessed after all aggregates are computed.
1630: **
1631: ** If the expression is an unbound variable marker (a question mark
1632: ** character '?' in the original SQL) then the Expr.iTable holds the index
1633: ** number for that variable.
1634: **
1635: ** If the expression is a subquery then Expr.iColumn holds an integer
1636: ** register number containing the result of the subquery. If the
1637: ** subquery gives a constant result, then iTable is -1. If the subquery
1638: ** gives a different answer at different times during statement processing
1639: ** then iTable is the address of a subroutine that computes the subquery.
1640: **
1641: ** If the Expr is of type OP_Column, and the table it is selecting from
1642: ** is a disk table or the "old.*" pseudo-table, then pTab points to the
1643: ** corresponding table definition.
1644: **
1645: ** ALLOCATION NOTES:
1646: **
1647: ** Expr objects can use a lot of memory space in database schema. To
1648: ** help reduce memory requirements, sometimes an Expr object will be
1649: ** truncated. And to reduce the number of memory allocations, sometimes
1650: ** two or more Expr objects will be stored in a single memory allocation,
1651: ** together with Expr.zToken strings.
1652: **
1653: ** If the EP_Reduced and EP_TokenOnly flags are set when
1654: ** an Expr object is truncated. When EP_Reduced is set, then all
1655: ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
1656: ** are contained within the same memory allocation. Note, however, that
1657: ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
1658: ** allocated, regardless of whether or not EP_Reduced is set.
1659: */
1660: struct Expr {
1661: u8 op; /* Operation performed by this node */
1662: char affinity; /* The affinity of the column or 0 if not a column */
1663: u16 flags; /* Various flags. EP_* See below */
1664: union {
1665: char *zToken; /* Token value. Zero terminated and dequoted */
1666: int iValue; /* Non-negative integer value if EP_IntValue */
1667: } u;
1668:
1669: /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
1670: ** space is allocated for the fields below this point. An attempt to
1671: ** access them will result in a segfault or malfunction.
1672: *********************************************************************/
1673:
1674: Expr *pLeft; /* Left subnode */
1675: Expr *pRight; /* Right subnode */
1676: union {
1677: ExprList *pList; /* Function arguments or in "<expr> IN (<expr-list)" */
1678: Select *pSelect; /* Used for sub-selects and "<expr> IN (<select>)" */
1679: } x;
1680: CollSeq *pColl; /* The collation type of the column or 0 */
1681:
1682: /* If the EP_Reduced flag is set in the Expr.flags mask, then no
1683: ** space is allocated for the fields below this point. An attempt to
1684: ** access them will result in a segfault or malfunction.
1685: *********************************************************************/
1686:
1687: int iTable; /* TK_COLUMN: cursor number of table holding column
1688: ** TK_REGISTER: register number
1689: ** TK_TRIGGER: 1 -> new, 0 -> old */
1690: ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
1691: ** TK_VARIABLE: variable number (always >= 1). */
1692: i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
1693: i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
1694: u8 flags2; /* Second set of flags. EP2_... */
1695: u8 op2; /* If a TK_REGISTER, the original value of Expr.op */
1696: AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
1697: Table *pTab; /* Table for TK_COLUMN expressions. */
1698: #if SQLITE_MAX_EXPR_DEPTH>0
1699: int nHeight; /* Height of the tree headed by this node */
1700: #endif
1701: };
1702:
1703: /*
1704: ** The following are the meanings of bits in the Expr.flags field.
1705: */
1706: #define EP_FromJoin 0x0001 /* Originated in ON or USING clause of a join */
1707: #define EP_Agg 0x0002 /* Contains one or more aggregate functions */
1708: #define EP_Resolved 0x0004 /* IDs have been resolved to COLUMNs */
1709: #define EP_Error 0x0008 /* Expression contains one or more errors */
1710: #define EP_Distinct 0x0010 /* Aggregate function with DISTINCT keyword */
1711: #define EP_VarSelect 0x0020 /* pSelect is correlated, not constant */
1712: #define EP_DblQuoted 0x0040 /* token.z was originally in "..." */
1713: #define EP_InfixFunc 0x0080 /* True for an infix function: LIKE, GLOB, etc */
1714: #define EP_ExpCollate 0x0100 /* Collating sequence specified explicitly */
1715: #define EP_FixedDest 0x0200 /* Result needed in a specific register */
1716: #define EP_IntValue 0x0400 /* Integer value contained in u.iValue */
1717: #define EP_xIsSelect 0x0800 /* x.pSelect is valid (otherwise x.pList is) */
1718: #define EP_Hint 0x1000 /* Optimizer hint. Not required for correctness */
1719: #define EP_Reduced 0x2000 /* Expr struct is EXPR_REDUCEDSIZE bytes only */
1720: #define EP_TokenOnly 0x4000 /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
1721: #define EP_Static 0x8000 /* Held in memory not obtained from malloc() */
1722:
1723: /*
1724: ** The following are the meanings of bits in the Expr.flags2 field.
1725: */
1726: #define EP2_MallocedToken 0x0001 /* Need to sqlite3DbFree() Expr.zToken */
1727: #define EP2_Irreducible 0x0002 /* Cannot EXPRDUP_REDUCE this Expr */
1728:
1729: /*
1730: ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
1731: ** flag on an expression structure. This flag is used for VV&A only. The
1732: ** routine is implemented as a macro that only works when in debugging mode,
1733: ** so as not to burden production code.
1734: */
1735: #ifdef SQLITE_DEBUG
1736: # define ExprSetIrreducible(X) (X)->flags2 |= EP2_Irreducible
1737: #else
1738: # define ExprSetIrreducible(X)
1739: #endif
1740:
1741: /*
1742: ** These macros can be used to test, set, or clear bits in the
1743: ** Expr.flags field.
1744: */
1745: #define ExprHasProperty(E,P) (((E)->flags&(P))==(P))
1746: #define ExprHasAnyProperty(E,P) (((E)->flags&(P))!=0)
1747: #define ExprSetProperty(E,P) (E)->flags|=(P)
1748: #define ExprClearProperty(E,P) (E)->flags&=~(P)
1749:
1750: /*
1751: ** Macros to determine the number of bytes required by a normal Expr
1752: ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
1753: ** and an Expr struct with the EP_TokenOnly flag set.
1754: */
1755: #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
1756: #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
1757: #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
1758:
1759: /*
1760: ** Flags passed to the sqlite3ExprDup() function. See the header comment
1761: ** above sqlite3ExprDup() for details.
1762: */
1763: #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
1764:
1765: /*
1766: ** A list of expressions. Each expression may optionally have a
1767: ** name. An expr/name combination can be used in several ways, such
1768: ** as the list of "expr AS ID" fields following a "SELECT" or in the
1769: ** list of "ID = expr" items in an UPDATE. A list of expressions can
1770: ** also be used as the argument to a function, in which case the a.zName
1771: ** field is not used.
1772: */
1773: struct ExprList {
1774: int nExpr; /* Number of expressions on the list */
1775: int nAlloc; /* Number of entries allocated below */
1776: int iECursor; /* VDBE Cursor associated with this ExprList */
1777: struct ExprList_item {
1778: Expr *pExpr; /* The list of expressions */
1779: char *zName; /* Token associated with this expression */
1780: char *zSpan; /* Original text of the expression */
1781: u8 sortOrder; /* 1 for DESC or 0 for ASC */
1782: u8 done; /* A flag to indicate when processing is finished */
1783: u16 iOrderByCol; /* For ORDER BY, column number in result set */
1784: u16 iAlias; /* Index into Parse.aAlias[] for zName */
1785: } *a; /* One entry for each expression */
1786: };
1787:
1788: /*
1789: ** An instance of this structure is used by the parser to record both
1790: ** the parse tree for an expression and the span of input text for an
1791: ** expression.
1792: */
1793: struct ExprSpan {
1794: Expr *pExpr; /* The expression parse tree */
1795: const char *zStart; /* First character of input text */
1796: const char *zEnd; /* One character past the end of input text */
1797: };
1798:
1799: /*
1800: ** An instance of this structure can hold a simple list of identifiers,
1801: ** such as the list "a,b,c" in the following statements:
1802: **
1803: ** INSERT INTO t(a,b,c) VALUES ...;
1804: ** CREATE INDEX idx ON t(a,b,c);
1805: ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
1806: **
1807: ** The IdList.a.idx field is used when the IdList represents the list of
1808: ** column names after a table name in an INSERT statement. In the statement
1809: **
1810: ** INSERT INTO t(a,b,c) ...
1811: **
1812: ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
1813: */
1814: struct IdList {
1815: struct IdList_item {
1816: char *zName; /* Name of the identifier */
1817: int idx; /* Index in some Table.aCol[] of a column named zName */
1818: } *a;
1819: int nId; /* Number of identifiers on the list */
1820: int nAlloc; /* Number of entries allocated for a[] below */
1821: };
1822:
1823: /*
1824: ** The bitmask datatype defined below is used for various optimizations.
1825: **
1826: ** Changing this from a 64-bit to a 32-bit type limits the number of
1827: ** tables in a join to 32 instead of 64. But it also reduces the size
1828: ** of the library by 738 bytes on ix86.
1829: */
1830: typedef u64 Bitmask;
1831:
1832: /*
1833: ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
1834: */
1835: #define BMS ((int)(sizeof(Bitmask)*8))
1836:
1837: /*
1838: ** The following structure describes the FROM clause of a SELECT statement.
1839: ** Each table or subquery in the FROM clause is a separate element of
1840: ** the SrcList.a[] array.
1841: **
1842: ** With the addition of multiple database support, the following structure
1843: ** can also be used to describe a particular table such as the table that
1844: ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
1845: ** such a table must be a simple name: ID. But in SQLite, the table can
1846: ** now be identified by a database name, a dot, then the table name: ID.ID.
1847: **
1848: ** The jointype starts out showing the join type between the current table
1849: ** and the next table on the list. The parser builds the list this way.
1850: ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
1851: ** jointype expresses the join between the table and the previous table.
1852: **
1853: ** In the colUsed field, the high-order bit (bit 63) is set if the table
1854: ** contains more than 63 columns and the 64-th or later column is used.
1855: */
1856: struct SrcList {
1857: i16 nSrc; /* Number of tables or subqueries in the FROM clause */
1858: i16 nAlloc; /* Number of entries allocated in a[] below */
1859: struct SrcList_item {
1860: char *zDatabase; /* Name of database holding this table */
1861: char *zName; /* Name of the table */
1862: char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
1863: Table *pTab; /* An SQL table corresponding to zName */
1864: Select *pSelect; /* A SELECT statement used in place of a table name */
1865: int addrFillSub; /* Address of subroutine to manifest a subquery */
1866: int regReturn; /* Register holding return address of addrFillSub */
1867: u8 jointype; /* Type of join between this able and the previous */
1868: u8 notIndexed; /* True if there is a NOT INDEXED clause */
1869: u8 isCorrelated; /* True if sub-query is correlated */
1870: #ifndef SQLITE_OMIT_EXPLAIN
1871: u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
1872: #endif
1873: int iCursor; /* The VDBE cursor number used to access this table */
1874: Expr *pOn; /* The ON clause of a join */
1875: IdList *pUsing; /* The USING clause of a join */
1876: Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
1877: char *zIndex; /* Identifier from "INDEXED BY <zIndex>" clause */
1878: Index *pIndex; /* Index structure corresponding to zIndex, if any */
1879: } a[1]; /* One entry for each identifier on the list */
1880: };
1881:
1882: /*
1883: ** Permitted values of the SrcList.a.jointype field
1884: */
1885: #define JT_INNER 0x0001 /* Any kind of inner or cross join */
1886: #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
1887: #define JT_NATURAL 0x0004 /* True for a "natural" join */
1888: #define JT_LEFT 0x0008 /* Left outer join */
1889: #define JT_RIGHT 0x0010 /* Right outer join */
1890: #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
1891: #define JT_ERROR 0x0040 /* unknown or unsupported join type */
1892:
1893:
1894: /*
1895: ** A WherePlan object holds information that describes a lookup
1896: ** strategy.
1897: **
1898: ** This object is intended to be opaque outside of the where.c module.
1899: ** It is included here only so that that compiler will know how big it
1900: ** is. None of the fields in this object should be used outside of
1901: ** the where.c module.
1902: **
1903: ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
1904: ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true. And pVtabIdx
1905: ** is only used when wsFlags&WHERE_VIRTUALTABLE is true. It is never the
1906: ** case that more than one of these conditions is true.
1907: */
1908: struct WherePlan {
1909: u32 wsFlags; /* WHERE_* flags that describe the strategy */
1910: u32 nEq; /* Number of == constraints */
1911: double nRow; /* Estimated number of rows (for EQP) */
1912: union {
1913: Index *pIdx; /* Index when WHERE_INDEXED is true */
1914: struct WhereTerm *pTerm; /* WHERE clause term for OR-search */
1915: sqlite3_index_info *pVtabIdx; /* Virtual table index to use */
1916: } u;
1917: };
1918:
1919: /*
1920: ** For each nested loop in a WHERE clause implementation, the WhereInfo
1921: ** structure contains a single instance of this structure. This structure
1922: ** is intended to be private the the where.c module and should not be
1923: ** access or modified by other modules.
1924: **
1925: ** The pIdxInfo field is used to help pick the best index on a
1926: ** virtual table. The pIdxInfo pointer contains indexing
1927: ** information for the i-th table in the FROM clause before reordering.
1928: ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
1929: ** All other information in the i-th WhereLevel object for the i-th table
1930: ** after FROM clause ordering.
1931: */
1932: struct WhereLevel {
1933: WherePlan plan; /* query plan for this element of the FROM clause */
1934: int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
1935: int iTabCur; /* The VDBE cursor used to access the table */
1936: int iIdxCur; /* The VDBE cursor used to access pIdx */
1937: int addrBrk; /* Jump here to break out of the loop */
1938: int addrNxt; /* Jump here to start the next IN combination */
1939: int addrCont; /* Jump here to continue with the next loop cycle */
1940: int addrFirst; /* First instruction of interior of the loop */
1941: u8 iFrom; /* Which entry in the FROM clause */
1942: u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
1943: int p1, p2; /* Operands of the opcode used to ends the loop */
1944: union { /* Information that depends on plan.wsFlags */
1945: struct {
1946: int nIn; /* Number of entries in aInLoop[] */
1947: struct InLoop {
1948: int iCur; /* The VDBE cursor used by this IN operator */
1949: int addrInTop; /* Top of the IN loop */
1950: } *aInLoop; /* Information about each nested IN operator */
1951: } in; /* Used when plan.wsFlags&WHERE_IN_ABLE */
1952: } u;
1953:
1954: /* The following field is really not part of the current level. But
1955: ** we need a place to cache virtual table index information for each
1956: ** virtual table in the FROM clause and the WhereLevel structure is
1957: ** a convenient place since there is one WhereLevel for each FROM clause
1958: ** element.
1959: */
1960: sqlite3_index_info *pIdxInfo; /* Index info for n-th source table */
1961: };
1962:
1963: /*
1964: ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
1965: ** and the WhereInfo.wctrlFlags member.
1966: */
1967: #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
1968: #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
1969: #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
1970: #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
1971: #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
1972: #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
1973: #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
1974: #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
1975: #define WHERE_AND_ONLY 0x0080 /* Don't use indices for OR terms */
1976:
1977: /*
1978: ** The WHERE clause processing routine has two halves. The
1979: ** first part does the start of the WHERE loop and the second
1980: ** half does the tail of the WHERE loop. An instance of
1981: ** this structure is returned by the first half and passed
1982: ** into the second half to give some continuity.
1983: */
1984: struct WhereInfo {
1985: Parse *pParse; /* Parsing and code generating context */
1986: u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
1987: u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE or DELETE */
1988: u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
1989: u8 eDistinct;
1990: SrcList *pTabList; /* List of tables in the join */
1991: int iTop; /* The very beginning of the WHERE loop */
1992: int iContinue; /* Jump here to continue with next record */
1993: int iBreak; /* Jump here to break out of the loop */
1994: int nLevel; /* Number of nested loop */
1995: struct WhereClause *pWC; /* Decomposition of the WHERE clause */
1996: double savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
1997: double nRowOut; /* Estimated number of output rows */
1998: WhereLevel a[1]; /* Information about each nest loop in WHERE */
1999: };
2000:
2001: #define WHERE_DISTINCT_UNIQUE 1
2002: #define WHERE_DISTINCT_ORDERED 2
2003:
2004: /*
2005: ** A NameContext defines a context in which to resolve table and column
2006: ** names. The context consists of a list of tables (the pSrcList) field and
2007: ** a list of named expression (pEList). The named expression list may
2008: ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
2009: ** to the table being operated on by INSERT, UPDATE, or DELETE. The
2010: ** pEList corresponds to the result set of a SELECT and is NULL for
2011: ** other statements.
2012: **
2013: ** NameContexts can be nested. When resolving names, the inner-most
2014: ** context is searched first. If no match is found, the next outer
2015: ** context is checked. If there is still no match, the next context
2016: ** is checked. This process continues until either a match is found
2017: ** or all contexts are check. When a match is found, the nRef member of
2018: ** the context containing the match is incremented.
2019: **
2020: ** Each subquery gets a new NameContext. The pNext field points to the
2021: ** NameContext in the parent query. Thus the process of scanning the
2022: ** NameContext list corresponds to searching through successively outer
2023: ** subqueries looking for a match.
2024: */
2025: struct NameContext {
2026: Parse *pParse; /* The parser */
2027: SrcList *pSrcList; /* One or more tables used to resolve names */
2028: ExprList *pEList; /* Optional list of named expressions */
2029: int nRef; /* Number of names resolved by this context */
2030: int nErr; /* Number of errors encountered while resolving names */
2031: u8 allowAgg; /* Aggregate functions allowed here */
2032: u8 hasAgg; /* True if aggregates are seen */
2033: u8 isCheck; /* True if resolving names in a CHECK constraint */
2034: int nDepth; /* Depth of subquery recursion. 1 for no recursion */
2035: AggInfo *pAggInfo; /* Information about aggregates at this level */
2036: NameContext *pNext; /* Next outer name context. NULL for outermost */
2037: };
2038:
2039: /*
2040: ** An instance of the following structure contains all information
2041: ** needed to generate code for a single SELECT statement.
2042: **
2043: ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
2044: ** If there is a LIMIT clause, the parser sets nLimit to the value of the
2045: ** limit and nOffset to the value of the offset (or 0 if there is not
2046: ** offset). But later on, nLimit and nOffset become the memory locations
2047: ** in the VDBE that record the limit and offset counters.
2048: **
2049: ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
2050: ** These addresses must be stored so that we can go back and fill in
2051: ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
2052: ** the number of columns in P2 can be computed at the same time
2053: ** as the OP_OpenEphm instruction is coded because not
2054: ** enough information about the compound query is known at that point.
2055: ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
2056: ** for the result set. The KeyInfo for addrOpenTran[2] contains collating
2057: ** sequences for the ORDER BY clause.
2058: */
2059: struct Select {
2060: ExprList *pEList; /* The fields of the result */
2061: u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
2062: char affinity; /* MakeRecord with this affinity for SRT_Set */
2063: u16 selFlags; /* Various SF_* values */
2064: SrcList *pSrc; /* The FROM clause */
2065: Expr *pWhere; /* The WHERE clause */
2066: ExprList *pGroupBy; /* The GROUP BY clause */
2067: Expr *pHaving; /* The HAVING clause */
2068: ExprList *pOrderBy; /* The ORDER BY clause */
2069: Select *pPrior; /* Prior select in a compound select statement */
2070: Select *pNext; /* Next select to the left in a compound */
2071: Select *pRightmost; /* Right-most select in a compound select statement */
2072: Expr *pLimit; /* LIMIT expression. NULL means not used. */
2073: Expr *pOffset; /* OFFSET expression. NULL means not used. */
2074: int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
2075: int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */
2076: double nSelectRow; /* Estimated number of result rows */
2077: };
2078:
2079: /*
2080: ** Allowed values for Select.selFlags. The "SF" prefix stands for
2081: ** "Select Flag".
2082: */
2083: #define SF_Distinct 0x01 /* Output should be DISTINCT */
2084: #define SF_Resolved 0x02 /* Identifiers have been resolved */
2085: #define SF_Aggregate 0x04 /* Contains aggregate functions */
2086: #define SF_UsesEphemeral 0x08 /* Uses the OpenEphemeral opcode */
2087: #define SF_Expanded 0x10 /* sqlite3SelectExpand() called on this */
2088: #define SF_HasTypeInfo 0x20 /* FROM subqueries have Table metadata */
2089: #define SF_UseSorter 0x40 /* Sort using a sorter */
2090:
2091:
2092: /*
2093: ** The results of a select can be distributed in several ways. The
2094: ** "SRT" prefix means "SELECT Result Type".
2095: */
2096: #define SRT_Union 1 /* Store result as keys in an index */
2097: #define SRT_Except 2 /* Remove result from a UNION index */
2098: #define SRT_Exists 3 /* Store 1 if the result is not empty */
2099: #define SRT_Discard 4 /* Do not save the results anywhere */
2100:
2101: /* The ORDER BY clause is ignored for all of the above */
2102: #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
2103:
2104: #define SRT_Output 5 /* Output each row of result */
2105: #define SRT_Mem 6 /* Store result in a memory cell */
2106: #define SRT_Set 7 /* Store results as keys in an index */
2107: #define SRT_Table 8 /* Store result as data with an automatic rowid */
2108: #define SRT_EphemTab 9 /* Create transient tab and store like SRT_Table */
2109: #define SRT_Coroutine 10 /* Generate a single row of result */
2110:
2111: /*
2112: ** A structure used to customize the behavior of sqlite3Select(). See
2113: ** comments above sqlite3Select() for details.
2114: */
2115: typedef struct SelectDest SelectDest;
2116: struct SelectDest {
2117: u8 eDest; /* How to dispose of the results */
2118: u8 affinity; /* Affinity used when eDest==SRT_Set */
2119: int iParm; /* A parameter used by the eDest disposal method */
2120: int iMem; /* Base register where results are written */
2121: int nMem; /* Number of registers allocated */
2122: };
2123:
2124: /*
2125: ** During code generation of statements that do inserts into AUTOINCREMENT
2126: ** tables, the following information is attached to the Table.u.autoInc.p
2127: ** pointer of each autoincrement table to record some side information that
2128: ** the code generator needs. We have to keep per-table autoincrement
2129: ** information in case inserts are down within triggers. Triggers do not
2130: ** normally coordinate their activities, but we do need to coordinate the
2131: ** loading and saving of autoincrement information.
2132: */
2133: struct AutoincInfo {
2134: AutoincInfo *pNext; /* Next info block in a list of them all */
2135: Table *pTab; /* Table this info block refers to */
2136: int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
2137: int regCtr; /* Memory register holding the rowid counter */
2138: };
2139:
2140: /*
2141: ** Size of the column cache
2142: */
2143: #ifndef SQLITE_N_COLCACHE
2144: # define SQLITE_N_COLCACHE 10
2145: #endif
2146:
2147: /*
2148: ** At least one instance of the following structure is created for each
2149: ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
2150: ** statement. All such objects are stored in the linked list headed at
2151: ** Parse.pTriggerPrg and deleted once statement compilation has been
2152: ** completed.
2153: **
2154: ** A Vdbe sub-program that implements the body and WHEN clause of trigger
2155: ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
2156: ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
2157: ** The Parse.pTriggerPrg list never contains two entries with the same
2158: ** values for both pTrigger and orconf.
2159: **
2160: ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
2161: ** accessed (or set to 0 for triggers fired as a result of INSERT
2162: ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
2163: ** a mask of new.* columns used by the program.
2164: */
2165: struct TriggerPrg {
2166: Trigger *pTrigger; /* Trigger this program was coded from */
2167: int orconf; /* Default ON CONFLICT policy */
2168: SubProgram *pProgram; /* Program implementing pTrigger/orconf */
2169: u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
2170: TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
2171: };
2172:
2173: /*
2174: ** The yDbMask datatype for the bitmask of all attached databases.
2175: */
2176: #if SQLITE_MAX_ATTACHED>30
2177: typedef sqlite3_uint64 yDbMask;
2178: #else
2179: typedef unsigned int yDbMask;
2180: #endif
2181:
2182: /*
2183: ** An SQL parser context. A copy of this structure is passed through
2184: ** the parser and down into all the parser action routine in order to
2185: ** carry around information that is global to the entire parse.
2186: **
2187: ** The structure is divided into two parts. When the parser and code
2188: ** generate call themselves recursively, the first part of the structure
2189: ** is constant but the second part is reset at the beginning and end of
2190: ** each recursion.
2191: **
2192: ** The nTableLock and aTableLock variables are only used if the shared-cache
2193: ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
2194: ** used to store the set of table-locks required by the statement being
2195: ** compiled. Function sqlite3TableLock() is used to add entries to the
2196: ** list.
2197: */
2198: struct Parse {
2199: sqlite3 *db; /* The main database structure */
2200: int rc; /* Return code from execution */
2201: char *zErrMsg; /* An error message */
2202: Vdbe *pVdbe; /* An engine for executing database bytecode */
2203: u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
2204: u8 checkSchema; /* Causes schema cookie check after an error */
2205: u8 nested; /* Number of nested calls to the parser/code generator */
2206: u8 nTempReg; /* Number of temporary registers in aTempReg[] */
2207: u8 nTempInUse; /* Number of aTempReg[] currently checked out */
2208: int aTempReg[8]; /* Holding area for temporary registers */
2209: int nRangeReg; /* Size of the temporary register block */
2210: int iRangeReg; /* First register in temporary register block */
2211: int nErr; /* Number of errors seen */
2212: int nTab; /* Number of previously allocated VDBE cursors */
2213: int nMem; /* Number of memory cells used so far */
2214: int nSet; /* Number of sets used so far */
2215: int nOnce; /* Number of OP_Once instructions so far */
2216: int ckBase; /* Base register of data during check constraints */
2217: int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
2218: int iCacheCnt; /* Counter used to generate aColCache[].lru values */
2219: u8 nColCache; /* Number of entries in aColCache[] */
2220: u8 iColCache; /* Next entry in aColCache[] to replace */
2221: struct yColCache {
2222: int iTable; /* Table cursor number */
2223: int iColumn; /* Table column number */
2224: u8 tempReg; /* iReg is a temp register that needs to be freed */
2225: int iLevel; /* Nesting level */
2226: int iReg; /* Reg with value of this column. 0 means none. */
2227: int lru; /* Least recently used entry has the smallest value */
2228: } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
2229: yDbMask writeMask; /* Start a write transaction on these databases */
2230: yDbMask cookieMask; /* Bitmask of schema verified databases */
2231: u8 isMultiWrite; /* True if statement may affect/insert multiple rows */
2232: u8 mayAbort; /* True if statement may throw an ABORT exception */
2233: int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
2234: int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
2235: #ifndef SQLITE_OMIT_SHARED_CACHE
2236: int nTableLock; /* Number of locks in aTableLock */
2237: TableLock *aTableLock; /* Required table locks for shared-cache mode */
2238: #endif
2239: int regRowid; /* Register holding rowid of CREATE TABLE entry */
2240: int regRoot; /* Register holding root page number for new objects */
2241: AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
2242: int nMaxArg; /* Max args passed to user function by sub-program */
2243:
2244: /* Information used while coding trigger programs. */
2245: Parse *pToplevel; /* Parse structure for main program (or NULL) */
2246: Table *pTriggerTab; /* Table triggers are being coded for */
2247: u32 oldmask; /* Mask of old.* columns referenced */
2248: u32 newmask; /* Mask of new.* columns referenced */
2249: u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
2250: u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
2251: u8 disableTriggers; /* True to disable triggers */
2252: double nQueryLoop; /* Estimated number of iterations of a query */
2253:
2254: /* Above is constant between recursions. Below is reset before and after
2255: ** each recursion */
2256:
2257: int nVar; /* Number of '?' variables seen in the SQL so far */
2258: int nzVar; /* Number of available slots in azVar[] */
2259: char **azVar; /* Pointers to names of parameters */
2260: Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
2261: int nAlias; /* Number of aliased result set columns */
2262: int *aAlias; /* Register used to hold aliased result */
2263: u8 explain; /* True if the EXPLAIN flag is found on the query */
2264: Token sNameToken; /* Token with unqualified schema object name */
2265: Token sLastToken; /* The last token parsed */
2266: const char *zTail; /* All SQL text past the last semicolon parsed */
2267: Table *pNewTable; /* A table being constructed by CREATE TABLE */
2268: Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
2269: const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
2270: #ifndef SQLITE_OMIT_VIRTUALTABLE
2271: Token sArg; /* Complete text of a module argument */
2272: u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
2273: int nVtabLock; /* Number of virtual tables to lock */
2274: Table **apVtabLock; /* Pointer to virtual tables needing locking */
2275: #endif
2276: int nHeight; /* Expression tree height of current sub-select */
2277: Table *pZombieTab; /* List of Table objects to delete after code gen */
2278: TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
2279:
2280: #ifndef SQLITE_OMIT_EXPLAIN
2281: int iSelectId;
2282: int iNextSelectId;
2283: #endif
2284: };
2285:
2286: #ifdef SQLITE_OMIT_VIRTUALTABLE
2287: #define IN_DECLARE_VTAB 0
2288: #else
2289: #define IN_DECLARE_VTAB (pParse->declareVtab)
2290: #endif
2291:
2292: /*
2293: ** An instance of the following structure can be declared on a stack and used
2294: ** to save the Parse.zAuthContext value so that it can be restored later.
2295: */
2296: struct AuthContext {
2297: const char *zAuthContext; /* Put saved Parse.zAuthContext here */
2298: Parse *pParse; /* The Parse structure */
2299: };
2300:
2301: /*
2302: ** Bitfield flags for P5 value in OP_Insert and OP_Delete
2303: */
2304: #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
2305: #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
2306: #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
2307: #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
2308: #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
2309: #define OPFLAG_CLEARCACHE 0x20 /* Clear pseudo-table cache in OP_Column */
2310:
2311: /*
2312: * Each trigger present in the database schema is stored as an instance of
2313: * struct Trigger.
2314: *
2315: * Pointers to instances of struct Trigger are stored in two ways.
2316: * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
2317: * database). This allows Trigger structures to be retrieved by name.
2318: * 2. All triggers associated with a single table form a linked list, using the
2319: * pNext member of struct Trigger. A pointer to the first element of the
2320: * linked list is stored as the "pTrigger" member of the associated
2321: * struct Table.
2322: *
2323: * The "step_list" member points to the first element of a linked list
2324: * containing the SQL statements specified as the trigger program.
2325: */
2326: struct Trigger {
2327: char *zName; /* The name of the trigger */
2328: char *table; /* The table or view to which the trigger applies */
2329: u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
2330: u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
2331: Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
2332: IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
2333: the <column-list> is stored here */
2334: Schema *pSchema; /* Schema containing the trigger */
2335: Schema *pTabSchema; /* Schema containing the table */
2336: TriggerStep *step_list; /* Link list of trigger program steps */
2337: Trigger *pNext; /* Next trigger associated with the table */
2338: };
2339:
2340: /*
2341: ** A trigger is either a BEFORE or an AFTER trigger. The following constants
2342: ** determine which.
2343: **
2344: ** If there are multiple triggers, you might of some BEFORE and some AFTER.
2345: ** In that cases, the constants below can be ORed together.
2346: */
2347: #define TRIGGER_BEFORE 1
2348: #define TRIGGER_AFTER 2
2349:
2350: /*
2351: * An instance of struct TriggerStep is used to store a single SQL statement
2352: * that is a part of a trigger-program.
2353: *
2354: * Instances of struct TriggerStep are stored in a singly linked list (linked
2355: * using the "pNext" member) referenced by the "step_list" member of the
2356: * associated struct Trigger instance. The first element of the linked list is
2357: * the first step of the trigger-program.
2358: *
2359: * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
2360: * "SELECT" statement. The meanings of the other members is determined by the
2361: * value of "op" as follows:
2362: *
2363: * (op == TK_INSERT)
2364: * orconf -> stores the ON CONFLICT algorithm
2365: * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
2366: * this stores a pointer to the SELECT statement. Otherwise NULL.
2367: * target -> A token holding the quoted name of the table to insert into.
2368: * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
2369: * this stores values to be inserted. Otherwise NULL.
2370: * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
2371: * statement, then this stores the column-names to be
2372: * inserted into.
2373: *
2374: * (op == TK_DELETE)
2375: * target -> A token holding the quoted name of the table to delete from.
2376: * pWhere -> The WHERE clause of the DELETE statement if one is specified.
2377: * Otherwise NULL.
2378: *
2379: * (op == TK_UPDATE)
2380: * target -> A token holding the quoted name of the table to update rows of.
2381: * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
2382: * Otherwise NULL.
2383: * pExprList -> A list of the columns to update and the expressions to update
2384: * them to. See sqlite3Update() documentation of "pChanges"
2385: * argument.
2386: *
2387: */
2388: struct TriggerStep {
2389: u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
2390: u8 orconf; /* OE_Rollback etc. */
2391: Trigger *pTrig; /* The trigger that this step is a part of */
2392: Select *pSelect; /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
2393: Token target; /* Target table for DELETE, UPDATE, INSERT */
2394: Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
2395: ExprList *pExprList; /* SET clause for UPDATE. VALUES clause for INSERT */
2396: IdList *pIdList; /* Column names for INSERT */
2397: TriggerStep *pNext; /* Next in the link-list */
2398: TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
2399: };
2400:
2401: /*
2402: ** The following structure contains information used by the sqliteFix...
2403: ** routines as they walk the parse tree to make database references
2404: ** explicit.
2405: */
2406: typedef struct DbFixer DbFixer;
2407: struct DbFixer {
2408: Parse *pParse; /* The parsing context. Error messages written here */
2409: const char *zDb; /* Make sure all objects are contained in this database */
2410: const char *zType; /* Type of the container - used for error messages */
2411: const Token *pName; /* Name of the container - used for error messages */
2412: };
2413:
2414: /*
2415: ** An objected used to accumulate the text of a string where we
2416: ** do not necessarily know how big the string will be in the end.
2417: */
2418: struct StrAccum {
2419: sqlite3 *db; /* Optional database for lookaside. Can be NULL */
2420: char *zBase; /* A base allocation. Not from malloc. */
2421: char *zText; /* The string collected so far */
2422: int nChar; /* Length of the string so far */
2423: int nAlloc; /* Amount of space allocated in zText */
2424: int mxAlloc; /* Maximum allowed string length */
2425: u8 mallocFailed; /* Becomes true if any memory allocation fails */
2426: u8 useMalloc; /* 0: none, 1: sqlite3DbMalloc, 2: sqlite3_malloc */
2427: u8 tooBig; /* Becomes true if string size exceeds limits */
2428: };
2429:
2430: /*
2431: ** A pointer to this structure is used to communicate information
2432: ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
2433: */
2434: typedef struct {
2435: sqlite3 *db; /* The database being initialized */
2436: int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
2437: char **pzErrMsg; /* Error message stored here */
2438: int rc; /* Result code stored here */
2439: } InitData;
2440:
2441: /*
2442: ** Structure containing global configuration data for the SQLite library.
2443: **
2444: ** This structure also contains some state information.
2445: */
2446: struct Sqlite3Config {
2447: int bMemstat; /* True to enable memory status */
2448: int bCoreMutex; /* True to enable core mutexing */
2449: int bFullMutex; /* True to enable full mutexing */
2450: int bOpenUri; /* True to interpret filenames as URIs */
2451: int mxStrlen; /* Maximum string length */
2452: int szLookaside; /* Default lookaside buffer size */
2453: int nLookaside; /* Default lookaside buffer count */
2454: sqlite3_mem_methods m; /* Low-level memory allocation interface */
2455: sqlite3_mutex_methods mutex; /* Low-level mutex interface */
2456: sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
2457: void *pHeap; /* Heap storage space */
2458: int nHeap; /* Size of pHeap[] */
2459: int mnReq, mxReq; /* Min and max heap requests sizes */
2460: void *pScratch; /* Scratch memory */
2461: int szScratch; /* Size of each scratch buffer */
2462: int nScratch; /* Number of scratch buffers */
2463: void *pPage; /* Page cache memory */
2464: int szPage; /* Size of each page in pPage[] */
2465: int nPage; /* Number of pages in pPage[] */
2466: int mxParserStack; /* maximum depth of the parser stack */
2467: int sharedCacheEnabled; /* true if shared-cache mode enabled */
2468: /* The above might be initialized to non-zero. The following need to always
2469: ** initially be zero, however. */
2470: int isInit; /* True after initialization has finished */
2471: int inProgress; /* True while initialization in progress */
2472: int isMutexInit; /* True after mutexes are initialized */
2473: int isMallocInit; /* True after malloc is initialized */
2474: int isPCacheInit; /* True after malloc is initialized */
2475: sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
2476: int nRefInitMutex; /* Number of users of pInitMutex */
2477: void (*xLog)(void*,int,const char*); /* Function for logging */
2478: void *pLogArg; /* First argument to xLog() */
2479: int bLocaltimeFault; /* True to fail localtime() calls */
2480: };
2481:
2482: /*
2483: ** Context pointer passed down through the tree-walk.
2484: */
2485: struct Walker {
2486: int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
2487: int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
2488: Parse *pParse; /* Parser context. */
2489: union { /* Extra data for callback */
2490: NameContext *pNC; /* Naming context */
2491: int i; /* Integer value */
2492: } u;
2493: };
2494:
2495: /* Forward declarations */
2496: int sqlite3WalkExpr(Walker*, Expr*);
2497: int sqlite3WalkExprList(Walker*, ExprList*);
2498: int sqlite3WalkSelect(Walker*, Select*);
2499: int sqlite3WalkSelectExpr(Walker*, Select*);
2500: int sqlite3WalkSelectFrom(Walker*, Select*);
2501:
2502: /*
2503: ** Return code from the parse-tree walking primitives and their
2504: ** callbacks.
2505: */
2506: #define WRC_Continue 0 /* Continue down into children */
2507: #define WRC_Prune 1 /* Omit children but continue walking siblings */
2508: #define WRC_Abort 2 /* Abandon the tree walk */
2509:
2510: /*
2511: ** Assuming zIn points to the first byte of a UTF-8 character,
2512: ** advance zIn to point to the first byte of the next UTF-8 character.
2513: */
2514: #define SQLITE_SKIP_UTF8(zIn) { \
2515: if( (*(zIn++))>=0xc0 ){ \
2516: while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
2517: } \
2518: }
2519:
2520: /*
2521: ** The SQLITE_*_BKPT macros are substitutes for the error codes with
2522: ** the same name but without the _BKPT suffix. These macros invoke
2523: ** routines that report the line-number on which the error originated
2524: ** using sqlite3_log(). The routines also provide a convenient place
2525: ** to set a debugger breakpoint.
2526: */
2527: int sqlite3CorruptError(int);
2528: int sqlite3MisuseError(int);
2529: int sqlite3CantopenError(int);
2530: #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
2531: #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
2532: #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
2533:
2534:
2535: /*
2536: ** FTS4 is really an extension for FTS3. It is enabled using the
2537: ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
2538: ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
2539: */
2540: #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
2541: # define SQLITE_ENABLE_FTS3
2542: #endif
2543:
2544: /*
2545: ** The ctype.h header is needed for non-ASCII systems. It is also
2546: ** needed by FTS3 when FTS3 is included in the amalgamation.
2547: */
2548: #if !defined(SQLITE_ASCII) || \
2549: (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
2550: # include <ctype.h>
2551: #endif
2552:
2553: /*
2554: ** The following macros mimic the standard library functions toupper(),
2555: ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
2556: ** sqlite versions only work for ASCII characters, regardless of locale.
2557: */
2558: #ifdef SQLITE_ASCII
2559: # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
2560: # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
2561: # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
2562: # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
2563: # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
2564: # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
2565: # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
2566: #else
2567: # define sqlite3Toupper(x) toupper((unsigned char)(x))
2568: # define sqlite3Isspace(x) isspace((unsigned char)(x))
2569: # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
2570: # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
2571: # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
2572: # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
2573: # define sqlite3Tolower(x) tolower((unsigned char)(x))
2574: #endif
2575:
2576: /*
2577: ** Internal function prototypes
2578: */
2579: int sqlite3StrICmp(const char *, const char *);
2580: int sqlite3Strlen30(const char*);
2581: #define sqlite3StrNICmp sqlite3_strnicmp
2582:
2583: int sqlite3MallocInit(void);
2584: void sqlite3MallocEnd(void);
2585: void *sqlite3Malloc(int);
2586: void *sqlite3MallocZero(int);
2587: void *sqlite3DbMallocZero(sqlite3*, int);
2588: void *sqlite3DbMallocRaw(sqlite3*, int);
2589: char *sqlite3DbStrDup(sqlite3*,const char*);
2590: char *sqlite3DbStrNDup(sqlite3*,const char*, int);
2591: void *sqlite3Realloc(void*, int);
2592: void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
2593: void *sqlite3DbRealloc(sqlite3 *, void *, int);
2594: void sqlite3DbFree(sqlite3*, void*);
2595: int sqlite3MallocSize(void*);
2596: int sqlite3DbMallocSize(sqlite3*, void*);
2597: void *sqlite3ScratchMalloc(int);
2598: void sqlite3ScratchFree(void*);
2599: void *sqlite3PageMalloc(int);
2600: void sqlite3PageFree(void*);
2601: void sqlite3MemSetDefault(void);
2602: void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
2603: int sqlite3HeapNearlyFull(void);
2604:
2605: /*
2606: ** On systems with ample stack space and that support alloca(), make
2607: ** use of alloca() to obtain space for large automatic objects. By default,
2608: ** obtain space from malloc().
2609: **
2610: ** The alloca() routine never returns NULL. This will cause code paths
2611: ** that deal with sqlite3StackAlloc() failures to be unreachable.
2612: */
2613: #ifdef SQLITE_USE_ALLOCA
2614: # define sqlite3StackAllocRaw(D,N) alloca(N)
2615: # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
2616: # define sqlite3StackFree(D,P)
2617: #else
2618: # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
2619: # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
2620: # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
2621: #endif
2622:
2623: #ifdef SQLITE_ENABLE_MEMSYS3
2624: const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
2625: #endif
2626: #ifdef SQLITE_ENABLE_MEMSYS5
2627: const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
2628: #endif
2629:
2630:
2631: #ifndef SQLITE_MUTEX_OMIT
2632: sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
2633: sqlite3_mutex_methods const *sqlite3NoopMutex(void);
2634: sqlite3_mutex *sqlite3MutexAlloc(int);
2635: int sqlite3MutexInit(void);
2636: int sqlite3MutexEnd(void);
2637: #endif
2638:
2639: int sqlite3StatusValue(int);
2640: void sqlite3StatusAdd(int, int);
2641: void sqlite3StatusSet(int, int);
2642:
2643: #ifndef SQLITE_OMIT_FLOATING_POINT
2644: int sqlite3IsNaN(double);
2645: #else
2646: # define sqlite3IsNaN(X) 0
2647: #endif
2648:
2649: void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
2650: #ifndef SQLITE_OMIT_TRACE
2651: void sqlite3XPrintf(StrAccum*, const char*, ...);
2652: #endif
2653: char *sqlite3MPrintf(sqlite3*,const char*, ...);
2654: char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
2655: char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
2656: #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
2657: void sqlite3DebugPrintf(const char*, ...);
2658: #endif
2659: #if defined(SQLITE_TEST)
2660: void *sqlite3TestTextToPtr(const char*);
2661: #endif
2662:
2663: /* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
2664: #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
2665: void sqlite3ExplainBegin(Vdbe*);
2666: void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
2667: void sqlite3ExplainNL(Vdbe*);
2668: void sqlite3ExplainPush(Vdbe*);
2669: void sqlite3ExplainPop(Vdbe*);
2670: void sqlite3ExplainFinish(Vdbe*);
2671: void sqlite3ExplainSelect(Vdbe*, Select*);
2672: void sqlite3ExplainExpr(Vdbe*, Expr*);
2673: void sqlite3ExplainExprList(Vdbe*, ExprList*);
2674: const char *sqlite3VdbeExplanation(Vdbe*);
2675: #else
2676: # define sqlite3ExplainBegin(X)
2677: # define sqlite3ExplainSelect(A,B)
2678: # define sqlite3ExplainExpr(A,B)
2679: # define sqlite3ExplainExprList(A,B)
2680: # define sqlite3ExplainFinish(X)
2681: # define sqlite3VdbeExplanation(X) 0
2682: #endif
2683:
2684:
2685: void sqlite3SetString(char **, sqlite3*, const char*, ...);
2686: void sqlite3ErrorMsg(Parse*, const char*, ...);
2687: int sqlite3Dequote(char*);
2688: int sqlite3KeywordCode(const unsigned char*, int);
2689: int sqlite3RunParser(Parse*, const char*, char **);
2690: void sqlite3FinishCoding(Parse*);
2691: int sqlite3GetTempReg(Parse*);
2692: void sqlite3ReleaseTempReg(Parse*,int);
2693: int sqlite3GetTempRange(Parse*,int);
2694: void sqlite3ReleaseTempRange(Parse*,int,int);
2695: void sqlite3ClearTempRegCache(Parse*);
2696: Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
2697: Expr *sqlite3Expr(sqlite3*,int,const char*);
2698: void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
2699: Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
2700: Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
2701: Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
2702: void sqlite3ExprAssignVarNumber(Parse*, Expr*);
2703: void sqlite3ExprDelete(sqlite3*, Expr*);
2704: ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
2705: void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
2706: void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
2707: void sqlite3ExprListDelete(sqlite3*, ExprList*);
2708: int sqlite3Init(sqlite3*, char**);
2709: int sqlite3InitCallback(void*, int, char**, char**);
2710: void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
2711: void sqlite3ResetInternalSchema(sqlite3*, int);
2712: void sqlite3BeginParse(Parse*,int);
2713: void sqlite3CommitInternalChanges(sqlite3*);
2714: Table *sqlite3ResultSetOfSelect(Parse*,Select*);
2715: void sqlite3OpenMasterTable(Parse *, int);
2716: void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
2717: void sqlite3AddColumn(Parse*,Token*);
2718: void sqlite3AddNotNull(Parse*, int);
2719: void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
2720: void sqlite3AddCheckConstraint(Parse*, Expr*);
2721: void sqlite3AddColumnType(Parse*,Token*);
2722: void sqlite3AddDefaultValue(Parse*,ExprSpan*);
2723: void sqlite3AddCollateType(Parse*, Token*);
2724: void sqlite3EndTable(Parse*,Token*,Token*,Select*);
2725: int sqlite3ParseUri(const char*,const char*,unsigned int*,
2726: sqlite3_vfs**,char**,char **);
2727: int sqlite3CodeOnce(Parse *);
2728:
2729: Bitvec *sqlite3BitvecCreate(u32);
2730: int sqlite3BitvecTest(Bitvec*, u32);
2731: int sqlite3BitvecSet(Bitvec*, u32);
2732: void sqlite3BitvecClear(Bitvec*, u32, void*);
2733: void sqlite3BitvecDestroy(Bitvec*);
2734: u32 sqlite3BitvecSize(Bitvec*);
2735: int sqlite3BitvecBuiltinTest(int,int*);
2736:
2737: RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
2738: void sqlite3RowSetClear(RowSet*);
2739: void sqlite3RowSetInsert(RowSet*, i64);
2740: int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
2741: int sqlite3RowSetNext(RowSet*, i64*);
2742:
2743: void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
2744:
2745: #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
2746: int sqlite3ViewGetColumnNames(Parse*,Table*);
2747: #else
2748: # define sqlite3ViewGetColumnNames(A,B) 0
2749: #endif
2750:
2751: void sqlite3DropTable(Parse*, SrcList*, int, int);
2752: void sqlite3CodeDropTable(Parse*, Table*, int, int);
2753: void sqlite3DeleteTable(sqlite3*, Table*);
2754: #ifndef SQLITE_OMIT_AUTOINCREMENT
2755: void sqlite3AutoincrementBegin(Parse *pParse);
2756: void sqlite3AutoincrementEnd(Parse *pParse);
2757: #else
2758: # define sqlite3AutoincrementBegin(X)
2759: # define sqlite3AutoincrementEnd(X)
2760: #endif
2761: void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
2762: void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
2763: IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
2764: int sqlite3IdListIndex(IdList*,const char*);
2765: SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
2766: SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
2767: SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
2768: Token*, Select*, Expr*, IdList*);
2769: void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
2770: int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
2771: void sqlite3SrcListShiftJoinType(SrcList*);
2772: void sqlite3SrcListAssignCursors(Parse*, SrcList*);
2773: void sqlite3IdListDelete(sqlite3*, IdList*);
2774: void sqlite3SrcListDelete(sqlite3*, SrcList*);
2775: Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
2776: Token*, int, int);
2777: void sqlite3DropIndex(Parse*, SrcList*, int);
2778: int sqlite3Select(Parse*, Select*, SelectDest*);
2779: Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
2780: Expr*,ExprList*,int,Expr*,Expr*);
2781: void sqlite3SelectDelete(sqlite3*, Select*);
2782: Table *sqlite3SrcListLookup(Parse*, SrcList*);
2783: int sqlite3IsReadOnly(Parse*, Table*, int);
2784: void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
2785: #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
2786: Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
2787: #endif
2788: void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
2789: void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
2790: WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**,ExprList*,u16);
2791: void sqlite3WhereEnd(WhereInfo*);
2792: int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
2793: void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
2794: void sqlite3ExprCodeMove(Parse*, int, int, int);
2795: void sqlite3ExprCodeCopy(Parse*, int, int, int);
2796: void sqlite3ExprCacheStore(Parse*, int, int, int);
2797: void sqlite3ExprCachePush(Parse*);
2798: void sqlite3ExprCachePop(Parse*, int);
2799: void sqlite3ExprCacheRemove(Parse*, int, int);
2800: void sqlite3ExprCacheClear(Parse*);
2801: void sqlite3ExprCacheAffinityChange(Parse*, int, int);
2802: int sqlite3ExprCode(Parse*, Expr*, int);
2803: int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
2804: int sqlite3ExprCodeTarget(Parse*, Expr*, int);
2805: int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
2806: void sqlite3ExprCodeConstants(Parse*, Expr*);
2807: int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
2808: void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
2809: void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
2810: Table *sqlite3FindTable(sqlite3*,const char*, const char*);
2811: Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
2812: Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
2813: void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
2814: void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
2815: void sqlite3Vacuum(Parse*);
2816: int sqlite3RunVacuum(char**, sqlite3*);
2817: char *sqlite3NameFromToken(sqlite3*, Token*);
2818: int sqlite3ExprCompare(Expr*, Expr*);
2819: int sqlite3ExprListCompare(ExprList*, ExprList*);
2820: void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
2821: void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
2822: Vdbe *sqlite3GetVdbe(Parse*);
2823: void sqlite3PrngSaveState(void);
2824: void sqlite3PrngRestoreState(void);
2825: void sqlite3PrngResetState(void);
2826: void sqlite3RollbackAll(sqlite3*);
2827: void sqlite3CodeVerifySchema(Parse*, int);
2828: void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
2829: void sqlite3BeginTransaction(Parse*, int);
2830: void sqlite3CommitTransaction(Parse*);
2831: void sqlite3RollbackTransaction(Parse*);
2832: void sqlite3Savepoint(Parse*, int, Token*);
2833: void sqlite3CloseSavepoints(sqlite3 *);
2834: int sqlite3ExprIsConstant(Expr*);
2835: int sqlite3ExprIsConstantNotJoin(Expr*);
2836: int sqlite3ExprIsConstantOrFunction(Expr*);
2837: int sqlite3ExprIsInteger(Expr*, int*);
2838: int sqlite3ExprCanBeNull(const Expr*);
2839: void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
2840: int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
2841: int sqlite3IsRowid(const char*);
2842: void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
2843: void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
2844: int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
2845: void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
2846: int*,int,int,int,int,int*);
2847: void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
2848: int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
2849: void sqlite3BeginWriteOperation(Parse*, int, int);
2850: void sqlite3MultiWrite(Parse*);
2851: void sqlite3MayAbort(Parse*);
2852: void sqlite3HaltConstraint(Parse*, int, char*, int);
2853: Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
2854: ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
2855: SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
2856: IdList *sqlite3IdListDup(sqlite3*,IdList*);
2857: Select *sqlite3SelectDup(sqlite3*,Select*,int);
2858: void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
2859: FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
2860: void sqlite3RegisterBuiltinFunctions(sqlite3*);
2861: void sqlite3RegisterDateTimeFunctions(void);
2862: void sqlite3RegisterGlobalFunctions(void);
2863: int sqlite3SafetyCheckOk(sqlite3*);
2864: int sqlite3SafetyCheckSickOrOk(sqlite3*);
2865: void sqlite3ChangeCookie(Parse*, int);
2866:
2867: #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
2868: void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
2869: #endif
2870:
2871: #ifndef SQLITE_OMIT_TRIGGER
2872: void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
2873: Expr*,int, int);
2874: void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
2875: void sqlite3DropTrigger(Parse*, SrcList*, int);
2876: void sqlite3DropTriggerPtr(Parse*, Trigger*);
2877: Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
2878: Trigger *sqlite3TriggerList(Parse *, Table *);
2879: void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
2880: int, int, int);
2881: void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
2882: void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
2883: void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
2884: TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
2885: TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
2886: ExprList*,Select*,u8);
2887: TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
2888: TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
2889: void sqlite3DeleteTrigger(sqlite3*, Trigger*);
2890: void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
2891: u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
2892: # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
2893: #else
2894: # define sqlite3TriggersExist(B,C,D,E,F) 0
2895: # define sqlite3DeleteTrigger(A,B)
2896: # define sqlite3DropTriggerPtr(A,B)
2897: # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
2898: # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
2899: # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
2900: # define sqlite3TriggerList(X, Y) 0
2901: # define sqlite3ParseToplevel(p) p
2902: # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
2903: #endif
2904:
2905: int sqlite3JoinType(Parse*, Token*, Token*, Token*);
2906: void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
2907: void sqlite3DeferForeignKey(Parse*, int);
2908: #ifndef SQLITE_OMIT_AUTHORIZATION
2909: void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
2910: int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
2911: void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
2912: void sqlite3AuthContextPop(AuthContext*);
2913: int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
2914: #else
2915: # define sqlite3AuthRead(a,b,c,d)
2916: # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
2917: # define sqlite3AuthContextPush(a,b,c)
2918: # define sqlite3AuthContextPop(a) ((void)(a))
2919: #endif
2920: void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
2921: void sqlite3Detach(Parse*, Expr*);
2922: int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
2923: int sqlite3FixSrcList(DbFixer*, SrcList*);
2924: int sqlite3FixSelect(DbFixer*, Select*);
2925: int sqlite3FixExpr(DbFixer*, Expr*);
2926: int sqlite3FixExprList(DbFixer*, ExprList*);
2927: int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
2928: int sqlite3AtoF(const char *z, double*, int, u8);
2929: int sqlite3GetInt32(const char *, int*);
2930: int sqlite3Atoi(const char*);
2931: int sqlite3Utf16ByteLen(const void *pData, int nChar);
2932: int sqlite3Utf8CharLen(const char *pData, int nByte);
2933: u32 sqlite3Utf8Read(const u8*, const u8**);
2934:
2935: /*
2936: ** Routines to read and write variable-length integers. These used to
2937: ** be defined locally, but now we use the varint routines in the util.c
2938: ** file. Code should use the MACRO forms below, as the Varint32 versions
2939: ** are coded to assume the single byte case is already handled (which
2940: ** the MACRO form does).
2941: */
2942: int sqlite3PutVarint(unsigned char*, u64);
2943: int sqlite3PutVarint32(unsigned char*, u32);
2944: u8 sqlite3GetVarint(const unsigned char *, u64 *);
2945: u8 sqlite3GetVarint32(const unsigned char *, u32 *);
2946: int sqlite3VarintLen(u64 v);
2947:
2948: /*
2949: ** The header of a record consists of a sequence variable-length integers.
2950: ** These integers are almost always small and are encoded as a single byte.
2951: ** The following macros take advantage this fact to provide a fast encode
2952: ** and decode of the integers in a record header. It is faster for the common
2953: ** case where the integer is a single byte. It is a little slower when the
2954: ** integer is two or more bytes. But overall it is faster.
2955: **
2956: ** The following expressions are equivalent:
2957: **
2958: ** x = sqlite3GetVarint32( A, &B );
2959: ** x = sqlite3PutVarint32( A, B );
2960: **
2961: ** x = getVarint32( A, B );
2962: ** x = putVarint32( A, B );
2963: **
2964: */
2965: #define getVarint32(A,B) (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
2966: #define putVarint32(A,B) (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
2967: #define getVarint sqlite3GetVarint
2968: #define putVarint sqlite3PutVarint
2969:
2970:
2971: const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
2972: void sqlite3TableAffinityStr(Vdbe *, Table *);
2973: char sqlite3CompareAffinity(Expr *pExpr, char aff2);
2974: int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
2975: char sqlite3ExprAffinity(Expr *pExpr);
2976: int sqlite3Atoi64(const char*, i64*, int, u8);
2977: void sqlite3Error(sqlite3*, int, const char*,...);
2978: void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
2979: u8 sqlite3HexToInt(int h);
2980: int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
2981: const char *sqlite3ErrStr(int);
2982: int sqlite3ReadSchema(Parse *pParse);
2983: CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
2984: CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
2985: CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
2986: Expr *sqlite3ExprSetColl(Expr*, CollSeq*);
2987: Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
2988: int sqlite3CheckCollSeq(Parse *, CollSeq *);
2989: int sqlite3CheckObjectName(Parse *, const char *);
2990: void sqlite3VdbeSetChanges(sqlite3 *, int);
2991: int sqlite3AddInt64(i64*,i64);
2992: int sqlite3SubInt64(i64*,i64);
2993: int sqlite3MulInt64(i64*,i64);
2994: int sqlite3AbsInt32(int);
2995: #ifdef SQLITE_ENABLE_8_3_NAMES
2996: void sqlite3FileSuffix3(const char*, char*);
2997: #else
2998: # define sqlite3FileSuffix3(X,Y)
2999: #endif
3000: u8 sqlite3GetBoolean(const char *z);
3001:
3002: const void *sqlite3ValueText(sqlite3_value*, u8);
3003: int sqlite3ValueBytes(sqlite3_value*, u8);
3004: void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
3005: void(*)(void*));
3006: void sqlite3ValueFree(sqlite3_value*);
3007: sqlite3_value *sqlite3ValueNew(sqlite3 *);
3008: char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
3009: #ifdef SQLITE_ENABLE_STAT3
3010: char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
3011: #endif
3012: int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
3013: void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
3014: #ifndef SQLITE_AMALGAMATION
3015: extern const unsigned char sqlite3OpcodeProperty[];
3016: extern const unsigned char sqlite3UpperToLower[];
3017: extern const unsigned char sqlite3CtypeMap[];
3018: extern const Token sqlite3IntTokens[];
3019: extern SQLITE_WSD struct Sqlite3Config sqlite3Config;
3020: extern SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
3021: #ifndef SQLITE_OMIT_WSD
3022: extern int sqlite3PendingByte;
3023: #endif
3024: #endif
3025: void sqlite3RootPageMoved(sqlite3*, int, int, int);
3026: void sqlite3Reindex(Parse*, Token*, Token*);
3027: void sqlite3AlterFunctions(void);
3028: void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
3029: int sqlite3GetToken(const unsigned char *, int *);
3030: void sqlite3NestedParse(Parse*, const char*, ...);
3031: void sqlite3ExpirePreparedStatements(sqlite3*);
3032: int sqlite3CodeSubselect(Parse *, Expr *, int, int);
3033: void sqlite3SelectPrep(Parse*, Select*, NameContext*);
3034: int sqlite3ResolveExprNames(NameContext*, Expr*);
3035: void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
3036: int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
3037: void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
3038: void sqlite3AlterFinishAddColumn(Parse *, Token *);
3039: void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
3040: CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
3041: char sqlite3AffinityType(const char*);
3042: void sqlite3Analyze(Parse*, Token*, Token*);
3043: int sqlite3InvokeBusyHandler(BusyHandler*);
3044: int sqlite3FindDb(sqlite3*, Token*);
3045: int sqlite3FindDbName(sqlite3 *, const char *);
3046: int sqlite3AnalysisLoad(sqlite3*,int iDB);
3047: void sqlite3DeleteIndexSamples(sqlite3*,Index*);
3048: void sqlite3DefaultRowEst(Index*);
3049: void sqlite3RegisterLikeFunctions(sqlite3*, int);
3050: int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
3051: void sqlite3MinimumFileFormat(Parse*, int, int);
3052: void sqlite3SchemaClear(void *);
3053: Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
3054: int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
3055: KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
3056: int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
3057: void (*)(sqlite3_context*,int,sqlite3_value **),
3058: void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
3059: FuncDestructor *pDestructor
3060: );
3061: int sqlite3ApiExit(sqlite3 *db, int);
3062: int sqlite3OpenTempDatabase(Parse *);
3063:
3064: void sqlite3StrAccumInit(StrAccum*, char*, int, int);
3065: void sqlite3StrAccumAppend(StrAccum*,const char*,int);
3066: void sqlite3AppendSpace(StrAccum*,int);
3067: char *sqlite3StrAccumFinish(StrAccum*);
3068: void sqlite3StrAccumReset(StrAccum*);
3069: void sqlite3SelectDestInit(SelectDest*,int,int);
3070: Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
3071:
3072: void sqlite3BackupRestart(sqlite3_backup *);
3073: void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
3074:
3075: /*
3076: ** The interface to the LEMON-generated parser
3077: */
3078: void *sqlite3ParserAlloc(void*(*)(size_t));
3079: void sqlite3ParserFree(void*, void(*)(void*));
3080: void sqlite3Parser(void*, int, Token, Parse*);
3081: #ifdef YYTRACKMAXSTACKDEPTH
3082: int sqlite3ParserStackPeak(void*);
3083: #endif
3084:
3085: void sqlite3AutoLoadExtensions(sqlite3*);
3086: #ifndef SQLITE_OMIT_LOAD_EXTENSION
3087: void sqlite3CloseExtensions(sqlite3*);
3088: #else
3089: # define sqlite3CloseExtensions(X)
3090: #endif
3091:
3092: #ifndef SQLITE_OMIT_SHARED_CACHE
3093: void sqlite3TableLock(Parse *, int, int, u8, const char *);
3094: #else
3095: #define sqlite3TableLock(v,w,x,y,z)
3096: #endif
3097:
3098: #ifdef SQLITE_TEST
3099: int sqlite3Utf8To8(unsigned char*);
3100: #endif
3101:
3102: #ifdef SQLITE_OMIT_VIRTUALTABLE
3103: # define sqlite3VtabClear(Y)
3104: # define sqlite3VtabSync(X,Y) SQLITE_OK
3105: # define sqlite3VtabRollback(X)
3106: # define sqlite3VtabCommit(X)
3107: # define sqlite3VtabInSync(db) 0
3108: # define sqlite3VtabLock(X)
3109: # define sqlite3VtabUnlock(X)
3110: # define sqlite3VtabUnlockList(X)
3111: # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
3112: # define sqlite3GetVTable(X,Y) ((VTable*)0)
3113: #else
3114: void sqlite3VtabClear(sqlite3 *db, Table*);
3115: int sqlite3VtabSync(sqlite3 *db, char **);
3116: int sqlite3VtabRollback(sqlite3 *db);
3117: int sqlite3VtabCommit(sqlite3 *db);
3118: void sqlite3VtabLock(VTable *);
3119: void sqlite3VtabUnlock(VTable *);
3120: void sqlite3VtabUnlockList(sqlite3*);
3121: int sqlite3VtabSavepoint(sqlite3 *, int, int);
3122: VTable *sqlite3GetVTable(sqlite3*, Table*);
3123: # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
3124: #endif
3125: void sqlite3VtabMakeWritable(Parse*,Table*);
3126: void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
3127: void sqlite3VtabFinishParse(Parse*, Token*);
3128: void sqlite3VtabArgInit(Parse*);
3129: void sqlite3VtabArgExtend(Parse*, Token*);
3130: int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
3131: int sqlite3VtabCallConnect(Parse*, Table*);
3132: int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
3133: int sqlite3VtabBegin(sqlite3 *, VTable *);
3134: FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
3135: void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
3136: int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
3137: int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
3138: int sqlite3Reprepare(Vdbe*);
3139: void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
3140: CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
3141: int sqlite3TempInMemory(const sqlite3*);
3142: const char *sqlite3JournalModename(int);
3143: int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
3144: int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
3145:
3146: /* Declarations for functions in fkey.c. All of these are replaced by
3147: ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
3148: ** key functionality is available. If OMIT_TRIGGER is defined but
3149: ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
3150: ** this case foreign keys are parsed, but no other functionality is
3151: ** provided (enforcement of FK constraints requires the triggers sub-system).
3152: */
3153: #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
3154: void sqlite3FkCheck(Parse*, Table*, int, int);
3155: void sqlite3FkDropTable(Parse*, SrcList *, Table*);
3156: void sqlite3FkActions(Parse*, Table*, ExprList*, int);
3157: int sqlite3FkRequired(Parse*, Table*, int*, int);
3158: u32 sqlite3FkOldmask(Parse*, Table*);
3159: FKey *sqlite3FkReferences(Table *);
3160: #else
3161: #define sqlite3FkActions(a,b,c,d)
3162: #define sqlite3FkCheck(a,b,c,d)
3163: #define sqlite3FkDropTable(a,b,c)
3164: #define sqlite3FkOldmask(a,b) 0
3165: #define sqlite3FkRequired(a,b,c,d) 0
3166: #endif
3167: #ifndef SQLITE_OMIT_FOREIGN_KEY
3168: void sqlite3FkDelete(sqlite3 *, Table*);
3169: #else
3170: #define sqlite3FkDelete(a,b)
3171: #endif
3172:
3173:
3174: /*
3175: ** Available fault injectors. Should be numbered beginning with 0.
3176: */
3177: #define SQLITE_FAULTINJECTOR_MALLOC 0
3178: #define SQLITE_FAULTINJECTOR_COUNT 1
3179:
3180: /*
3181: ** The interface to the code in fault.c used for identifying "benign"
3182: ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
3183: ** is not defined.
3184: */
3185: #ifndef SQLITE_OMIT_BUILTIN_TEST
3186: void sqlite3BeginBenignMalloc(void);
3187: void sqlite3EndBenignMalloc(void);
3188: #else
3189: #define sqlite3BeginBenignMalloc()
3190: #define sqlite3EndBenignMalloc()
3191: #endif
3192:
3193: #define IN_INDEX_ROWID 1
3194: #define IN_INDEX_EPH 2
3195: #define IN_INDEX_INDEX 3
3196: int sqlite3FindInIndex(Parse *, Expr *, int*);
3197:
3198: #ifdef SQLITE_ENABLE_ATOMIC_WRITE
3199: int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
3200: int sqlite3JournalSize(sqlite3_vfs *);
3201: int sqlite3JournalCreate(sqlite3_file *);
3202: #else
3203: #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
3204: #endif
3205:
3206: void sqlite3MemJournalOpen(sqlite3_file *);
3207: int sqlite3MemJournalSize(void);
3208: int sqlite3IsMemJournal(sqlite3_file *);
3209:
3210: #if SQLITE_MAX_EXPR_DEPTH>0
3211: void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
3212: int sqlite3SelectExprHeight(Select *);
3213: int sqlite3ExprCheckHeight(Parse*, int);
3214: #else
3215: #define sqlite3ExprSetHeight(x,y)
3216: #define sqlite3SelectExprHeight(x) 0
3217: #define sqlite3ExprCheckHeight(x,y)
3218: #endif
3219:
3220: u32 sqlite3Get4byte(const u8*);
3221: void sqlite3Put4byte(u8*, u32);
3222:
3223: #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
3224: void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
3225: void sqlite3ConnectionUnlocked(sqlite3 *db);
3226: void sqlite3ConnectionClosed(sqlite3 *db);
3227: #else
3228: #define sqlite3ConnectionBlocked(x,y)
3229: #define sqlite3ConnectionUnlocked(x)
3230: #define sqlite3ConnectionClosed(x)
3231: #endif
3232:
3233: #ifdef SQLITE_DEBUG
3234: void sqlite3ParserTrace(FILE*, char *);
3235: #endif
3236:
3237: /*
3238: ** If the SQLITE_ENABLE IOTRACE exists then the global variable
3239: ** sqlite3IoTrace is a pointer to a printf-like routine used to
3240: ** print I/O tracing messages.
3241: */
3242: #ifdef SQLITE_ENABLE_IOTRACE
3243: # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
3244: void sqlite3VdbeIOTraceSql(Vdbe*);
3245: SQLITE_EXTERN void (*sqlite3IoTrace)(const char*,...);
3246: #else
3247: # define IOTRACE(A)
3248: # define sqlite3VdbeIOTraceSql(X)
3249: #endif
3250:
3251: /*
3252: ** These routines are available for the mem2.c debugging memory allocator
3253: ** only. They are used to verify that different "types" of memory
3254: ** allocations are properly tracked by the system.
3255: **
3256: ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
3257: ** the MEMTYPE_* macros defined below. The type must be a bitmask with
3258: ** a single bit set.
3259: **
3260: ** sqlite3MemdebugHasType() returns true if any of the bits in its second
3261: ** argument match the type set by the previous sqlite3MemdebugSetType().
3262: ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
3263: **
3264: ** sqlite3MemdebugNoType() returns true if none of the bits in its second
3265: ** argument match the type set by the previous sqlite3MemdebugSetType().
3266: **
3267: ** Perhaps the most important point is the difference between MEMTYPE_HEAP
3268: ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
3269: ** it might have been allocated by lookaside, except the allocation was
3270: ** too large or lookaside was already full. It is important to verify
3271: ** that allocations that might have been satisfied by lookaside are not
3272: ** passed back to non-lookaside free() routines. Asserts such as the
3273: ** example above are placed on the non-lookaside free() routines to verify
3274: ** this constraint.
3275: **
3276: ** All of this is no-op for a production build. It only comes into
3277: ** play when the SQLITE_MEMDEBUG compile-time option is used.
3278: */
3279: #ifdef SQLITE_MEMDEBUG
3280: void sqlite3MemdebugSetType(void*,u8);
3281: int sqlite3MemdebugHasType(void*,u8);
3282: int sqlite3MemdebugNoType(void*,u8);
3283: #else
3284: # define sqlite3MemdebugSetType(X,Y) /* no-op */
3285: # define sqlite3MemdebugHasType(X,Y) 1
3286: # define sqlite3MemdebugNoType(X,Y) 1
3287: #endif
3288: #define MEMTYPE_HEAP 0x01 /* General heap allocations */
3289: #define MEMTYPE_LOOKASIDE 0x02 /* Might have been lookaside memory */
3290: #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
3291: #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
3292: #define MEMTYPE_DB 0x10 /* Uses sqlite3DbMalloc, not sqlite_malloc */
3293:
3294: #endif /* _SQLITEINT_H_ */
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>