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